Programs & Examples On #Launching application

Xcode 9 error: "iPhone has denied the launch request"

It's an intermittent bug in Xcode - I just stopped and started all my devices and it magically worked (after messing about for 1/2 hour) I had upgraded MacOS overnight to 10.13.04 which obviously upset something! Xcode 9.3, iOS 11.3 watchOS 4.3

Copy/Paste from Excel to a web page

Maybe it would be better if you would read your excel file from PHP, and then either save it to a DB or do some processing on it.

here an in-dept tutorial on how to read and write Excel data with PHP:
http://www.ibm.com/developerworks/opensource/library/os-phpexcel/index.html

How to vertically align an image inside a div

I have been playing around with using padding for center alignment. You will need to define the top level outer-container size, but the inner container should resize, and you can set the padding at different percentage values.

jsfiddle

<div class='container'>
  <img src='image.jpg' />
</div>

.container {
  padding: 20%;
  background-color: blue;
}

img {
  width: 100%;
}

What's the source of Error: getaddrinfo EAI_AGAIN?

EAI_AGAIN is a DNS lookup timed out error, means it is a network connectivity error or proxy related error.

My main question is what does dns.js do?

  • The dns.js is there for node to get ip address of the domain(in brief).

Some more info: http://www.codingdefined.com/2015/06/nodejs-error-errno-eaiagain.html

The OutputPath property is not set for this project

had this problem as output from Azure DevOps after setting to build the .csproj instead of the .sln in the Build Pipeline.

The solution for me: Edit .csproj of the affected project, then copy your whole

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCpu' ">

Node, paste it, and then change the first line as followed:

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|any cpu' ">

The reason is, that in my case the error said

Please check to make sure that you have specified a valid combination of Configuration and Platform for this project.  Configuration='release'  Platform='any cpu'.  

Why Azure wants to use "any cpu" instead of the default "AnyCpu" is a mystery for me, but this hack works.

What is an abstract class in PHP?

An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.

The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class

Abstract must contains the abstract method and those methods must be defined in its inheriting class.

How to handle change of checkbox using jQuery?

Use :checkbox selector:

$(':checkbox').change(function() {

        // do stuff here. It will fire on any checkbox change

}); 

Code: http://jsfiddle.net/s6fe9/

What are the differences between a HashMap and a Hashtable in Java?

HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.

Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.

Getting error "The package appears to be corrupt" while installing apk file

None of the answer is working for me.

As the error message is package corrupt , I will have to run

  1. adb uninstall <package name>
  2. Run app again / use adb install

How to get $HOME directory of different user in bash script?

In BASH, you can find a user's $HOME directory by prefixing the user's login ID with a tilde character. For example:

$ echo ~bob

This will echo out user bob's $HOME directory.

However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo as user bob:

$ sudo -i -ubob -sfoo

