Programs & Examples On #Eventqueue

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

I don't think that IDE is relevant here. After all you're running a Maven and Maven doesn't have a source that will allow to compile the diamond operators. So, I think you should configure maven-compiler-plugin itself.

You can read about this here. But in general try to add the following properties:

<properties>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>

and see whether it compiles now in Maven only.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

My situation was a little different, I was trying to segue into a UINavigationController, and what fixed it for me was getting the main queue portion.

For Objective-C:

dispatch_async(dispatch_get_main_queue(), ^{
    [self performSegueWithIdentifier:@"SegueName" sender:self];
});

For Swift 3:

DispatchQueue.main.async { [weak self] in
    self?.performSegue(withIdentifier: "SegueName", sender: self)
}

Spring Boot Remove Whitelabel Error Page

I was trying to call a REST endpoint from a microservice and I was using the resttemplate's put method.

In my design if any error occurred inside the REST endpoint it should return a JSON error response, it was working for some calls but not for this put one, it returned the white label error page instead.

So I did some investigation and I found out that;

Spring try to understand the caller if it is a machine then it returns JSON response or if it is a browser than it returns the white label error page HTML.

As a result: my client app needed to say to REST endpoint that the caller is a machine, not a browser so for this the client app needed to add 'application/json' into the ACCEPT header explicitly for the resttemplate's 'put' method. I added this to the header and solved the problem.

my call to the endpoint:

restTemplate.put(url, request, param1, param2);

for above call I had to add below header param.

headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);

or I tried to change put to exchange as well, in this case, exchange call added the same header for me and solved the problem too but I don't know why :)

restTemplate.exchange(....)

java IO Exception: Stream Closed

Don't call write.close() in writeToFile().

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

Programmatically select a row in JTable

You use the available API of JTable and do not try to mess with the colors.

Some selection methods are available directly on the JTable (like the setRowSelectionInterval). If you want to have access to all selection-related logic, the selection model is the place to start looking

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

How to send a stacktrace to log4j?

This answer may be not related to the question asked but related to title of the question.

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable("Created at main()");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        createdBy.printStackTrace(pw);
        try {
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug(os.toString());
    }
}

OR

public static String getStackTrace (Throwable t)
{
    StringWriter stringWriter = new StringWriter();
    PrintWriter  printWriter  = new PrintWriter(stringWriter);
    t.printStackTrace(printWriter);
    printWriter.close();    //surprise no IO exception here
    try {
        stringWriter.close();
    }
    catch (IOException e) {
    }
    return stringWriter.toString();
}

OR

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
    logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
}

How to convert object array to string array in Java

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.

If you know your Object array contains Strings only, you may also do (instread of calling toString()):

for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];

The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:

    Object[] o = new String[10];
    String[] s = (String[]) o;

How to reset settings in Visual Studio Code?

Go to File -> preferences -> settings.

On the right panel you will see all customized user settings so you can remove the ones you want to reset. On doing so the default settings mentioned in left pane will become active instantly.

How to get week number of the month from the date in sql server 2008

Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -

select (DATEPART(wk,@date_given)-DATEPART(wk,dateadd(d,1-day(@date_given),@date_given)))+1

above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month

How to add images in select list?

not exactly an image, but i found the easiest solution was to just add some unicode code in, ? works great for me

How to debug in Django, the good way?

Most options are alredy mentioned. To print template context, I've created a simple library for that. See https://github.com/edoburu/django-debugtools

You can use it to print template context without any {% load %} construct:

{% print var %}   prints variable
{% print %}       prints all

It uses a customized pprint format to display the variables in a <pre> tag.

Crystal Reports - Adding a parameter to a 'Command' query

Try this:

Select Project_Name, ReleaseDate, TaskName
From DB_Table
Where Project_Name like '{?Pm-?Proj_Name}'
  And ReleaseDate >= currentdate

currentdate should be a valid database function or field to work. If you are using MS SQL Server, use GETDATE() instead.

If all you want is to filter records in a subreport based on a parameter from the main report, it might be easier to simply add the table to the subreport, and then create a Project_Name link between the main report and subreport. You can then use the Select Expert to filter the ReleaseDate as well.

Git pull till a particular commit

If you merge a commit into your branch, you should get all the history between.

Observe:

$ git init ./
Initialized empty Git repository in /Users/dfarrell/git/demo/.git/
$ echo 'a' > letter
$ git add letter
$ git commit -m 'Initial Letter'
[master (root-commit) 6e59e76] Initial Letter
 1 file changed, 1 insertion(+)
 create mode 100644 letter
$ echo 'b' >> letter
$ git add letter && git commit -m 'Adding letter'
[master 7126e6d] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'c' >> letter; git add letter && git commit -m 'Adding letter'
[master f2458be] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'd' >> letter; git add letter && git commit -m 'Adding letter'
[master 7f77979] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'e' >> letter; git add letter && git commit -m 'Adding letter'
[master 790eade] Adding letter
 1 file changed, 1 insertion(+)
$ git log
commit 790eade367b0d8ab8146596cd717c25fd895302a
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:26 2015 -0500

    Adding letter

commit 7f77979efd17f277b4be695c559c1383d2fc2f27
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:24 2015 -0500

    Adding letter

commit f2458bea7780bf09fe643095dbae95cf97357ccc
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:19 2015 -0500

    Adding letter

commit 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:52 2015 -0500

    Adding letter

commit 6e59e7650314112fb80097d7d3803c964b3656f0
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:33 2015 -0500

    Initial Letter
$ git checkout 6e59e7650314112fb80097d7d3803c964b3656f
$ git checkout 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Note: checking out '7126e6dcb9c28ac60cb86ae40fb358350d0c5fad'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 7126e6d... Adding letter
$ git checkout -b B 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Switched to a new branch 'B'
$ git pull 790eade367b0d8ab8146596cd717c25fd895302a
fatal: '790eade367b0d8ab8146596cd717c25fd895302a' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
$ git merge 7f77979efd17f277b4be695c559c1383d2fc2f27
Updating 7126e6d..7f77979
Fast-forward
 letter | 2 ++
 1 file changed, 2 insertions(+)
$ cat letter
a
b
c
d

How do I replace a character in a string in Java?

If you're using Spring you can simply call HtmlUtils.htmlEscape(String input) which will handle the '&' to '&' translation.

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Rounding a variable to two decimal places C#

decimal pay  = 1.994444M;

Math.Round(pay , 2); 

OS X Terminal UTF-8 issues

Since nano is a terminal application. I guess it's more a terminal problem than a nano problem.

I met similar problems at OS X (I cannot input and view the Chinese characters at terminal).

I tried tweaking the system setting through OS X UI whose real effect is change the environment variable LANG.

So finally I just add some stuff into the ~/.bashrc to fix the problem.

# I'm Chinese and I prefer English manual
export LC_COLLATE="zh_CN.UTF-8"
export LC_CTYPE="zh_CN.UTF-8"
export LC_MESSAGES="en_US.UTF-8"
export LC_MONETARY="zh_CN.UTF-8"
export LC_NUMERIC="zh_CN.UTF-8"
export LC_TIME="zh_CN.UTF-8"

BTW, don't set LC_ALL which will override all the other LC_* settings.

Styling the last td in a table with css

There is also a different approach.. and this would work for tables that aren't static... basically use <th> instead of <td> for that column:

<style type="text/css">
 table td { border: 1px solid black; }
 table th { border: 0px; }
<style>
<table>
  <tbody>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <th>Five</th>
    </tr>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <th>Five</th>
    </tr>
  </tbody>
</table>

How do I determine file encoding in OS X?

Which LaTeX are you using? When I was using teTeX, I had to manually download the unicode package and add this to my .tex files:

% UTF-8 stuff
\usepackage[notipa]{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

Now, I've switched over to XeTeX from the TeXlive 2008 package (here), it is even more simple:

% UTF-8 stuff
\usepackage{fontspec}
\usepackage{xunicode}

As for detection of a file's encoding, you could play with file(1) (but it is rather limited) but like someone else said, it is difficult.

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

Retrieve the maximum length of a VARCHAR column in SQL Server

SELECT MAX(LEN(Desc)) as MaxLen FROM table

Getting the absolute path of the executable, using C#?

Suppose i have .config file in console app and now am getting like below.

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";

How to enable DataGridView sorting when user clicks on the column header?


there is quite simply solution when using Entity Framework (version 6 in this case). I'm not sure but it seems to ObservableCollectionExtensions.ToBindingList<T> method returns implementation of sortable binding list. I haven't found source code to confirm this supposition but object returning from this method works with DataGridView very well especially when sorting columns by clicking on its headers.

The code is very simply and relies only on .net and entity framework classes:

using System.Data.Entity;

IEnumerable<Item> items = MethodCreatingItems();

var observableItems = new System.Collections.ObjectModel.ObservableCollection<Item>(items);
System.ComponentModel.BindingList<Item> source = observableItems.ToBindingList();

MyDataGridView.DataSource = source;

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

What is the difference between JAX-RS and JAX-WS?

i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

How to loop through files matching wildcard in batch file

Expanding on Nathans post. The following will do the job lot in one batch file.

@echo off

if %1.==Sub. goto %2

for %%f in (*.in) do call %0 Sub action %%~nf
goto end

:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt

:end

Using only CSS, show div on hover over <a>

Don't forget. if you are trying to hover around an image, you have to put it around a container. css:

.brand:hover + .brand-sales {
    display: block;
}

.brand-sales {
    display: none;
}

If you hover on this:

<span className="brand">
   <img src="https://murmure.me/wp-content/uploads/2017/10/nike-square-1900x1900.jpg" 
     alt"some image class="product-card-place-logo"/>
</span>

This will show:

<div class="product-card-sales-container brand-sales">
    <div class="product-card-">Message from the business goes here. They can talk alot or not</div>
</div>

What is “2's Complement”?

Imagine that you have a finite number of bits/trits/digits/whatever. You define 0 as all digits being 0, and count upwards naturally:

00
01
02
..

Eventually you will overflow.

98
99
00

We have two digits and can represent all numbers from 0 to 100. All those numbers are positive! Suppose we want to represent negative numbers too?

What we really have is a cycle. The number before 2 is 1. The number before 1 is 0. The number before 0 is... 99.

So, for simplicity, let's say that any number over 50 is negative. "0" through "49" represent 0 through 49. "99" is -1, "98" is -2, ... "50" is -50.

This representation is ten's complement. Computers typically use two's complement, which is the same except using bits instead of digits.

The nice thing about ten's complement is that addition just works. You do not need to do anything special to add positive and negative numbers!

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

How do I find out what is hammering my SQL Server?

This query uses DMV's to identify the most costly queries by CPU

SELECT TOP 20
    qs.sql_handle,
    qs.execution_count,
    qs.total_worker_time AS Total_CPU,
    total_CPU_inSeconds = --Converted from microseconds
        qs.total_worker_time/1000000,
    average_CPU_inSeconds = --Converted from microseconds
        (qs.total_worker_time/1000000) / qs.execution_count,
    qs.total_elapsed_time,
    total_elapsed_time_inSeconds = --Converted from microseconds
        qs.total_elapsed_time/1000000,
    st.text,
    qp.query_plan
FROM
    sys.dm_exec_query_stats AS qs
CROSS APPLY 
    sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY
    sys.dm_exec_query_plan (qs.plan_handle) AS qp
ORDER BY 
    qs.total_worker_time DESC

For a complete explanation see: How to identify the most costly SQL Server queries by CPU

Drop-down box dependent on the option selected in another drop-down box

Try something like this... jsfiddle demo

HTML

<!-- Source: -->
<select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option>
</select>

<!-- Status: -->
<select id="status" name="status">
    <option>OPEN</option>
    <option>DELIVERED</option>
</select>

JS

$(document).ready(function () {

    $("#source").change(function () {
        var el = $(this);
        if (el.val() === "ONLINE") {
            $("#status").append("<option>SHIPPED</option>");
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();
        }
    });

});

Get all mysql selected rows into an array

You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

How to change content on hover

_x000D_
_x000D_
.label:after{_x000D_
    content:'ADD';_x000D_
}_x000D_
.label:hover:after{_x000D_
    content:'NEW';_x000D_
}
_x000D_
<span class="label"></span>
_x000D_
_x000D_
_x000D_

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to create a session using JavaScript?

You can use sessionStorage it is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Error while trying to run project: Unable to start program. Cannot find the file specified

I had a similar problem, but none of the solutions listed here helped. My problem was that my solution has multiple projects and the wrong one was selected as the StartUp Project, once I changed that, it worked.

How can I sort an ArrayList of Strings in Java?

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

How to hide columns in an ASP.NET GridView with auto-generated columns?

I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.

In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.

For example: A Gridview is on the page as follows.

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>

And then in the code behind a PopulateGridView routine is called during the page load event.

protected void PopulateGridView()
{
    DataTable dt = GetDataSource();
    gv.DataSource = dt;
    foreach (DataColumn col in dt.Columns)
    {
        BoundField field = new BoundField();
        field.DataField = col.ColumnName;
        field.HeaderText = col.ColumnName;
        if (col.ColumnName.EndsWith("ID"))
        {
            field.Visible = false;
        }
        gv.Columns.Add(field);
    }
    gv.DataBind();
}

In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.

What is "runtime"?

Matt Ball answered it correctly. I would say about it with examples.

Consider running a program compiled in Turbo-Borland C/C++ (version 3.1 from the year 1991) compiler and let it run under a 32-bit version of windows like Win 98/2000 etc.

It's a 16-bit compiler. And you will see all your programs have 16-bit pointers. Why is it so when your OS is 32bit? Because your compiler has set up the execution environment of 16 bit and the 32-bit version of OS supported it.

What is commonly called as JRE (Java Runtime Environment) provides a Java program with all the resources it may need to execute.

Actually, runtime environment is brain product of idea of Virtual Machines. A virtual machine implements the raw interface between hardware and what a program may need to execute. The runtime environment adopts these interfaces and presents them for the use of the programmer. A compiler developer would need these facilities to provide an execution environment for its programs.

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Add vertical whitespace using Twitter Bootstrap?

There is nothing more DRY than

.btn {
    margin-bottom:5px;
}

Android: ScrollView vs NestedScrollView

NestedScrollView as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.

This is where NestedScrollView comes in.

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

CSS to line break before/after a particular `inline-block` item

Maybe it's is completely possible with only CSS but I prefer to avoid "float" as much as I can because it interferes with it's parent's height.

If you are using jQuery, you can create a simple `wrapN` plugin that is similar to `wrapAll` except it only wraps "N" elements and then breaks and wraps the next "N" elements using a loop. Then set your wrappers class to `display: block;`.

(function ($) {
    $.fn.wrapN = function (wrapper, n, start) {
        if (wrapper === undefined || n === undefined) return false;
        if (start === undefined) start = 0;
        for (var i = start; i < $(this).size(); i += n)
           $(this).slice(i, i + n).wrapAll(wrapper);
        return this;
    };
}(jQuery));

$(document).ready(function () {
    $("li").wrapN("<span class='break' />", 3);
});

Here is a JSFiddle of the finished product:

http://jsfiddle.net/dustinpoissant/L79ahLoz/

How do I detect what .NET Framework versions and service packs are installed?

Enumerate the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP. Each subkey is a .NET version. It should have Install=1 value if it's present on the machine, an SP value that shows the service pack and an MSI=1 value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

  1. Install Microsoft SQL Management Studio, which you can download for free from Microsoft's website:

    Version 2008

    Microsoft SQL Management Studio 2008 is part of SQL Server 2008 Express with Advanced Services

    Version 2012

    Click download button and check ENU\x64\SQLManagementStudio_x64_ENU.exe

    Version 2014

    Click download button and check MgmtStudio 64BIT\SQLManagementStudio_x64_ENU.exe

  2. Open Microsoft SQL Management Studio.

  3. Backup original database to .BAK file (db -> Task -> Backup).
  4. Create empty database with new name (clone). Note comments below as this is optional.
  5. Click to clone database and open restore dialog (see image) restore dialog
  6. Select Device and add the backup file from step 3. add backup file
  7. Change destination to test database change destination
  8. Change location of database files, it must be different from the original. You can type directly into text box, just add postfix. (NOTE: Order is important. Select checkbox, then change the filenames.) change location
  9. Check WITH REPLACE and WITH KEEP_REPLICATION with replace

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

How do I mock a class without an interface?

The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.

If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You had selected the time format wrong

<?php 
date_default_timezone_set('GMT');

echo date("Y-m-d,h:m:s");
?>

java.net.UnknownHostException: Invalid hostname for server: local

What the exception is really saying is that there is no known server with the name "local". My guess is that you're trying to connect to your local computer. Try with the hostname "localhost" instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).

From the javadocs:

Thrown to indicate that the IP address of a host could not be determined.

127.0.0.1or ::1 or "localhost" should always be the loopback interface, so if that doesn't work I'd be really surprised.

If there really is a server called "local" on your network - examine your DNS settings or add it to your hosts file.

Removing duplicate characters from a string

Create a list in Python and also a set which doesn't allow any duplicates. Solution1 :

def fix(string):
    s = set()
    list = []
    for ch in string:
        if ch not in s:
            s.add(ch)
            list.append(ch)

    return ''.join(list)        

string = "Protiijaayiiii"
print(fix(string))

Method 2 :

s = "Protijayi"

aa = [ ch  for i, ch in enumerate(s) if ch not in s[:i]]
print(''.join(aa))

How to get selected value of a html select with asp.net

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">    
<head>
    <title> HtmlSelect Example </title>
    <script runat="server">
      void Button_Click (Object sender, EventArgs e)
      {
         Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
                       + ", value: " + Select1.Value;    
      }    
   </script>    
</head>    
<body>    
   <form id="form1" runat="server">

      Select an item: 

      <select id="Select1" runat="server">    
         <option value="Text for Item 1" selected="selected"> Item 1 </option>
         <option value="Text for Item 2"> Item 2 </option>
         <option value="Text for Item 3"> Item 3 </option>
         <option value="Text for Item 4"> Item 4 </option>
      </select>

      <button onserverclick="Button_Click" runat="server" Text="Submit"/>

      <asp:Label id="Label1" runat="server"/>    
   </form>
</body>
</html>

Source from Microsoft. Hope this is helpful!

How to align LinearLayout at the center of its parent?

Try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
            <TableRow >
            <LinearLayout 
            android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal" 
                    android:layout_gravity="center_horizontal" >
                    <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="1"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                     <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="2"
                    android:textAppearance="?android:attr/textAppearanceLarge" />
             </LinearLayout>
           </TableRow>
        </TableLayout>
    </FrameLayout>
</LinearLayout>

Apache shows PHP code instead of executing it

If you are a ubuntu user, after installing apache must run the following command in fresh installation

sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt

In my case works fine.

Print execution time of a shell command

root@hostname:~# time [command]

It also distinguishes between real time used and system time used.

Is there a way to word-wrap long words in a div?

You can try specifying a width for the div, whether it be in pixels, percentages or ems, and at that point the div will remain that width and the text will wrap automatically then within the div.

How to Consume WCF Service with Android

To get started with WCF, it might be easiest to just use the default SOAP format and HTTP POST (rather than GET) for the web-service bindings. The easiest HTTP binding to get working is "basicHttpBinding". Here is an example of what the ServiceContract/OperationContract might look like for your login service:

[ServiceContract(Namespace="http://mycompany.com/LoginService")]
public interface ILoginService
{
    [OperationContract]
    string Login(string username, string password);
}

The implementation of the service could look like this:

public class LoginService : ILoginService
{
    public string Login(string username, string password)
    {
        // Do something with username, password to get/create sessionId
        // string sessionId = "12345678";
        string sessionId = OperationContext.Current.SessionId;

        return sessionId;
    }
}

You can host this as a windows service using a ServiceHost, or you can host it in IIS like a normal ASP.NET web (service) application. There are a lot of tutorials out there for both of these.

The WCF service config might look like this:

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


    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="LoginServiceBehavior">
                    <serviceMetadata />
                </behavior>
            </serviceBehaviors>
        </behaviors>

        <services>
            <service name="WcfTest.LoginService"
                     behaviorConfiguration="LoginServiceBehavior" >
                <host>
                    <baseAddresses>
                        <add baseAddress="http://somesite.com:55555/LoginService/" />
                    </baseAddresses>
                </host>
                <endpoint name="LoginService"
                          address=""
                          binding="basicHttpBinding"
                          contract="WcfTest.ILoginService" />

                <endpoint name="LoginServiceMex"
                          address="mex"
                          binding="mexHttpBinding"
                          contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

(The MEX stuff is optional for production, but is needed for testing with WcfTestClient.exe, and for exposing the service meta-data).

You'll have to modify your Java code to POST a SOAP message to the service. WCF can be a little picky when inter-operating with non-WCF clients, so you'll have to mess with the POST headers a little to get it to work. Once you get this running, you can then start to investigate security for the login (might need to use a different binding to get better security), or possibly using WCF REST to allow for logins with a GET rather than SOAP/POST.

Here is an example of what the HTTP POST should look like from the Java code. There is a tool called "Fiddler" that can be really useful for debugging web-services.

POST /LoginService HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://mycompany.com/LoginService/ILoginService/Login"
Host: somesite.com:55555
Content-Length: 216
Expect: 100-continue
Connection: Keep-Alive

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Login xmlns="http://mycompany.com/LoginService">
<username>Blah</username>
<password>Blah2</password>
</Login>
</s:Body>
</s:Envelope>

Ajax using https on an http page

You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.

C# string does not contain possible?

Use Enumerable.Contains function:

var result =
    !(compareString.Contains(firstString) || compareString.Contains(secondString));

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.

Actually the problem was in ApplesDO Class:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }
}