This will start up a new shell, and the -i will simulate a login with the user's default environment and shell (which means the foo command will execute from the bob's$HOME` directory.)

Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers). However, this file usually has several examples you can use.

In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.

Replace multiple strings with multiple other strings

user regular function to define the pattern to replace and then use replace function to work on input string,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

Can't ignore UserInterfaceState.xcuserstate

For xcode 8.3.3 I just checked tried the above code and observe that, now in this casewe have to change the commands to like this

first you can create a .gitignore file by using

 touch .gitignore

after that you can delete all the userInterface file by using this command and by using this command it will respect your .gitignore file.

 git rm --cached [project].xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
 git commit -m "Removed file that shouldn't be tracked"

How to import jquery using ES6 syntax?

I wanted to use the alread-buildy jQuery (from jquery.org) and all the solutions mentioned here didn't work, how I fixed this issue was adding the following lines which should make it work on nearly every environment:

 export default  ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
    ? module.exports.noConflict(true)
    : ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)

iOS: how to perform a HTTP POST request?

I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after ASIHTTPRequest was abandoned. I highly recommend it. It's a great wrapper around NSURLConnection and allows for asynchronous calls, and basically anything you might need.

Is there a php echo/print equivalent in javascript

this is an another way:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

How do I turn a String into a InputStreamReader in java?

Same question as @Dan - why not StringReader ?

If it has to be InputStreamReader, then:

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

just add your .jar file in applet tag as an attribute as shown below:

<applet
    code="file.class"
    archive="file.jar"
    height=550 
    width=1100>         
</applet>

How can I give eclipse more memory than 512M?

While working on an enterprise project in STS (heavily Eclipse based) I was crashing constantly and STS plateaued at around 1GB of RAM usage. I couldn't add new .war files to my local tomcat server and after deleting the tomcat folder to re-add it, found I couldn't re-add it either. Essentially almost anything that required a new popup besides the main menus was causing STS to freeze up.

I edited the STS.ini (your Eclipse.ini can be configured similarly) to:

--launcher.XXMaxPermSize 1024M -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m

Rebooted STS immediately and saw it plateau at about 1.5 gigs before finally not crashing

Jquery: Find Text and replace

Joanna Avalos answer is better, Just note that I replaced .text() to .html(), otherwise, some of the html elements inside that will be destroyed.

SQL Server: Query fast, but slow from procedure

Though I'm usually against it (though in this case it seems that you have a genuine reason), have you tried providing any query hints on the SP version of the query? If SQL Server is preparing a different execution plan in those two instances, can you use a hint to tell it what index to use, so that the plan matches the first one?

For some examples, you can go here.

EDIT: If you can post your query plan here, perhaps we can identify some difference between the plans that's telling.

SECOND: Updated the link to be SQL-2000 specific. You'll have to scroll down a ways, but there's a second titled "Table Hints" that's what you're looking for.

THIRD: The "Bad" query seems to be ignoring the [IX_Openers_SessionGUID] on the "Openers" table - any chance adding an INDEX hint to force it to use that index will change things?

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I'm new to this topic, so I can't say a whole lot, but BLAS is pretty much the standard in scientific computing. BLAS is actually an API standard, which has many implementations. I'm honestly not sure which implementations are most popular or why.

If you want to also be able to do common linear algebra operations (solving systems, least squares regression, decomposition, etc.) look into LAPACK.

How to terminate a thread when main program ends?

Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt. Such termination functions may (though inevitably in the main thread!) call any stop function you require; together with the possibility of setting a thread as daemon, that gives you the tools to properly design the system functionality you need.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

add this two line in onCreate

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

Share method

File dir = new File(Environment.getExternalStorageDirectory(), "ColorStory");
File imgFile = new File(dir, "0.png");
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setType("image/*");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + imgFile));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(sendIntent, "Share images..."));

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Counting number of words in a file

Take a look at my solution here, it should work. The idea is to remove all the unwanted symbols from the words, then separate those words and store them in some other variable, i was using ArrayList. By adjusting the "excludedSymbols" variable you can add more symbols which you would like to be excluded from the words.

public static void countWords () {
    String textFileLocation ="c:\\yourFileLocation";
    String readWords ="";
    ArrayList<String> extractOnlyWordsFromTextFile = new ArrayList<>();
    // excludedSymbols can be extended to whatever you want to exclude from the file 
    String[] excludedSymbols = {" ", "," , "." , "/" , ":" , ";" , "<" , ">", "\n"};
    String readByteCharByChar = "";
    boolean testIfWord = false;


    try {
        InputStream inputStream = new FileInputStream(textFileLocation);
        byte byte1 = (byte) inputStream.read();
        while (byte1 != -1) {

            readByteCharByChar +=String.valueOf((char)byte1);
            for(int i=0;i<excludedSymbols.length;i++) {
            if(readByteCharByChar.equals(excludedSymbols[i])) {
                if(!readWords.equals("")) {
                extractOnlyWordsFromTextFile.add(readWords);
                }
                readWords ="";
                testIfWord = true;
                break;
            }
            }
            if(!testIfWord) {
                readWords+=(char)byte1;
            }
            readByteCharByChar = "";
            testIfWord = false;
            byte1 = (byte)inputStream.read();
            if(byte1 == -1 && !readWords.equals("")) {
                extractOnlyWordsFromTextFile.add(readWords);
            }
        }
        inputStream.close();
        System.out.println(extractOnlyWordsFromTextFile);
        System.out.println("The number of words in the choosen text file are: " + extractOnlyWordsFromTextFile.size());
    } catch (IOException ioException) {

        ioException.printStackTrace();
    }
}

htaccess Access-Control-Allow-Origin

Add an .htaccess file with the following directives to your fonts folder, if have problems accessing your fonts. Can easily be modified for use with .css or .js files.

<FilesMatch "\.(eot|ttf|otf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

Return the characters after Nth character in a string

Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4

=REPLACE(A1,1,4,"")

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

Parse JSON String to JSON Object in C#.NET

Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:

MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);

[Serializable]
public class MyClass
{
    public string myVar {get; set;}
    etc.
}

Call child component method from parent class - Angular

Consider the following example,

    import import { AfterViewInit, ViewChild } from '@angular/core';
    import { Component } from '@angular/core';
    import { CountdownTimerComponent }  from './countdown-timer.component';
    @Component({
        selector: 'app-countdown-parent-vc',
        templateUrl: 'app-countdown-parent-vc.html',
        styleUrl: [app-countdown-parent-vc.css]
    export class CreateCategoryComponent implements OnInit {
         @ViewChild(CountdownTimerComponent, {static: false})
         private timerComponent: CountdownTimerComponent;
         ngAfterViewInit() {
             this.timerComponent.startTimer();
         }

         submitNewCategory(){
            this.ngAfterViewInit();     
         }

Read more about @ViewChild here.

String.Replace(char, char) method in C#

string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);

Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.

Laravel Pagination links not including other GET parameters

Not append() but appends() So, right answer is:

{!! $records->appends(Input::except('page'))->links() !!}

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

Disabling submit button until all fields have values

Grave digging... I like a different approach:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)

Protractor : How to wait for page complete after click a button?

I typically just add something to the control flow, i.e.:

it('should navigate to the logfile page when attempting ' +
   'to access the user login page, after logging in', function() {
  userLoginPage.login(true);
  userLoginPage.get();
  logfilePage.expectLogfilePage();
});

logfilePage:

function login() {
  element(by.buttonText('Login')).click();

  // Adding this to the control flow will ensure the resulting page is loaded before moving on
  browser.getLocationAbsUrl();
}

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

IIS Manager in Windows 10

after turning IIS on (by going to Windows Features On/Off) type inetmgr in search bar or run

How to Truncate a string in PHP to the word closest to a certain number of characters?

Here is my function based on @Cd-MaN's approach.

function shorten($string, $width) {
  if(strlen($string) > $width) {
    $string = wordwrap($string, $width);
    $string = substr($string, 0, strpos($string, "\n"));
  }

  return $string;
}

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

Launch Bootstrap Modal on page load

In my case adding jQuery to display the modal didn't work:

$(document).ready(function() {
    $('#myModal').modal('show');
});

Which seemed to be because the modal had attribute aria-hidden="true":

<div class="modal fade" aria-hidden="true" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Removing that attribute was needed as well as the jQuery above:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

Note that I tried changing the modal classes from modal fade to modal fade in, and that didn't work. Also, changing the classes from modal fade to modal show stopped the modal from being able to be closed.

Converting a PDF to PNG

I'll add my solution, even thought his thread is old. Maybe this will help someone anyway.

First, I need to generate the PDF. I use XeLaTeX for that:

xelatex test.tex

Now, ImageMagick and GraphicMagic both parse parameters from left to right, so the leftmost parameter, will be executed first. I ended up using this sequence for optimal processing:

gm convert -trim -transparent white -background transparent -density 1200x1200 -resize 25% test.pdf test.png

It gives nice graphics on transparent background, trimmed to what is actually on the page. The -density and -resize parameters, give a better granularity, and increase overall resolution.

I suggest checking if the density can be decreased for you. It'll cut down converting time.

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

Reading values from DataTable

You can do it using the foreach loop

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

  foreach(DataRow row in dr_art_line_2.Rows)
  {
     QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
  }

How to set full calendar to a specific start date when it's initialized for the 1st time?

You have it backwards. Display the calendar first, and then call gotoDate.

$('#calendar').fullCalendar({
  // Options
});

$('#calendar').fullCalendar('gotoDate', currentDate);

Removing duplicate rows in Notepad++

If the rows are immediately after each other then you can use a regex replace:

Search Pattern: ^(.*\r?\n)(\1)+

Replace with: \1

PKIX path building failed: unable to find valid certification path to requested target

I've run into this a few times and it was due to a certificate chain being incomplete. If you are using the standard java trust store, it may not have a certificate that is needed to complete the certificate chain which is required to validate the certificate of the SSL site you are connecting to.

I ran into this problem with some DigiCert certificates and had to manually add the intermediary cert myself.

How to execute UNION without sorting? (SQL)

SELECT *, 1 AS sort_order
  FROM table1
 EXCEPT 
SELECT *, 1 AS sort_order
  FROM table2
UNION
SELECT *, 1 AS sort_order
  FROM table1
 INTERSECT 
SELECT *, 1 AS sort_order
  FROM table2
UNION
SELECT *, 2 AS sort_order
  FROM table2
 EXCEPT 
SELECT *, 2 AS sort_order
  FROM table1
ORDER BY sort_order;

But the real answer is: other than the ORDER BY clause, the sort order will by arbitrary and not guaranteed.

Center-align a HTML table

<table align="center"></table>

This works for me.

Add a column to existing table and uniquely number them on MS SQL Server

This will depend on the database but for SQL Server, this could be achieved as follows:

alter table Example
add NewColumn int identity(1,1)

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You only have to add group = 1 into the ggplot or geom_line aes().

For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.

Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.

Try this:

plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
         geom_point() +
         geom_line() +
         labs(x = "Year", y = "Particulate matter emissions (tons)", 
              title = "Motor vehicle emissions in Baltimore")

jQuery delete all table rows except first

I think this is more readable given the intent:

$('someTableSelector').children( 'tr:not(:first)' ).remove();

Using children also takes care of the case where the first row contains a table by limiting the depth of the search.

If you had an TBODY element, you can do this:

$("someTableSelector > tbody:last").children().remove();

If you have THEAD or TFOOT elements you'll need to do something different.

1030 Got error 28 from storage engine

Check your /backup to see if you can delete an older not needed backup.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Windows users, add this to PHP.ini:

curl.cainfo = "C:/cacert.pem";

Path needs to be changed to your own and you can download cacert.pem from a google search

(yes I know its a CentOS question)

String concatenation in Ruby

You can also use % as follows:

source = "#{ROOT_DIR}/%s/App.config" % project

This approach works with ' (single) quotation mark as well.

Reload browser window after POST without prompting user to resend POST data

To reload opener window with all parameters (not all be sent with window.location.href method and method with form.submit() is maybe one step to late) i prefer to use window.history method.

window.opener.history.go(0);

How to tag docker image with docker-compose

Original answer Nov 20 '15:

No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag> after you call docker-compose.

Now there's an option as described above or here

build: ./dir
image: webapp:tag

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

Android EditText view Floating Hint in Material Design

You need to add the following to your module build.gradle file:

implementation 'com.google.android.material:material:1.0.0'

And use com.google.android.material.textfield.TextInputLayout in your XML:

       <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/text_input_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/my_hint">

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="UserName"/>
   </com.google.android.material.textfield.TextInputLayout>

Crop image in PHP

HTML Code:-

enter code here
  <!DOCTYPE html>
  <html>
  <body>

  <form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="image" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
 </form>

 </body>
 </html>

upload.php

enter code here
<?php 
      $image = $_FILES;
      $NewImageName = rand(4,10000)."-". $image['image']['name'];
      $destination = realpath('../images/testing').'/';
      move_uploaded_file($image['image']['tmp_name'], $destination.$NewImageName);
      $image = imagecreatefromjpeg($destination.$NewImageName);
      $filename = $destination.$NewImageName;

      $thumb_width = 200;
      $thumb_height = 150;

      $width = imagesx($image);
      $height = imagesy($image);

      $original_aspect = $width / $height;
      $thumb_aspect = $thumb_width / $thumb_height;

      if ( $original_aspect >= $thumb_aspect )
      {
         // If image is wider than thumbnail (in aspect ratio sense)
         $new_height = $thumb_height;
         $new_width = $width / ($height / $thumb_height);
      }
      else
      {
         // If the thumbnail is wider than the image
         $new_width = $thumb_width;
         $new_height = $height / ($width / $thumb_width);
      }

      $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

      // Resize and crop
      imagecopyresampled($thumb,
                         $image,
                         0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                         0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                         0, 0,
                         $new_width, $new_height,
                         $width, $height);
      imagejpeg($thumb, $filename, 80);
      echo "cropped"; die;
      ?>  

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.

How do I read configuration settings from Symfony2 config.yml?

Rather than defining contact_email within app.config, define it in a parameters entry:

parameters:
    contact_email: [email protected]

You should find the call you are making within your controller now works.

Toggle show/hide on click with jQuery

Make use of jquery toggle function which do the task for you

.toggle() - Display or hide the matched elements.

$('#myelement').click(function(){
      $('#another-element').toggle('slow');
  });

How to write new line character to a file in Java

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

How to use SqlClient in ASP.NET Core?

I think you may have missed this part in the tutorial:

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

Alternate background colors for list items

Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.

<ul>
    <li class="even"><a href="link">Link 1</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li class="even"><a href="link">Link 3</a></li>
    <li class="odd"><a href="link">Link 4</a></li>
    <li class="even"><a href="link">Link 5</a></li>
</ul>

In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:

li.even { background-color: red; }
li.odd { background-color: blue; }

You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?

Execute SQLite script

There are many ways to do this, one way is:

sqlite3 auction.db

Followed by:

sqlite> .read create.sql

In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.

Java Synchronized list

Yes, Just be careful if you are also iterating over the list, because in this case you will need to synchronize on it. From the Javadoc:

It is imperative that the user manually synchronize on the returned list when iterating over it:

List list = Collections.synchronizedList(new ArrayList());
    ...
synchronized (list) {
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());
}

Or, you can use CopyOnWriteArrayList which is slower for writes but doesn't have this issue.

How to create dispatch queue in Swift 3

DispatchQueue.main.async(execute: {
   // code
})

AES Encrypt and Decrypt

CryptoSwift is very interesting project but for now it has some AES speed limitations. Be carefull if you need to do some serious crypto - it might be worth to go through the pain of bridge implemmenting CommonCrypto.

BigUps to Marcin for pureSwift implementation

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

How to drop all tables from a database with one SQL query?

The simplest way is to drop the whole database and create it once again:

drop database db_name
create database db_name

That's all.

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.

Select first 4 rows of a data.frame in R

Using the index:

df[1:4,]

Where the values in the parentheses can be interpreted as either logical, numeric, or character (matching the respective names):

df[row.index, column.index]

Read help(`[`) for more detail on this subject, and also read about index matrices in the Introduction to R.

How to detect if multiple keys are pressed at once using JavaScript?

You should use the keydown event to keep track of the keys pressed, and you should use the keyup event to keep track of when the keys are released.

See this example: http://jsfiddle.net/vor0nwe/mkHsU/

(Update: I’m reproducing the code here, in case jsfiddle.net bails:) The HTML:

<ul id="log">
    <li>List of keys:</li>
</ul>

...and the Javascript (using jQuery):

var log = $('#log')[0],
    pressedKeys = [];

$(document.body).keydown(function (evt) {
    var li = pressedKeys[evt.keyCode];
    if (!li) {
        li = log.appendChild(document.createElement('li'));
        pressedKeys[evt.keyCode] = li;
    }
    $(li).text('Down: ' + evt.keyCode);
    $(li).removeClass('key-up');
});

$(document.body).keyup(function (evt) {
    var li = pressedKeys[evt.keyCode];
    if (!li) {
       li = log.appendChild(document.createElement('li'));
    }
    $(li).text('Up: ' + evt.keyCode);
    $(li).addClass('key-up');
});

In that example, I’m using an array to keep track of which keys are being pressed. In a real application, you might want to delete each element once their associated key has been released.

Note that while I've used jQuery to make things easy for myself in this example, the concept works just as well when working in 'raw' Javascript.

Query to list number of records in each table in a database

I think that the shortest, fastest and simplest way would be:

SELECT
    object_name(object_id) AS [Table],
    SUM(row_count) AS [Count]
FROM
    sys.dm_db_partition_stats
WHERE
    --object_schema_name(object_id) = 'dbo' AND 
    index_id < 2
GROUP BY
    object_id

Lightbox to show videos from Youtube and Vimeo?

Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.

Detect if a jQuery UI dialog box is open

Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.

if ($('#mydialog').dialog('isOpen') === true) {
    // true
} else {
    // false
}

Initialize empty vector in structure - c++

How about

user r = {"",{}};

or

user r = {"",{'\0'}};

or

user r = {"",std::vector<unsigned char>()};

or

user r;

Pandas aggregate count distinct

How about either of:

>>> df
         date  duration user_id
0  2013-04-01        30    0001
1  2013-04-01        15    0001
2  2013-04-01        20    0002
3  2013-04-02        15    0002
4  2013-04-02        30    0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1

How to fix "containing working copy admin area is missing" in SVN?

For me, the same issue happened when I both:

  • deleted (--force) a .map file
  • added *.map to svn:ignore via svn propedit svn:ignore .

My solution was to:

  1. undo changes to the property
  2. commit changes to the files
  3. checkout a fresh copy of the repository (alas!)
  4. change the property and commit

Can I call a function of a shell script from another shell script?

The problem

The currenly accepted answer works only under important condition. Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source ./first.sh
func1 World

this works only if the first.sh is executed from within the same directory where the first.sh is located. Ie. if the current working path of shell is /foo, the attempt to run command

cd /foo
./bar/second.sh

prints error:

/foo/bar/second.sh: line 4: func1: command not found

That's because the source ./first.sh is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run

(cd /foo/bar; ./second.sh)

More generic solution

Given...

/foo/bar/first.sh:

function func1 {  
   echo "Hello $1"
}

and

/foo/bar/second.sh:

#!/bin/bash

source $(dirname "$0")/first.sh

func1 World

then

cd /foo
./bar/second.sh

prints

Hello World

How it works

  • $0 returns relative or absolute path to the executed script
  • dirname returns relative path to directory, where the $0 script exists
  • $( dirname "$0" ) the dirname "$0" command returns relative path to directory of executed script, which is then used as argument for source command
  • in "second.sh", /first.sh just appends the name of imported shell script
  • source loads content of specified file into current shell

How do I use the built in password reset/change views with my own templates

I was using this two lines in the url and the template from the admin what i was changing to my need

url(r'^change-password/$', 'django.contrib.auth.views.password_change', {
    'template_name': 'password_change_form.html'}, name="password-change"),
url(r'^change-password-done/$', 'django.contrib.auth.views.password_change_done', {
    'template_name': 'password_change_done.html'
    }, name="password-change-done")

How to declare array of zeros in python (or an array of a certain size)

Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

buckets = [[0 for col in range(5)] for row in range(10)]

to avoid reference sharing between the rows.

This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.

How to compare two vectors for equality element by element in C++?

Check std::mismatch method of C++.

comparing vectors has been discussed on DaniWeb forum and also answered.

C++: Comparing two vectors

Check the below SO post. will helpful for you. they have achieved the same with different-2 method.

Compare two vectors C++

Check if a row exists, otherwise insert

Full solution is below (including cursor structure). Many thanks to Cassius Porcus for the begin trans ... commit code from posting above.

declare @mystat6 bigint
declare @mystat6p varchar(50)
declare @mystat6b bigint

DECLARE mycur1 CURSOR for

 select result1,picture,bittot from  all_Tempnogos2results11

 OPEN mycur1

 FETCH NEXT FROM mycur1 INTO @mystat6, @mystat6p , @mystat6b

 WHILE @@Fetch_Status = 0
 BEGIN

 begin tran /* default read committed isolation level is fine */

 if not exists (select * from all_Tempnogos2results11_uniq with (updlock, rowlock, holdlock)
                     where all_Tempnogos2results11_uniq.result1 = @mystat6 
                        and all_Tempnogos2results11_uniq.bittot = @mystat6b )
     insert all_Tempnogos2results11_uniq values (@mystat6 , @mystat6p , @mystat6b)

 --else
 --  /* update */

 commit /* locks are released here */

 FETCH NEXT FROM mycur1 INTO @mystat6 , @mystat6p , @mystat6b

 END

 CLOSE mycur1

 DEALLOCATE mycur1
 go

How to combine two byte arrays

You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following

byte[] concatBytes = ArrayUtils.addAll(one,two);

How to update Ruby to 1.9.x on Mac?

With brew this is a one-liner:

(assuming that you have tapped homebrew/versions, which can be done by running brew tap homebrew/versions)

brew install ruby193

Worked out of the box for me on OS X 10.8.4. Or if you want 2.0, you just brew install ruby

More generally, brew search ruby shows you the different repos available, and if you want to get really specific you can use brew versions ruby and checkout a specific version instead.

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

Disable scrolling in webview?

Set a listener on your WebView:

webView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return(event.getAction() == MotionEvent.ACTION_MOVE));
            }
        });

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals 
    }
   }
 }

Key = Youtube videos all meta keys for youtube videos and value

"pip install unroll": "python setup.py egg_info" failed with error code 1

pip3 install --upgrade setuptools WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.

******To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.******

use python3 -m pip "command" eg: python3 -m pip install --user pyqt5

How to set UTF-8 encoding for a PHP file

Html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />

vs Php:

<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

How to replace part of string by position?

It's better to use the String.substr().

Like this:

ReplString = GivenStr.substr(0, PostostarRelStr)
           + GivenStr(PostostarRelStr, ReplString.lenght());

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

SQL Developer with JDK (64 bit) cannot find JVM

Today I try to use oracle client 64 and failed connect Connection Identifier which is defined at tnsnames.ora file. I assume that try to connect Oracle 32 Bit Server using SQL Developer 64 bit. That is why I install new jdk x86 and trying to change jdk path but this error happened:

msvcr100.dll error

Trying to download SQL Developer 32 Bit, but at the site said that the bundle support both 32 bit and 64 bit depend on java installed.

Windows 32-bit/64-bit: This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already on your machine.

My java home is 64 bit. New installed 32 bit jdk is not set at java home.

I need to open $User_dir\AppData\Roaming\sqldeveloper\version\product.conf

Remove line SetJavaHome C:\Program Files\Java\jdk1.8.0_201

Start sqldeveloper.exe instead of sqldeveloper64W.exe

New popup will shown and choose java home to new jdk version (32 bit mine) :

C:\Program Files (x86)\Java\jdk1.8.0_201

My fault, I pin sqldeveloper64W.exe to taskbar, why that error occured then after I move cursor and it was sqldeveloper64W.exe, I try to click sqldeveloper.exe, then I found that my setting is goes well.

So check it maybe it was happened on your system too. If sqldeveloper.exe does not working, try to choose sqldeveloper64W.exe.

Now I can call my Connection Identifier which is defined at tnsnames.ora using new setting SQL developer 32 bit mode.

Stop a gif animation onload, on mouseover start the activation

Adding a suffix like this:

$('#img_gif').attr('src','file.gif?' + Math.random());  

the browser is compelled to download a new image every time the user accesses the page. Moreover the client cache may be quickly filled.

Here follows the alternative solution I tested on Chrome 49 and Firefox 45.
In the css stylesheet set the display property as 'none', like this:

#img_gif{
  display:'none';
}

Outside the '$(document).ready' statement insert:

$(window).load(function(){ $('#img_gif').show(); });

Every time the user accesses the page, the animation will be started after the complete load of all the elements. This is the only way I found to sincronize gif and html5 animations.

Please note that:
The gif animation will not restart after refreshing the page (like pressing "F5").
The "$(document).ready" statement doesn't produce the same effect of "$(window).load".
The property "visibility" doesn't produce the same effect of "display".

How to send email from Terminal?

Go into Terminal and type man mail for help.

You will need to set SMTP up:

http://hints.macworld.com/article.php?story=20081217161612647

See also:

http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html

Eg:

mail -s "hello" "[email protected]" <<EOF
hello
world
EOF

This will send an email to [email protected] with the subject hello and the message

Hello

World

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

Remove CSS class from element with JavaScript (no jQuery)

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.


UPDATE: To support class names containing dash character, such as "My-Class", use

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

How to implement the Android ActionBar back button?

AndroidManifest file:

    <activity android:name=".activity.DetailsActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="br.com.halyson.materialdesign.activity.HomeActivity" />
    </activity>

add in DetailsActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);   
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

it's work :]

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

Procedure or function !!! has too many arguments specified

For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.

Just put use [DBName] on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.

How to take backup of a single table in a MySQL database?

just use mysqldump -u root database table or if using with password mysqldump -u root -p pass database table

Call method in directive controller from other controller

You could also expose the directive's controller to the parent scope, like ngForm with name attribute does: http://docs.angularjs.org/api/ng.directive:ngForm

Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview

In this example I have myDirective with dedicated controller with $clear method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')

Terminal Commands: For loop with echo

for ((i=0; i<=1000; i++)); do
    echo "http://example.com/$i.jpg"
done

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

How to store directory files listing into an array?

Try with:

#! /bin/bash

i=0
while read line
do
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -ls)

echo ${array[1]}

In your version, the while runs in a subshell, the environment variables you modify in the loop are not visible outside it.

(Do keep in mind that parsing the output of ls is generally not a good idea at all.)

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

Change value in a cell based on value in another cell

by typing yes it wont charge taxes, by typing no it will charge taxes.

=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to get all subsets of a set? (powerset)

def get_power_set(s):
  power_set=[[]]
  for elem in s:
    # iterate over the sub sets so far
    for sub_set in power_set:
      # add a new subset consisting of the subset at hand added elem
      power_set=power_set+[list(sub_set)+[elem]]
  return power_set

For example:

get_power_set([1,2,3])

yield

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

JavaScript function in href vs. onclick

I use

Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>

A long way around but it gets the job done. use an A style to simplify then it becomes:

<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style> 
<a nohref onClick="alert('Hello World')">HERE</a>

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Getting all selected checkboxes in an array

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();

How to go back (ctrl+z) in vi/vim

Just in normal mode press:

  • u - undo,
  • Ctrl + r - redo changes which were undone (undo the undos).

Undo and Redo

Which TensorFlow and CUDA version combinations are compatible?

I had a similar problem after upgrading to TF 2.0. The CUDA version that TF was reporting did not match what Ubuntu 18.04 thought I had installed. It said I was using CUDA 7.5.0, but apt thought I had the right version installed.

What I eventually had to do was grep recursively in /usr/local for CUDNN_MAJOR, and I found that /usr/local/cuda-10.0/targets/x86_64-linux/include/cudnn.h did indeed specify the version as 7.5.0.
/usr/local/cuda-10.1 got it right, and /usr/local/cuda pointed to /usr/local/cuda-10.1, so it was (and remains) a mystery to me why TF was looking at /usr/local/cuda-10.0.

Anyway, I just moved /usr/local/cuda-10.0 to /usr/local/old-cuda-10.0 so TF couldn't find it any more and everything then worked like a charm.

It was all very frustrating, and I still feel like I just did a random hack. But it worked :) and perhaps this will help someone with a similar issue.

Alternating Row Colors in Bootstrap 3 - No Table

I find that if I specify .row:nth-of-type(..), my other row's elements (for other formatting, etc) also get alternating colours. So rather, I'd define in my css an entirely new class:

.row-striped:nth-of-type(odd){
  background-color: #efefef;
}

.row-striped:nth-of-type(even){
  background-color: #ffffff;
}

So now, the alternating row colours will only apply to the row container, when I specify its class as .row-striped, and not the elements inside the row.

<!-- this entire row container is #efefef -->
<div class="row row-striped">
    <div class="form-group">
        <div class="col-sm-8"><h5>Field Greens with strawberry vinegrette</h5></div>
        <div class="col-sm-4">
            <input type="number" type="number" step="1" min="0"></input><small>$30/salad</small>
        </div>
    </div>
</div>

<!-- this entire row container is #ffffff -->
<div class="row row-striped">
    <div class="form-group">
        <div class="col-sm-8"><h5>Greek Salad</h5></div>
        <div class="col-sm-4">
            <input type="number" type="number" step="1" min="0"></input><small>$25/salad</small>
        </div>
    </div>
</div>

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Open a folder using Process.Start

Strange.

If it can't find explorer.exe, you should get an exception. If it can't find the folder, it should still open some folder (eg my Documents)

You say another copy of Explorer appears in the taskmanager, but you can't see it.

Is it possible that it is opening offscreen (ie another monitor)?

Or are you by any chance doing this in a non-interactive service?

Write Array to Excel Range

In my case, the program queries the database which returns a DataGridView. I then copy that to an array. I get the size of the just created array and then write the array to an Excel spreadsheet. This code outputs over 5000 lines of data in about two seconds.

//private System.Windows.Forms.DataGridView dgvResults;
dgvResults.DataSource = DB.getReport();

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    var dgArray = new object[dgvResults.RowCount, dgvResults.ColumnCount+1];
    foreach (DataGridViewRow i in dgvResults.Rows)
    {
        if (i.IsNewRow) continue;
        foreach (DataGridViewCell j in i.Cells)
        {
            dgArray[j.RowIndex, j.ColumnIndex] = j.Value.ToString();
        }
    }

    Microsoft.Office.Interop.Excel.Range chartRange;

    int rowCount = dgArray.GetLength(0);
    int columnCount = dgArray.GetLength(1);
    chartRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[2, 1]; //I have header info on row 1, so start row 2
    chartRange = chartRange.get_Resize(rowCount, columnCount);
    chartRange.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dgArray);


    oXL.Visible = false;
    oXL.UserControl = false;
    string outputFile = "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

    oWB.SaveAs("c:\\temp\\"+outputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
}
catch (Exception ex)
{
    //...
}

How do I get a background location update every n minutes in my iOS application?

I found a solution to implement this with the help of the Apple Developer Forums:

  • Specify location background mode
  • Create an NSTimer in the background with UIApplication:beginBackgroundTaskWithExpirationHandler:
  • When n is smaller than UIApplication:backgroundTimeRemaining it will work just fine. When n is larger, the location manager should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed.

This works because location is one of the three allowed types of background execution.

Note: I lost some time by testing this in the simulator where it doesn't work. However, it works fine on my phone.

Difference between CR LF, LF and CR line break types?

CR - ASCII code 13

LF - ASCII code 10.

Theoretically CR returns cursor to the first position (on the left). LF feeds one line moving cursor one line down. This is how in old days you controled printers and text-mode monitors. These characters are usually used to mark end of lines in text files. Different operating systems used different conventions. As you pointed out Windows uses CR/LF combination while pre-OSX Macs use just CR and so on.

What is simplest way to read a file into String?

This should work for you:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get("abc.java")));
}

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

COUNT DISTINCT with CONDITIONS

Try the following statement:

select  distinct A.[Tag],
     count(A.[Tag]) as TAG_COUNT,
     (SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
     from [TagTbl] AS A GROUP BY A.[Tag]

The first field will be the tag the second will be the whole count the third will be the positive ones count.

Select DataFrame rows between two dates

Another option, how to achieve this, is by using pandas.DataFrame.query() method. Let me show you an example on the following data frame called df.

>>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
>>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
>>> print(df)
      col_1       date
0  0.015198 2020-01-01
1  0.638600 2020-01-02
2  0.348485 2020-01-03
3  0.247583 2020-01-04
4  0.581835 2020-01-05

As an argument, use the condition for filtering like this:

>>> start_date, end_date = '2020-01-02', '2020-01-04'
>>> print(df.query('date >= @start_date and date <= @end_date'))
      col_1       date
1  0.244104 2020-01-02
2  0.374775 2020-01-03
3  0.510053 2020-01-04

If you do not want to include boundaries, just change the condition like following:

>>> print(df.query('date > @start_date and date < @end_date'))
      col_1       date
2  0.374775 2020-01-03

How to resolve /var/www copy/write permission denied?

sudo cp hello.php /var/www/

What output do you get?

Picasso v/s Imageloader v/s Fresco vs Glide

Neither Glide nor Picasso is perfect. The way Glide loads an image to memory and do the caching is better than Picasso which let an image loaded far faster. In addition, it also helps preventing an app from popular OutOfMemoryError. GIF Animation loading is a killing feature provided by Glide. Anyway Picasso decodes an image with better quality than Glide.

Which one do I prefer? Although I use Picasso for such a very long time, I must admit that I now prefer Glide. But I would recommend you to change Bitmap Format to ARGB_8888 and let Glide cache both full-size image and resized one first. The rest would do your job great!

  • Method count of Picasso and Glide are at 840 and 2678 respectively.
  • Picasso (v2.5.1)'s size is around 118KB while Glide (v3.5.2)'s is around 430KB.
  • Glide creates cached images per size while Picasso saves the full image and process it, so on load it shows faster with Glide but uses more memory.
  • Glide use less memory by default with RGB_565.

+1 For Picasso Palette Helper.

There is a post that talk a lot about Picasso vs Glide post

convert string to date in sql server

I think style no. 111 (Japan) should work:

SELECT CONVERT(DATETIME, '2012-08-17', 111)

And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD) which works for any language and date format setting in SQL Server:

SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)

Can I add background color only for padding?

I'd just wrap the header with another div and play with borders.

<div class="header-border"><div class="header-real">

    <p>Foo</p>

</div></div>

CSS:

.header-border { border: 2px solid #000000; }
.header-real { border: 10px solid #003399; background: #cccccc; padding: 10px; }

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

Warning: comparison with string literals results in unspecified behaviour

This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.

String literals like

"a"

or

"This is a string"

are put in the text or data segments of your program.

A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.

So if I have

char *s1 = "This is a string";

then s1 is a pointer to the first byte of the string.

Now, if I have

char *s2 = "This is a string";

this is also a pointer to the same first byte of that string in the text or data segment of the program.

But if I have

char *s3 = malloc( 17 );
strcpy(s3, "This is a string");

then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.

Illustrative examples:

Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:

s1 == s2 // True: we are comparing two pointers that contain the same address

but the following will evaluate to false

s1 == s3 // False: Comparing two pointers that don't hold the same address.

And although it might be tempting to have something like this:

struct Vehicle{
    char *type;
    // other stuff
}

if( type == "Car" )
   //blah1
else if( type == "Motorcycle )
   //blah2

You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.

I have tested it and it works. If I do

A.type = "Car";

then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like

if( A.type == B.type )

but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.

Solutions:

In your case, what you want to do is use strcmp(a,b) == 0 to replace a == b

In the case of my example, you should use an enum.

enum type {CAR = 0, MOTORCYCLE = 1}

The preceding thing with string was useful because you could print the type, so you might have an array like this

char *types[] = {"Car", "Motorcycle"};

And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.

Therefore it might be better to do

char *getTypeString(int type)
{
    switch(type)
    case CAR: return "Car";
    case MOTORCYCLE: return "Motorcycle"
    default: return NULL;
}

Purpose of installing Twitter Bootstrap through npm?

  1. The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.

    Now, the point of bootstrap's npm package

    is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.

  2. How to use it

    Imagine the following project structure:

    project
    |-- node_modules
    |-- public
    |   |-- css
    |   |-- img
    |   |-- js
    |   |-- index.html
    |-- package.json
    
    

In your index.html you can reference both css and js files like this:

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:

var bootstrap = require('bootstrap');

And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.

Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.


UPDATE March 2017

Almost two years have passed since I wrote this answer and an update is in place.

Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.

Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:

const bootstrap = require('bootstrap');

As for the css files, webpack has so called "loaders". They allow you write this in your js code:

require('bootstrap/dist/css/bootstrap.css');

and the css files will be "magically" included in your build. They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.

In conclusion.

  1. You should "bundle" your app code with a bundler
  2. You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

javascript: Disable Text Select

Simple Copy this text and put on the before </body>

function disableselect(e) {
  return false
}

function reEnable() {
  return true
}

document.onselectstart = new Function ("return false")

if (window.sidebar) {
  document.onmousedown = disableselect
  document.onclick = reEnable
}

Adding a library/JAR to an Eclipse Android project

Put the source in a folder outside yourt workspace. Rightclick in the project-explorer, and select "Import..."

Import the project in your workspace as an Android project. Try to build it, and make sure it is marked as a library project. Also make sure it is build with Google API support, if not you will get compile errors.

Then, in right click on your main project in the project explorer. Select properties, then select Android on the left. In the library section below, click "Add"..

The mapview-balloons library should now be available to add to your project..

How to insert a text at the beginning of a file?

To add a line to the top of the file:

sed -i '1iText to add\'

How set background drawable programmatically in Android

Use butterknife to bind the drawable resource to a variable by adding this to the top of your class (before any methods).

@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;

then inside one of your methods add

layout.setBackground(background);

That's all you need

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

Is there a way to specify how many characters of a string to print out using printf()?

In C++, I do it in this way:

char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;

Please note this is not safe because when passing the second argument I can go beyond the size of the string and generate a memory access violation. You have to implement your own check for avoiding this.

How to loop over files in directory and change path and add suffix to filename

for file in Data/*.txt
do
    for ((i = 0; i < 3; i++))
    do
        name=${file##*/}
        base=${name%.txt}
        ./MyProgram.exe "$file" Logs/"${base}_Log$i.txt"
    done
done

The name=${file##*/} substitution (shell parameter expansion) removes the leading pathname up to the last /.

The base=${name%.txt} substitution removes the trailing .txt. It's a bit trickier if the extensions can vary.

Reverse order of foreach list items

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

Disable Logback in SpringBoot

To add a solution in gradle.

dependencies {
    compile ('org.springframework.boot:spring-boot-starter') {
        exclude module : 'spring-boot-starter-logging'
    }
    compile ('org.springframework.boot:spring-boot-starter-web') {
        exclude module : 'spring-boot-starter-logging'
    }
}

How to create a simple http proxy in node.js?

Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    

Using `date` command to get previous, current and next month

the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -

Previous month
#cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
DEC-2016 
Current month
#cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
JAN-2017
Next month
#cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
FEB-2017

Windows Forms - Enter keypress activates submit button?

As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

detect key press in python?

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

Where to get this Java.exe file for a SQL Developer installation

I found my java.exe that worked for SQL Developer at C:\ORACLE11G\product\11.2.0\client_1\jdk\bin where C:\ORACLE11G is my Oracle Home. The client that I have installed is 11.2.0.

Hope this helps.

Simple conversion between java.util.Date and XMLGregorianCalendar

You can use the this customization to change the default mapping to java.util.Date

<xsd:annotation>
<xsd:appinfo>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
                 parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
                 printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
    </jaxb:globalBindings>
</xsd:appinfo>

Return only string message from Spring MVC 3 Controller

What about:

PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;

This woks for me.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Convert a negative number to a positive one in JavaScript

The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).

var y = -100;
var x =- y;

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

Is a DIV inside a TD a bad idea?

If you want to use position: absolute; on the div with position: relative; on the td you will run into issues. FF, safari, and chrome (mac, not PC though) will not position the div relative to the td (like you would expect) this is also true for divs with display: table-whatever; so if you want to do that you need two divs, one for the container width: 100%; height: 100%; and no border so it fills the td without any visual impact. and then the absolute one.

other than that why not just split the cell?

how to remove the first two columns in a file using shell (awk, sed, whatever)

awk '{$1=$2="";$0=$0;$1=$1}1'

Input

a b c d

Output

c d

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

How to get numbers after decimal point?

This is only if you want toget the first decimal

print(int(float(input()) * 10) % 10)

Or you can try this

num = float(input())
b = num - int(num) 
c = b * 10
print(int(c))

The simplest way to resize an UIImage?

(Swift 4 compatible) iOS 10+ and iOS < 10 solution (using UIGraphicsImageRenderer if possible, UIGraphicsGetImageFromCurrentImageContext otherwise)

/// Resizes an image
///
/// - Parameter newSize: New size
/// - Returns: Resized image
func scaled(to newSize: CGSize) -> UIImage {
    let rect = CGRect(origin: .zero, size: newSize)

    if #available(iOS 10, *) {
        let renderer = UIGraphicsImageRenderer(size: newSize)
        return renderer.image { _ in
            self.draw(in: rect)
        }
    } else {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

MAX function in where clause mysql

SELECT firstName, Lastname, MAX(id) as max WHERE YOUR_CONDITIONS_HERE HAVING id=max(id) 

How to convert CSV file to multiline JSON?

I see this is old but I needed the code from SingleNegationElimination however I had issue with the data containing non utf-8 characters. These appeared in fields I was not overly concerned with so I chose to ignore them. However that took some effort. I am new to python so with some trial and error I got it to work. The code is a copy of SingleNegationElimination with the extra handling of utf-8. I tried to do it with https://docs.python.org/2.7/library/csv.html but in the end gave up. The below code worked.

import csv, json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)

code = ''
for row in reader:
    try:
        print('+' + row['Code'])
        for key in row:
            row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')      
        json.dump(row, jsonfile)
        jsonfile.write('\n')
    except:
        print('-' + row['Code'])
        raise

Settings to Windows Firewall to allow Docker for Windows to share drive

If non of the above works, just make sure you're not connected to a VPN. That's exactly what happened to me, i was connected to a VPN using Cisco AnyConnect client, also make sure you set an static DNS in the docker settings.

Counting the number of option tags in a select tag in jQuery

Another approach that can be useful.

$('#select-id').find('option').length

Arrays in type script

A cleaner way to do this:

class Book {
    public Title: string;
    public Price: number;
    public Description: string;

    constructor(public BookId: number, public Author: string){}
}

Then

var bks: Book[] = [
    new Book(1, "vamsee")
];

Viewing local storage contents on IE

In IE11, you can see local storage in console on dev tools:

  1. Show dev tools (press F12)
  2. Click "Console" or press Ctrl+2
  3. Type localStorage and press Enter

Also, if you need to clear the localStorage, type localStorage.clear() on console.

Android: I am unable to have ViewPager WRAP_CONTENT

Nothing of suggested above worked for me. My use case is having 4 custom ViewPagers in ScrollView. Top of them is measured based on aspect ratio and the rest just has layout_height=wrap_content. I've tried cybergen , Daniel López Lacalle solutions. None of them work fully for me.

My guess why cybergen doesn't work on page > 1 is because it calculates height of pager based on page 1, that is hidden if you scroll further.

Both cybergen and Daniel López Lacalle suggestions have weird behavior in my case: 2 of 3 are loaded ok and 1 randomly height is 0. Appears that onMeasure was called before children were populated. So I came up with a mixture of these 2 answers + my own fixes:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
        // find the first child view
        View view = getChildAt(0);
        if (view != null) {
            // measure the first child view with the specified measure spec
            view.measure(widthMeasureSpec, heightMeasureSpec);
            int h = view.getMeasuredHeight();
            setMeasuredDimension(getMeasuredWidth(), h);
            //do not recalculate height anymore
            getLayoutParams().height = h;
        }
    }
}

Idea is to let ViewPager calculate children's dimensions and save calculated height of first page in layout params of the ViewPager. Don't forget to set fragment's layout height to wrap_content otherwise you can get height=0. I've used this one:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content">
        <!-- Childs are populated in fragment -->
</LinearLayout>

Please note that this solution works great if all of your pages have same height. Otherwise you need to recalculate ViewPager height based on current child active. I don't need it, but if you suggest the solution I would be happy to update the answer.

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

How to convert an NSTimeInterval (seconds) into minutes

All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

How can we stop a running java process through Windows cmd?

(on Windows OS without Service) Spring Boot start/stop sample.

run.bat

@ECHO OFF
IF "%1"=="start" (
    ECHO start your app name
    start "yourappname" java -jar -Dspring.profiles.active=prod yourappname-0.0.1.jar
) ELSE IF "%1"=="stop" (
    ECHO stop your app name
    TASKKILL /FI "WINDOWTITLE eq yourappname"
) ELSE (
    ECHO please, use "run.bat start" or "run.bat stop"
)
pause

start.bat

@ECHO OFF
call run.bat start

stop.bat:

@ECHO OFF
call run.bat stop

Google Maps: how to get country, state/province/region, city given a lat/long value?

I used this question as a starting point for my own solution. Thought it was appropriate to contribute my code back since its smaller than tabacitu's

Dependencies:

Code:

if(geoPosition.init()){  

    var foundLocation = function(city, state, country, lat, lon){
        //do stuff with your location! any of the first 3 args may be null
        console.log(arguments);
    }

    var geocoder = new google.maps.Geocoder(); 
    geoPosition.getCurrentPosition(function(r){
        var findResult = function(results, name){
            var result =  _.find(results, function(obj){
                return obj.types[0] == name && obj.types[1] == "political";
            });
            return result ? result.short_name : null;
        };
        geocoder.geocode({'latLng': new google.maps.LatLng(r.coords.latitude, r.coords.longitude)}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK && results.length) {
                results = results[0].address_components;
                var city = findResult(results, "locality");
                var state = findResult(results, "administrative_area_level_1");
                var country = findResult(results, "country");
                foundLocation(city, state, country, r.coords.latitude, r.coords.longitude);
            } else {
                foundLocation(null, null, null, r.coords.latitude, r.coords.longitude);
            }
        });
    }, { enableHighAccuracy:false, maximumAge: 1000 * 60 * 1 });
}

Get a Div Value in JQuery

$('#myDiv').text()

Although you'd be better off doing something like:

_x000D_
_x000D_
var txt = $('#myDiv p').text();_x000D_
alert(txt);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
_x000D_
_x000D_

Make sure you're linking to your jQuery file too :)

Clear an input field with Reactjs?

I have a similar solution to @Satheesh using React hooks:

State initialization:

const [enteredText, setEnteredText] = useState(''); 

Input tag:

<input type="text" value={enteredText}  (event handler, classNames, etc.) />

Inside the event handler function, after updating the object with data from input form, call:

setEnteredText('');

Note: This is described as 'two-way binding'

MessageBodyWriter not found for media type=application/json

Below should be in your pom.xml above other jersy/jackson dependencies. In my case it as below jersy-client dep-cy and i got MessageBodyWriter not found for media type=application/json.

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

How to add a downloaded .box file to Vagrant?

Try to change directory to where the .box is saved

Run vagrant box add my-box downloaded.box, this may work as it avoids absolute path (on Windows?).

Remove empty elements from an array in Javascript

'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.

// --- Example ----------
var field = [];

field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------

var originalLength;

// Store the length of the array.
originalLength = field.length;

for (var i in field) {
  // Attach the truthy values upon the end of the array. 
  field.push(field[i]);
}

// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);

Simplest way to set image as JPanel background

As I know the way you can do it is to override paintComponent method that demands to inherit JPanel

 @Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); // paint the background image and scale it to fill the entire space
    g.drawImage(/*....*/);
}

The other way (a bit complicated) to create second custom JPanel and put is as background for your main

ImagePanel

public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;

public ImagePanel(Image image)
{
    this.image = image;
    this.iWidth2 = image.getWidth(this)/2;
    this.iHeight2 = image.getHeight(this)/2;
}


public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    if (image != null)
    {
        int x = this.getParent().getWidth()/2 - iWidth2;
        int y = this.getParent().getHeight()/2 - iHeight2;
        g.drawImage(image,x,y,this);
    }
}
}

EmptyPanel

public class EmptyPanel extends JPanel{

private static final long serialVersionUID = 1L;

public EmptyPanel() {
    super();
    init();
}

@Override
public boolean isOptimizedDrawingEnabled() {
    return false;
}


public void init(){

    LayoutManager overlay = new OverlayLayout(this);
    this.setLayout(overlay);

    ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
    iPanel.setLayout(new BorderLayout());   
    this.add(iPanel);
    iPanel.setOpaque(false);                
}
}

IconToImage

public class IconToImage {

Icon icon;
Image image;


public IconToImage(Icon icon) {
    this.icon = icon;
    image = iconToImage();
}

public Image iconToImage() { 
    if (icon instanceof ImageIcon) { 
        return ((ImageIcon)icon).getImage(); 
    } else { 
        int w = icon.getIconWidth(); 
        int h = icon.getIconHeight(); 
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
        GraphicsDevice gd = ge.getDefaultScreenDevice(); 
        GraphicsConfiguration gc = gd.getDefaultConfiguration(); 
        BufferedImage image = gc.createCompatibleImage(w, h); 
        Graphics2D g = image.createGraphics(); 
        icon.paintIcon(null, g, 0, 0); 
        g.dispose(); 
        return image; 
    } 
}


/**
 * @return the image
 */
public Image getImage() {
    return image;
}
}

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

C: printf a float value

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

How to make a Generic Type Cast function

Something like this?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

You can then use it like this:

int val = ConvertValue<int>("42");

Edit:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.