There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }

    //Introducing the dummy constructor
    public ApplesDO() {
    }

}

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

How do I use PHP namespaces with autoload?

https://thomashunter.name/blog/simple-php-namespace-friendly-autoloader-class/

You’ll want to put your class files into a folder named Classes, which is in the same directory as the entry point into your PHP application. If classes use namespaces, the namespaces will be converted into the directory structure.

Unlike a lot of other auto-loaders, underscores will not be converted into directory structures (it’s tricky to do PHP < 5.3 pseudo namespaces along with PHP >= 5.3 real namespaces).

<?php
class Autoloader {
    static public function loader($className) {
        $filename = "Classes/" . str_replace("\\", '/', $className) . ".php";
        if (file_exists($filename)) {
            include($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('Autoloader::loader');

You’ll want to place the following code into your main PHP script (entry point):

require_once("Classes/Autoloader.php");

Here’s an example directory layout:

index.php
Classes/
  Autoloader.php
  ClassA.php - class ClassA {}
  ClassB.php - class ClassB {}
  Business/
    ClassC.php - namespace Business; classC {}
    Deeper/
      ClassD.php - namespace Business\Deeper; classD {}

Batch file to copy directories recursively

After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):

robocopy source_dir dest_dir /s /e

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

Android Studio - Auto complete and other features not working

You can also check if Power Save Mode on File menu is disabled.

SQL JOIN vs IN performance?

That's rather hard to say - in order to really find out which one works better, you'd need to actually profile the execution times.

As a general rule of thumb, I think if you have indices on your foreign key columns, and if you're using only (or mostly) INNER JOIN conditions, then the JOIN will be slightly faster.

But as soon as you start using OUTER JOIN, or if you're lacking foreign key indexes, the IN might be quicker.

Marc

Git - deleted some files locally, how do I get them from a remote repository

If you have deleted multiple files locally but not committed, you can force checkout

$ git checkout -f HEAD

Access: Move to next record until EOF

Keeping the code simple is always my advice:

If IsNull(Me.Id) = True Then
  DoCmd.GoToRecord , , acNext
Else
  DoCmd.GoToRecord , , acLast
End If

No suitable records were found verify your bundle identifier is correct

Just check that app you configured on iTuneconnect is having same bundle identifier that you are using to upload app.

Express-js can't GET my static files, why?

I am using Bootstrap CSS, JS and Fonts in my application. I created a folder called asset in root directory of the app and place all these folder inside it. Then in server file added following line:

app.use("/asset",express.static("asset"));

This line enables me to load the files that are in the asset directory from the /asset path prefix like: http://localhost:3000/asset/css/bootstrap.min.css.

Now in the views I can simply include CSS and JS like below:

<link href="/asset/css/bootstrap.min.css" rel="stylesheet">

How do I force a DIV block to extend to the bottom of a page even if it has no content?

You can use the "vh" length unit for the min-height property of the element itself and its parents. It's supported since IE9:

<body class="full-height">
    <form id="form1">
    <div id="header">
        <a title="Home" href="index.html" />
    </div>

    <div id="menuwrapper">
        <div id="menu">
        </div>
    </div>

    <div id="content" class="full-height">
    </div>
</body>

CSS:

.full-height {
    min-height: 100vh;
    box-sizing: border-box;
}

What are the differences between Visual Studio Code and Visual Studio?

I will provide a detailed differences between Visual Studio and Visual Studio Code below.

If you really look at it the most obvious difference is that .NET has been split into two:

  • .NET Core (Mac, Linux, and Windows)
  • .NET Framework (Windows only)

All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.

The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!

The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.

Visual Studio Code:

  • It's a lightweight source code editor which can be used to view, edit, run, and debug source code for applications.
  • Simply it is Visual Studio without the Visual UI, majorly a superman’s text-editor.
  • It is mainly oriented around files, not projects.
  • It does not have any scaffolding support.
  • It is a competitor of Sublime Text or Atom on Electron.
  • It is based on the Electron framework, which is used to build cross platform desktop application using web technologies.
  • It does not have support for Microsoft's version control system; Team Foundation Server.
  • It has limited IntelliSense for Microsoft file types and similar features.
  • It is mainly used by developers on a Mac who deal with client-side technologies (HTML, JavaScript, and CSS).

Visual Studio:

  • As the name indicates, it is an IDE, and it contains all the features required for project development. Like code auto completion, debugger, database integration, server setup, configurations, and so on.
  • It is a complete solution mostly used by and for .NET related developers. It includes everything from source control to bug tracker to deployment tools, etc. It has everything required to develop.
  • It is widely used on .NET related projects (though you can use it for other things). The community version is free, but if you want to make most of it then it is not free.
  • Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.

  • In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).

  • In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.

Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code

How to connect wireless network adapter to VMWare workstation?

Here is a simple way to connect with your WIFI -

  1. Click on Edit from the menu section
  2. Virtual Network Editor
  3. Change Settings
  4. Add Network
  5. Select a network name
  6. Select Bridged option in VMnet Information -> Bridge to : Automatic
  7. Apply

That's it. You might be asked password to connect. Add it and you would be able to connect to the network.

Kind Regards,

Rahul Tilloo

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

Find an item in List by LINQ?

If you want the index of the element, this will do it:

int index = list.Select((item, i) => new { Item = item, Index = i })
                .First(x => x.Item == search).Index;

// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
            where pair.Item == search
            select pair.Index).First();

You can't get rid of the lambda in the first pass.

Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:

var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
            where pair.Item == search
            select pair.Index).FirstOrDefault();

If you want the item:

// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).First();

// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).FirstOrDefault();

If you want to count the number of items that match:

int count = list.Count(item => item == search);
// or
int count = (from item in list
            where item == search
            select item).Count();

If you want all the items that match:

var items = list.Where(item => item == search);
// or
var items = from item in list
            where item == search
            select item;

And don't forget to check the list for null in any of these cases.

Or use (list ?? Enumerable.Empty<string>()) instead of list.

Thanks to Pavel for helping out in the comments.

Is there a pure CSS way to make an input transparent?

I set the opacity to 0. This made it disappear but still function when you click on it.

Declare an array in TypeScript

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

Convert DateTime to String PHP

You can use the format method of the DateTime class:

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

if ($result) {
  echo $result;
} else { // format failed
  echo "Unknown Time";
}

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

Delete the java.exe process in Task Manager and re-execute.It worked for me.

How get all values in a column using PHP?

First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function

function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
    $databaseConnectionQuery =  mysqli_connect($serverName, $userName, $password, $databaseName);
    if($databaseConnectionQuery === false)
    {
        die("ERROR: Could not connect. " . mysqli_connect_error());
        return false;
    }

    $resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
    $fetchFields = mysqli_fetch_fields($resultQuery);
    $fetchValues = mysqli_fetch_fields($resultQuery);

    if (mysqli_num_rows($resultQuery) > 0) 
    {           

        echo "<table class='table'>";
        echo "<tr>";
        foreach ($fetchFields as $fetchedField)
         {          
            echo "<td>";
            echo "<b>" . $fetchedField->name . "<b></a>";
            echo "</td>";
        }       
        echo "</tr>";
        while($totalRows = mysqli_fetch_array($resultQuery)) 
        {           
            echo "<tr>";                                
            for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
            {           
                echo "<td>";
                echo $totalRows[$eachRecord];
                echo "</td>";               
            }
            echo "<td><a href=''><button>Edit</button></a></td>";
            echo "<td><a href=''><button>Delete</button></a></td>";
            echo "</tr>";           
        } 
        echo "</table>";        

    } 
    else
    {
      echo "No Records Found in";
    }
}

All set now Pass the arguments as For Example

$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;

Here

localhost indicates Name of the host,

root indicates the username for database

root@123 indicates the password for the database

$queryStatment for generating Query

hope it helps

HTML5 Form Input Pattern Currency Format

How about :

^\d+\.\d{2}$

This matches one or more digits, a dot and 2 digits after the dot.

To match also comma as thousands delimiter :

^\d+(?:,\d{3})*\.\d{2}$

Convert serial.read() into a useable string using Arduino?

This would be way easier:

char data [21];
int number_of_bytes_received;

if(Serial.available() > 0)
{
    number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
    data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
} 

bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp


if (result == 0)
{
   Serial.println("data matches whatever");
} 
else 
{
   Serial.println("data does not match whatever");
}

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

What is special about /dev/tty?

The 'c' means it's a character special file.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

I think you are looking for the IGNORE_DUP_KEY option on your index. Have a look at IGNORE_DUP_KEY ON option documented at http://msdn.microsoft.com/en-us/library/ms186869.aspx which causes duplicate insertion attempts to produce a warning instead of an error.

How can I deploy an iPhone application from Xcode to a real iPhone device?

There is no workaround. You can only ad hoc deploy apps if they are registered with your device. This prevents you from building your own app store..

How can I go back/route-back on vue-router?

If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

Just initialize it in your main file with:

import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);

Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

this.$store.state.route.from.fullPath

You can also just place it in <router-link> component:

<router-link :to="{ path: $store.state.route.from.fullPath }"> 
  Back 
</router-link>

So when you use code above, link to previous path would be dynamically generated.

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

Finding first blank row, then writing to it

Very old thread but a simpler take :)

Sub firstBlank(c) 'as letter
    MsgBox (c & Split(Range(c & ":" & c).Find("", LookIn:=xlValues).address, "$")(2))
End Sub
Sub firstBlank(c) 'as number
    cLet = Split(Cells(1, c).address, "$")(1)
    MsgBox (cLet & Split(Range(cLet & ":" & cLet).Find("", LookIn:=xlValues).address, "$")(2))
End Sub

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

High Quality Image Scaling Library

Use this library: http://imageresizing.net

Have a read of this article by the library author: 20 Image Sizing Pitfalls with .NET

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

How to create a GUID in Excel?

The formula for Polish version:

=ZLACZ.TEKSTY(
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4)
)

Java Calendar, getting current month value, clarification needed

Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.

input type="submit" Vs button tag are they interchangeable?

I don't know if this is a bug or a feature, but there is very important (for some cases at least) difference I found: <input type="submit"> creates key value pair in your request and <button type="submit"> doesn't. Tested in Chrome and Safari.

So when you have multiple submit buttons in your form and want to know which one was clicked - do not use button, use input type="submit" instead.

How do you completely remove Ionic and Cordova installation from mac?

To uninstall Ionic and Cordova:

sudo npm uninstall -g cordova
sudo npm uninstall -g ionic

To install:

sudo npm install -g cordova

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Number of occurrences of a character in a string

Why use regex for that. String implements IEnumerable<char>, so you can just use LINQ.

test.Count(c => c == '&')

How do I output text without a newline in PowerShell?

A simplification to FrinkTheBrave's response:

[System.IO.File]::WriteAllText("c:\temp\myFile.txt", $myContent)

How to break lines in PowerShell?

Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

Android Stop Emulator from Command Line

The other answer didn't work for me (on Windows 7). But this worked:

telnet localhost 5554
kill

Slack clean all messages (~8K) in a channel

If you like Python and have obtained a legacy API token from the slack api, you can delete all private messages you sent to a user with the following:

import requests
import sys
import time
from json import loads

# config - replace the bit between quotes with your "token"
token = 'xoxp-854385385283-5438342854238520-513620305190-505dbc3e1c83b6729e198b52f128ad69'

# replace 'Carl' with name of the person you were messaging
dm_name = 'Carl'

# helper methods
api = 'https://slack.com/api/'
suffix = 'token={0}&pretty=1'.format(token)

def fetch(route, args=''):
  '''Make a GET request for data at `url` and return formatted JSON'''
  url = api + route + '?' + suffix + '&' + args
  return loads(requests.get(url).text)

# find the user whose dm messages should be removed
target_user = [i for i in fetch('users.list')['members'] if dm_name in i['real_name']]
if not target_user:
  print(' ! your target user could not be found')
  sys.exit()

# find the channel with messages to the target user
channel = [i for i in fetch('im.list')['ims'] if i['user'] == target_user[0]['id']]
if not channel:
  print(' ! your target channel could not be found')
  sys.exit()

# fetch and delete all messages
print(' * querying for channel', channel[0]['id'], 'with target user', target_user[0]['id'])
args = 'channel=' + channel[0]['id'] + '&limit=100'
result = fetch('conversations.history', args=args)
messages = result['messages']
print(' * has more:', result['has_more'], result.get('response_metadata', {}).get('next_cursor', ''))
while result['has_more']:
  cursor = result['response_metadata']['next_cursor']
  result = fetch('conversations.history', args=args + '&cursor=' + cursor)
  messages += result['messages']
  print(' * next page has more:', result['has_more'])

for idx, i in enumerate(messages):
  # tier 3 method rate limit: https://api.slack.com/methods/chat.delete
  # all rate limits: https://api.slack.com/docs/rate-limits#tiers
  time.sleep(1.05)
  result = fetch('chat.delete', args='channel={0}&ts={1}'.format(channel[0]['id'], i['ts']))
  print(' * deleted', idx+1, 'of', len(messages), 'messages', i['text'])
  if result.get('error', '') == 'ratelimited':
    print('\n ! sorry there have been too many requests. Please wait a little bit and try again.')
    sys.exit()

How to fix docker: Got permission denied issue

If you want to run docker as non-root user then you need to add it to the docker group.

  1. Create the docker group if it does not exist
$ sudo groupadd docker
  1. Add your user to the docker group.
$ sudo usermod -aG docker $USER
  1. Run the following command or Logout and login again and run (that doesn't work you may need to reboot your machine first)
$ newgrp docker

  1. Check if docker can be run without root
$ docker run hello-world

Reboot if still got error

$ reboot

Taken from the docker official documentation: manage-docker-as-a-non-root-user

How do I call the base class constructor?

You do this in the initializer-list of the constructor of the subclass.

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};

Base-class constructors that take arguments have to be called there before any members are initialized.

what is Promotional and Feature graphic in Android Market/Play Store?

Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.

The promo graphic will be required soon.

The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.

How to make a custom LinkedIn share button

LinkedIn revised their site recently, so there are a ton of old links just redirecting to the developer support homepage. Here is an updated link to the relevant page on LinkedIn's support site (as of Feb 16, 2015): https://developer.linkedin.com/docs/share-on-linkedin

Simulate a click on 'a' element using javascript/jquery

Using jQuery:

$('#gift-close').click();

Generate C# class from XML

I realise that this is a rather old post and you have probably moved on.

But I had the same problem as you so I decided to write my own program.

The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

It is in no way elegant but it did the job for me.

You can get it here: Please make suggestions if you like it.

SimpleXmlToCode

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

So you want to:

  1. execute part of a bash script as a different user
  2. change to that user's $HOME directory

Inspired by this answer, here's the adapted version of your script:

#!/usr/bin/env bash

different_user=deploy

useradd -m -s /bin/bash "$different_user"

echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo

echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
    echo "Current user: $(id)"
    echo "Current directory: $(pwd)"
EOF
echo

echo "Switched back to $(whoami)"

different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"

When you run it, you should get the following:

Current user: root
Current directory: /root

Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy

Switched back to root
deploy home directory: /home/deploy

How to order a data frame by one descending and one ascending column?

I use rank:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

> rum[order(rum$I1, -rank(rum$I2), decreasing = TRUE), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

Using async/await for multiple tasks

You can use Task.WhenAll function that you can pass n tasks; Task.WhenAll will return a task which runs to completion when all the tasks that you passed to Task.WhenAll complete. You have to wait asynchronously on Task.WhenAll so that you'll not block your UI thread:

   public async Task DoSomeThing() {

       var Task[] tasks = new Task[numTasks];
       for(int i = 0; i < numTask; i++)
       {
          tasks[i] = CallSomeAsync();
       }
       await Task.WhenAll(tasks);
       // code that'll execute on UI thread
   }

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

You have to specify Resource for the bucket via "arn:aws:s3:::bucketname" or "arn:aws:3:::bucketname*". The latter is preferred since it allows manipulations on the bucket's objects too. Notice there is no slash!

Listing objects is an operation on Bucket. Therefore, action "s3:ListBucket" is required. Adding an object to the Bucket is an operation on Object. Therefore, action "s3:PutObject" is needed. Certainly, you may want to add other actions as you require.

{
"Version": "version_id",
"Statement": [
    {
        "Sid": "some_id",
        "Effect": "Allow",
        "Action": [
            "s3:ListBucket",
            "s3:PutObject"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname*"
        ]
    }
] 
}

Onchange open URL via select - jQuery

Try this code its working perfect

<script>
$(function() {

    $("#submit").hide();

    $("#page-changer select").change(function() {
        window.location = $("#page-changer select option:selected").val();
    })

});
</script>

<?php
    if (isset($_POST['nav'])) {
         header("Location: $_POST[nav]");
    }
?>
<form id="page-changer" action="" method="post">
    <select name="nav">
        <option value="">Go to page...</option>
        <option value="http://css-tricks.com/">CSS-Tricks</option>
        <option value="http://digwp.com/">Digging Into WordPress</option>
        <option value="http://quotesondesign.com/">Quotes on Design</option>
    </select>
    <input type="submit" value="Go" id="submit" />
</form>

How do I configure different environments in Angular.js?

For Gulp users, gulp-ng-constant is also useful combined with gulp-concat, event-stream and yargs.

var concat = require('gulp-concat'),
    es = require('event-stream'),
    gulp = require('gulp'),
    ngConstant = require('gulp-ng-constant'),
    argv = require('yargs').argv;

var enviroment = argv.env || 'development';

gulp.task('config', function () {
  var config = gulp.src('config/' + enviroment + '.json')
    .pipe(ngConstant({name: 'app.config'}));
  var scripts = gulp.src('js/*');
  return es.merge(config, scripts)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('app/dist'))
    .on('error', function() { });
});

In my config folder I have these files:

ls -l config
total 8
-rw-r--r--+ 1 .. ci.json
-rw-r--r--+ 1 .. development.json
-rw-r--r--+ 1 .. production.json

Then you can run gulp config --env development and that will create something like this:

angular.module("app.config", [])
.constant("foo", "bar")
.constant("ngConstant", true);

I also have this spec:

beforeEach(module('app'));

it('loads the config', inject(function(config) {
  expect(config).toBeTruthy();
}));

How to access ssis package variables inside script component

First List the Variable that you want to use them in Script task at ReadOnlyVariables in the Script task editor and Edit the Script

To use your ReadOnlyVariables in script code

String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();

this line of code will treat the ssis package variable as a string.

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

Base64 encoding and decoding in oracle

I've implemented this to send Cyrillic e-mails through my MS Exchange server.

function to_base64(t in varchar2) return varchar2 is
 begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;

Try it.

upd: after a minor adjustment I came up with this, so it works both ways now:

function from_base64(t in varchar2) return varchar2 is
begin
  return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;

You can check it:

SQL> set serveroutput on
SQL> 
SQL> declare
  2    function to_base64(t in varchar2) return varchar2 is
  3    begin
  4      return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
  5    end to_base64;
  6  
  7    function from_base64(t in varchar2) return varchar2 is
  8    begin
  9      return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw    (t)));
 10    end from_base64;
 11  
 12  begin
 13    dbms_output.put_line(from_base64(to_base64('asdf')));
 14  end;
 15  /

asdf

PL/SQL procedure successfully completed

upd2: Ok, here's a sample conversion that works for CLOB I just came up with. Try to work it out for your blobs. :)

declare

  clobOriginal     clob;
  clobInBase64     clob;
  substring        varchar2(2000);
  n                pls_integer := 0;
  substring_length pls_integer := 2000;

  function to_base64(t in varchar2) return varchar2 is
  begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
  end to_base64;

  function from_base64(t in varchar2) return varchar2 is
  begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
  end from_base64;

begin

  select clobField into clobOriginal from clobTable where id = 1;

  while true loop

    /*we substract pieces of substring_length*/
    substring := dbms_lob.substr(clobOriginal,
                                 least(substring_length, substring_length * n + 1 - length(clobOriginal)),
                                 substring_length * n + 1);  
    /*if no substring is found  - then we've reached the end of blob*/

    if substring is null then
      exit;
    end if;  

    /*convert them to base64 encoding and stack it in new clob vadriable*/
    clobInBase64 := clobInBase64 || to_base64(substring);          
    n := n + 1;  

  end loop;

  n := 0;
  clobOriginal := null;

  /*then we do the very same thing backwards - decode base64*/
  while true loop 

    substring := dbms_lob.substr(clobInBase64,
                                 least(substring_length, substring_length * n + 1 - length(clobInBase64)),
                                 substring_length * n + 1);  
    if substring is null then
      exit;
    end if;  
    clobOriginal := clobOriginal || from_base64(substring);  
    n := n + 1;  
  end loop; 

      /*and insert the data in our sample table - to ensure it's the same*/
  insert into clobTable (id, anotherClobField) values (1, clobOriginal);

end;

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

Twitter Bootstrap 3: How to center a block

A few answers here seem incomplete. Here are several variations:

<style>
.box {
    height: 200px;
    width: 200px;
    border: 4px solid gray;
}
</style>    

<!-- This works: .container>.row>.center-block.box -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This does not work -->    
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This is the hybrid solution from other answers:
     .container>.row>.col-xs-6>.center-block.box
 -->   
<div class="container">
        <div class="row">
            <div class="col-xs-6 bg-info">
                <div class="center-block bg-primary box">This div is centered with .center-block</div>
            </div>
        </div>
    </div>

To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.

Check it out on bootply.

Resetting remote to a certain commit

On GitLab, you may have to set your branch to unprotected before doing this. You can do this in [repo] > Settings > Repository > Protected Branches. Then the method from Mark's answer works.

git reset --hard <commit-hash>
git push -f origin master

Capture close event on Bootstrap Modal

This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:

$("#myModal").on("hidden.bs.modal", function () {
    // put your default event here
});

Determine installed PowerShell version

You can look at the built in variable, $psversiontable. If it doesn't exist, you have V1. If it does exist, it will give you all the info you need.

1 >  $psversiontable

Name                           Value                                           
----                           -----                                           
CLRVersion                     2.0.50727.4927                                  
BuildVersion                   6.1.7600.16385                                  
PSVersion                      2.0                                             
WSManStackVersion              2.0                                             
PSCompatibleVersions           {1.0, 2.0}                                      
SerializationVersion           1.1.0.1                                         
PSRemotingProtocolVersion      2.1    

RecyclerView vs. ListView

I worked a little with RecyclerView and still prefer ListView.

  1. Sure, both of them use ViewHolders, so this is not an advantage.

  2. A RecyclerView is more difficult in coding.

  3. A RecyclerView doesn't contain a header and footer, so it's a minus.

  4. A ListView doesn't require to make a ViewHolder. In cases where you want to have a list with sections or subheaders it would be a good idea to make independent items (without a ViewHolder), it's easier and doesn't require separate classes.

Lombok annotations do not compile under Intellij idea

If you're using Intellij on Mac, this setup finally worked for me.

Installations: Intellij

  1. Go to Preferences, search for Plugins.
  2. Type "Lombok" in the plugin search box. Lombok is a non-bundled plugin, so it won't show at first.
  3. Click "Browse" to search for non-bundled plugins
  4. The "Lombok Plugin" should show up. Select it.
  5. Click the green "Install" button.
  6. Click the "Restart Intellij IDEA" button.

Settings:

  1. Enable Annotation processor

    • Go to Preferences -> Build, Execution,Deployment -->Preferences -> Compiler -> Annotation Processors
    • File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors
  2. Check if Lombok plugin is enabled

    • IntelliJ IDEA-> Preferences -> Other Settings -> Lombok plugin -> Enable Lombok
  3. Add Lombok jar in Global Libraries and project dependencies.

    • File --> Project Structure --> Global libraries (Add lombok.jar)
  4. File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok

  5. Restart Intellij

What are some examples of commonly used practices for naming git branches?

Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).

"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.

A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format man page).

So for every branch name that would be represented by a multi-word expression, using a '-' (dash) as a separator is a good idea.

Regex to match words of a certain length

Even, I was looking for the same regex but I wanted to include the all special character and blank spaces too. So here is the regex for that:

^[A-Za-z0-9\s$&+,:;=?@#|'<>.^*()%!-]{0,10}$

PHP: Get the key from an array in a foreach loop

Try this:

foreach($samplearr as $key => $item){
  print "<tr><td>" 
      . $key 
      . "</td><td>"  
      . $item['value1'] 
      . "</td><td>" 
      . $item['value2'] 
      . "</td></tr>";
}

Android disable screen timeout while app is running

This can be done by acquiring a Wake Lock.

I didn't tested it myself, but here is a small tutorial on this.

CSS table td width - fixed, not flexible

Chrome 37. for non fixed table:

td {
    width: 30px;
    max-width: 30px;
    overflow: hidden;
}

first two important! else - its flow away!

Get path to execution directory of Windows Forms application

string apppath = 
    (new System.IO.FileInfo
    (System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;

How to check if a string contains only digits in Java

Try this part of code:

void containsOnlyNumbers(String str)
{
    try {
        Integer num = Integer.valueOf(str);
        System.out.println("is a number");
    } catch (NumberFormatException e) {
        // TODO: handle exception
        System.out.println("is not a number");
    }

}

Full Screen DialogFragment in Android

I met the issue before when using a fullscreen dialogFragment: there is always a padding while having set fullscreen. try this code in dialogFragment's onActivityCreated() method:

public void onActivityCreated(Bundle savedInstanceState)
{   
    super.onActivityCreated(savedInstanceState);
    Window window = getDialog().getWindow();
    LayoutParams attributes = window.getAttributes();
    //must setBackgroundDrawable(TRANSPARENT) in onActivityCreated()
    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    if (needFullScreen)
    {
        window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
}

500 internal server error at GetResponse()

From that error, I would say that your code is fine, at least the part that calls the webservice. The error seems to be in the actual web service.

To get the error from the web server, add a try catch and catch a WebException. A WebException has a property called Response which is a HttpResponse. you can then log anything that is returned, and upload you code. Check back later in the logs and see what is actually being returned.

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

Trying to embed newline in a variable in bash

Try echo $'a\nb'.

If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:

var=$'a\nb\nc'
echo "$var"

Or, to fix your example program literally:

var="a b c"
for i in $var; do
    p="`echo -e "$p\\n$i"`"
done
echo "$p"

CSS Margin: 0 is not setting to 0

I just started learning CSS today and encountered the same problem and I think You don't need to reset style of all HTML tags. You need to reset default margin of top HTML You used, which is paragraph tag. And I know this is old question, but maybe my solution below will help somebody.

Try this:

body{   
    margin: 0; 
    background:#F0F0F0;
}
p{
    margin: 0;
}

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

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

You can easily check if string is empty with this:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

How to select where ID in Array Rails ActiveRecord without exception

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

Wait until flag=true

using non blocking javascript with EventTarget API

In my example, i need to wait for a callback before to use it. I have no idea when this callback is set. It can be before of after i need to execute it. And i can need to call it several time (everything async)

_x000D_
_x000D_
// bus to pass event_x000D_
const bus = new EventTarget();_x000D_
_x000D_
// it's magic_x000D_
const waitForCallback = new Promise((resolve, reject) => {_x000D_
    bus.addEventListener("initialized", (event) => {_x000D_
        resolve(event.detail);_x000D_
    });_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
// LET'S TEST IT !_x000D_
_x000D_
_x000D_
// launch before callback has been set_x000D_
waitForCallback.then((callback) => {_x000D_
    console.log(callback("world"));_x000D_
});_x000D_
_x000D_
_x000D_
// async init_x000D_
setTimeout(() => {_x000D_
    const callback = (param) => { return `hello ${param.toString()}`; }_x000D_
    bus.dispatchEvent(new CustomEvent("initialized", {detail: callback}));_x000D_
}, 500);_x000D_
_x000D_
_x000D_
// launch after callback has been set_x000D_
setTimeout(() => {_x000D_
    waitForCallback.then((callback) => {_x000D_
        console.log(callback("my little pony"));_x000D_
    });_x000D_
}, 1000);
_x000D_
_x000D_
_x000D_

Apache: client denied by server configuration

This code worked for me..

 <Location />
Allow from all
Order Deny,Allow
</Location> 

Hope this helps others

Is it possible to specify condition in Count()?

You can also use the Pivot Keyword if you are using SQL 2005 or above

more info and from Technet

SELECT *
FROM @Users
PIVOT (
    COUNT(Position)
    FOR Position
    IN (Manager, CEO, Employee)
) as p

Test Data Set

DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')

Java Try Catch Finally blocks without Catch

Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!

Controlling fps with requestAnimationFrame?

Here's a good explanation I found: CreativeJS.com, to wrap a setTimeou) call inside the function passed to requestAnimationFrame. My concern with a "plain" requestionAnimationFrame would be, "what if I only want it to animate three times a second?" Even with requestAnimationFrame (as opposed to setTimeout) is that it still wastes (some) amount of "energy" (meaning that the Browser code is doing something, and possibly slowing the system down) 60 or 120 or however many times a second, as opposed to only two or three times a second (as you might want).

Most of the time I run my browsers with JavaScript intentially off for just this reason. But, I'm using Yosemite 10.10.3, and I think there's some kind of timer problem with it - at least on my old system (relatively old - meaning 2011).

How to prevent SIGPIPEs (or handle them properly)

I'm super late to the party, but SO_NOSIGPIPE isn't portable, and might not work on your system (it seems to be a BSD thing).

A nice alternative if you're on, say, a Linux system without SO_NOSIGPIPE would be to set the MSG_NOSIGNAL flag on your send(2) call.

Example replacing write(...) by send(...,MSG_NOSIGNAL) (see nobar's comment)

char buf[888];
//write( sockfd, buf, sizeof(buf) );
send(    sockfd, buf, sizeof(buf), MSG_NOSIGNAL );

How to use regex in file find

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

Putty: Getting Server refused our key Error

When using Cpanel you can check if the key is authorized in

SSH Access >> Public keys >> Manage >> Authorize or Deauthorize.

What is the Java equivalent of PHP var_dump?

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

Simple example of threading in C++

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

Adding elements to object

function addValueInObject(object, key, value) {
    var res = {};
    var textObject = JSON.stringify(object);
    if (textObject === '{}') {
        res = JSON.parse('{"' + key + '":"' + value + '"}');
    } else {
        res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
    }
    return res;
}

this code is worked.

__init__() missing 1 required positional argument

You need to pass some data into it. An empty dictionary, for example.

if __name__ == '__main__': DHT('a').showData()

However, in your example a parameter is not even needed. You can declare it by just:

def __init__(self):

Maybe you mean to set it from the data?

class DHT:
    def __init__(self, data):
        self.data['one'] = data['one']
        self.data['two'] = data['two']
        self.data['three'] = data['three']
    def showData(self):
        print(self.data)

if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()

showData will print the data you just entered.

How to use target in location.href

Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?

How can I simulate a click to an anchor tag?

This would work in the cases where the window.open did not work

Proxy setting for R

For RStudio just you have to do this:

Firstly, open RStudio like always, select from the top menu:

Tools-Global Options-Packages

Uncheck the option: Use Internet Explorer library/proxy for HTTP

And then close the Rstudio, furthermore you have to:

  1. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents. Note that if it does not exist you can creat it just by writing this command in RStudio:

    file.edit('~/.Renviron')
    
  2. Add these two lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy="http://user_id:password@your_proxy:your_port"
    

And that's it..??!!!

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

How to "crop" a rectangular image into a square with CSS?

  1. Place your image in a div.
  2. Give your div explicit square dimensions.
  3. Set the CSS overflow property on the div to hidden (overflow:hidden).
  4. Put your imagine inside the div.
  5. Profit.

For example:

<div style="width:200px;height:200px;overflow:hidden">
    <img src="foo.png" />
</div>

Webpack.config how to just copy the index.html to the dist folder

I also found it easy and generic enough to put my index.html file in dist/ directory and add <script src='main.js'></script> to index.html to include my bundled webpack files. main.js seems to be default output name of our bundle if no other specified in webpack's conf file. I guess it's not good and long-term solution, but I hope it can help to understand how webpack works.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

What about casting to Number in Javascript using the Unary (+) Operator

lat: 12.23
lat: +12.23

Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which

Google Chrome Full Black Screen

if you can't see the chrome://flags because everything is black, and you don't want to revert your graphic driver as @wilfo did, then you can run google-chrome --disable-gpu from the console.

http://www.linuxquestions.org/questions/debian-26/chromium-doesn%27t-work-after-update-4175522748/

Running a simple shell script as a cronjob

What directory is file.txt in? cron runs jobs in your home directory, so unless your script cds somewhere else, that's where it's going to look for/create file.txt.

EDIT: When you refer to a file without specifying its full path (e.g. file.txt, as opposed to the full path /home/myUser/scripts/file.txt) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.

Thus, if you cd (change working directory) to the directory the script's in and then run it, file.txt will refer to a file in the same directory as the script. But if you don't cd there first, file.txt will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh or /home/myUser/scripts/test.sh; ./test.sh won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).

When you run a script from cron, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cds somewhere else or specifies an absolute path to the file.

What's the fastest way to do a bulk insert into Postgres?

It mostly depends on the (other) activity in the database. Operations like this effectively freeze the entire database for other sessions. Another consideration is the datamodel and the presence of constraints,triggers, etc.

My first approach is always: create a (temp) table with a structure similar to the target table (create table tmp AS select * from target where 1=0), and start by reading the file into the temp table. Then I check what can be checked: duplicates, keys that already exist in the target, etc.

Then I just do a "do insert into target select * from tmp" or similar.

If this fails, or takes too long, I abort it and consider other methods (temporarily dropping indexes/constraints, etc)

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

Questions every good Database/SQL developer should be able to answer

At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).

What and When to use Tuple?

The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

How to get the list of files in a directory in a shell script?

This is a way to do it where the syntax is simpler for me to understand:

yourfilenames=`ls ./*.txt`
for eachfile in $yourfilenames
do
   echo $eachfile
done

./ is the current working directory but could be replaced with any path
*.txt returns anything.txt
You can check what will be listed easily by typing the ls command straight into the terminal.

Basically, you create a variable yourfilenames containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with the ls command and the for loop syntax.

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

Break or return from Java 8 stream forEach?

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

Android SDK location

press WIN+R and from the run dialog run dialog Execute the following: **%appdata%..\Local\Android**

You should now be presented with Folder Explorer displaying the parent directory of the SDK.

How to concatenate strings in twig

You can use ~ like {{ foo ~ 'inline string' ~ bar.fieldName }}

But you can also create your own concat function to use it like in your question:
{{ concat('http://', app.request.host) }}:

In src/AppBundle/Twig/AppExtension.php

<?php

namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
        ];
    }

    public function concat()
    {
        return implode('', func_get_args())
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'app_extension';
    }
}

In app/config/services.yml:

services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

HTML - Alert Box when loading page

You can try this.

$(document).ready(function(){      
  alert();
     $('#rep??ortVariablesTable tbody').append( '<tr><td>lll</td><td>lll</td></tr>');
}); 

How do browser cookie domains work?

The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).

According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).

When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.

So, for example:

  • cookie attribute Domain=.example.com is equivalent to Domain=example.com
  • cookies with such Domain attributes will be available for example.com and www.example.com
  • cookies with such Domain attributes will be not available for another-example.com
  • specifying cookie attribute like Domain=www.example.com will close the way for www4.example.com

PS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(

Getting View's coordinates relative to the root layout

You can use `

view.getLocationOnScreen(int[] location)

;` to get location of your view correctly.

But there is a catch if you use it before layout has been inflated you will get wrong position.

Solution to this problem is adding ViewTreeObserver like this :-

Declare globally the array to store x y position of your view

 int[] img_coordinates = new int[2];

and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates

  // set a global layout listener which will be called when the layout pass is completed and the view is drawn
            parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {
                            //Remove the listener before proceeding
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }

                            // measure your views here
                            fab.getLocationOnScreen(img_coordinates);
                        }
                    }
            );

and then use it like this

xposition = img_coordinates[0];
yposition =  img_coordinates[1];

CMake: How to build external projects and include their targets

Edit: CMake now has builtin support for this. See new answer.

You can also force the build of the dependent target in a secondary make process

See my answer on a related topic.

How to delete the contents of a folder?

This:

  • removes all symbolic links
    • dead links
    • links to directories
    • links to files
  • removes subdirectories
  • does not remove the parent directory

Code:

for filename in os.listdir(dirpath):
    filepath = os.path.join(dirpath, filename)
    try:
        shutil.rmtree(filepath)
    except OSError:
        os.remove(filepath)

As many other answers, this does not try to adjust permissions to enable removal of files/directories.

How to create a number picker dialog?

For kotlin lovers.

fun numberPickerCustom() {
    val d = AlertDialog.Builder(context)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.number_picker_dialog, null)
    d.setTitle("Title")
    d.setMessage("Message")
    d.setView(dialogView)
    val numberPicker = dialogView.findViewById<NumberPicker>(R.id.dialog_number_picker)
    numberPicker.maxValue = 15
    numberPicker.minValue = 1
    numberPicker.wrapSelectorWheel = false
    numberPicker.setOnValueChangedListener { numberPicker, i, i1 -> println("onValueChange: ") }
    d.setPositiveButton("Done") { dialogInterface, i ->
        println("onClick: " + numberPicker.value)       
        }
    d.setNegativeButton("Cancel") { dialogInterface, i -> }
    val alertDialog = d.create()
    alertDialog.show()
}

and number_picker_dialog.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal">

    <NumberPicker
        android:id="@+id/dialog_number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

How do I make a placeholder for a 'select' box?

I see signs of correct answers, but to bring it all together, this would be my solution:

_x000D_
_x000D_
select {_x000D_
  color: grey;_x000D_
}_x000D_
_x000D_
option {_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
option[default] {_x000D_
   display: none;_x000D_
}
_x000D_
<select>_x000D_
    <option value="" default selected>Select your option</option>_x000D_
    <option value="hurr">Durr</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to add title to subplots in Matplotlib?

If you want to make it shorter, you could write :

import matplolib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()

It makes it maybe less clear but you don't need more lines or variables

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

How To: Best way to draw table in console app (C#)

It's easier in VisualBasic.net!

If you want the user to be able to manually enter data into a table:

Console.Write("Enter Data For Column 1: ")
    Dim Data1 As String = Console.ReadLine
    Console.Write("Enter Data For Column 2: ")
    Dim Data2 As String = Console.ReadLine

    Console.WriteLine("{0,-20} {1,-10} {2,-10}", "{Data Type}", "{Column 1}", "{Column 2}")
    Console.WriteLine("{0,-20} {1,-10} {2,-10}", "Data Entered:", Data1, Data2)

    Console.WriteLine("ENTER To Exit: ")
    Console.ReadLine()

It should look like this:

It should look like this (Click Me).

Java 6 Unsupported major.minor version 51.0

i also faced similar issue. I could able to solve this by setting JAVA_HOME in Environment variable in windows. Setting JAVA_HOME in batch file is not working in this case.

Adding to an ArrayList Java

thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D

import java.util.*;

public class HelloWorld {


public static void main(String[] Args) {

Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);        

    int First = list.get(1);
    int Second = list.get(2);

    if (First < Second) {

        System.out.println("One or more of your items have been restocked. The current stock is: " + First);

        Random rn = new Random();
int answer = rn.nextInt(99) + 1;

System.out.println("You are buying " + answer + " New stock");

First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}     
}  
}

How to return Json object from MVC controller to view

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});