Programs & Examples On #Latexmk

Saving images in Python at a very high quality

Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:

beingsaved = plt.figure()

# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)

beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)

MySQL: How to add one day to datetime field in query

It`s possible to use MySQL specific syntax sugar:

SELECT ... date_field + INTERVAL 1 DAY

Looks much more pretty instead of DATE_ADD function

Why is datetime.strptime not working in this simple example?

You should use strftime static method from datetime class from datetime module. Try:

import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")

bash export command

change from bash to sh scripting, make my script work.

!/bin/sh

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks

Matplotlib: "Unknown projection '3d'" error

First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.

Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")

I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.

If you're running version 0.99, try doing this instead of using using the projection keyword argument:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization! 
fig = plt.figure()

ax = Axes3D(fig) #<-- Note the difference from your original code...

X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()

This should work in matplotlib 1.0.x, as well, not just 0.99.

How to persist a property of type List<String> in JPA?

Use some JPA 2 implementation: it adds a @ElementCollection annotation, similar to the Hibernate one, that does exactly what you need. There's one example here.

Edit

As mentioned in the comments below, the correct JPA 2 implementation is

javax.persistence.ElementCollection

@ElementCollection
Map<Key, Value> collection;

See: http://docs.oracle.com/javaee/6/api/javax/persistence/ElementCollection.html

Import an existing git project into GitLab?

To keep ALL TAGS AND BRANCHES

Just simply run this command in an existing Git repository

cd existing_repo
git remote rename origin previous-hosts
git remote add gitlab [email protected]:hutber/kindred.com.git
git push -u gitlab --all
git push -u gitlab --tags

Is there a RegExp.escape function in JavaScript?

Another (much safer) approach is to escape all the characters (and not just a few special ones that we currently know) using the unicode escape format \u{code}:

function escapeRegExp(text) {
    return Array.from(text)
           .map(char => `\\u{${char.charCodeAt(0).toString(16)}}`)
           .join('');
}

console.log(escapeRegExp('a.b')); // '\u{61}\u{2e}\u{62}'

Please note that you need to pass the u flag for this method to work:

var expression = new RegExp(escapeRegExp(usersString), 'u');

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $("#type").change(function () {_x000D_
        var val = $(this).val();_x000D_
        if (val == "item1") {_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
        } else if (val == "item2") {_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
        } else if (val == "item3") {_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
        } else if (val == "item0") {_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Mysql 1050 Error "Table already exists" when in fact, it does not

I had this problem on Win7 in Sql Maestro for MySql 12.3. Enormously irritating, a show stopper in fact. Nothing helped, not even dropping and recreating the database. I have this same setup on XP and it works there, so after reading your answers about permissions I realized that it must be Win7 permissions related. So I ran MySql as administrator and even though Sql Maestro was run normally, the error disappeared. So it must have been a permissions issue between Win7 and MySql.

C# static class constructor

You can use static constructor to initialization static variable. Static constructor will be entry point for your class

public class MyClass
{

    static MyClass()
    {

        //write your initialization code here
    }

}

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("your.package.to.scan");
        return marshaller;
    }

Ruby capitalize every word first letter

"hello world".titleize which should output "Hello World".

Angular: How to update queryParams without changing route

First, we need to import the router module from angular router and declare its alias name

import { Router } from '@angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
    private router: Router ---> decalre alias name
  ) { }
}

1. You can change query params by using "router.navigate" function and pass the query parameters

this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
});

It will update query params in the current i.e activated route

  1. The below will redirect to abc page with _id, day and name as query params

    this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name: "dfd"} });

    It will update query params in the "abc" route along with three query paramters

For fetching query params:-

    import { ActivatedRoute } from '@angular/router'; //import activated routed

    export class ABC implements OnInit {

    constructor(
        private route: ActivatedRoute //declare its alias name
      ) {}

    ngOnInit(){
       console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
    }

Measuring execution time of a function in C++

If you want to safe time and lines of code you can make measuring the function execution time a one line macro:

a) Implement a time measuring class as already suggested above ( here is my implementation for android):

class MeasureExecutionTime{
private:
    const std::chrono::steady_clock::time_point begin;
    const std::string caller;
public:
    MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){}
    ~MeasureExecutionTime(){
        const auto duration=std::chrono::steady_clock::now()-begin;
        LOGD("ExecutionTime")<<"For "<<caller<<" is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<"ms";
    }
};

b) Add a convenient macro that uses the current function name as TAG (using a macro here is important, else __FUNCTION__ will evaluate to MeasureExecutionTime instead of the function you wanto to measure

#ifndef MEASURE_FUNCTION_EXECUTION_TIME
#define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__);
#endif

c) Write your macro at the begin of the function you want to measure. Example:

 void DecodeMJPEGtoANativeWindowBuffer(uvc_frame_t* frame_mjpeg,const ANativeWindow_Buffer& nativeWindowBuffer){
        MEASURE_FUNCTION_EXECUTION_TIME
        // Do some time-critical stuff 
}

Which will result int the following output:

ExecutionTime: For DecodeMJPEGtoANativeWindowBuffer is 54ms

Note that this (as all other suggested solutions) will measure the time between when your function was called and when it returned, not neccesarily the time your CPU was executing the function. However, if you don't give the scheduler any change to suspend your running code by calling sleep() or similar there is no difference between.

How to set the height of table header in UITableView?

I found a nice hack. Add the below line after modifying the frame propery

self.tableView.tableHeaderView = self.tableView.tableHeaderView;

The trick is (I think) that the UITableView is caching the height (the frame actually) when you assign the view to the tableHeaderView property. The above line just assigns the height again.

Write to rails console

I think you should use the Rails debug options:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

https://guides.rubyonrails.org/debugging_rails_applications.html

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

uint8_t vs unsigned char

Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).

How to vertically align an image inside a div

You can use this:

 .loaderimage {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 60px;
    height: 60px;
    margin-top: -30px; /* 50% of the height */
    margin-left: -30px;
 }

Pandas convert dataframe to array of tuples

Here's a vectorized approach (assuming the dataframe, data_set to be defined as df instead) that returns a list of tuples as shown:

>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()

produces:

[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
 (datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
 (datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
 (datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
 (datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
 (datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]

The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp value to it's corresponding datetime.datetime format equivalent by making use of the convert_datetime64 argument in DF.to_records which does so for a DateTimeIndex dataframe.

This returns a recarray which could be then made to return a list using .tolist


More generalized solution depending on the use case would be:

df.to_records().tolist()                              # Supply index=False to exclude index

How do you use script variables in psql?

You can try to use a WITH clause.

WITH vars AS (SELECT 42 AS answer, 3.14 AS appr_pi)
SELECT t.*, vars.answer, t.radius*vars.appr_pi
FROM table AS t, vars;

iOS 7: UITableView shows under status bar

Please note: This worked for me for the following configuration:

  • No navigation bar at the top of the screen (table view meets status bar)
  • Table view is non-scrollable

If the above two requirements aren't met your milage may vary.

Original Post

I created my view programmatically and this ended up working for me:

- (void) viewDidLayoutSubviews {
    // only works for iOS 7+
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CGRect viewBounds = self.view.bounds;
        CGFloat topBarOffset = self.topLayoutGuide.length;

        // snaps the view under the status bar (iOS 6 style)
        viewBounds.origin.y = topBarOffset * -1;

        // shrink the bounds of your view to compensate for the offset
        viewBounds.size.height = viewBounds.size.height + (topBarOffset * -1);
        self.view.bounds = viewBounds;
    }
}

Source (in topLayoutGuide section at bottom of pg.39).

How do I remove the non-numeric character from a string in java?

One more approach for removing all non-numeric characters from a string:

String newString = oldString.replaceAll("[^0-9]", "");

simple custom event

This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.

public partial class Form1 : Form
{
    private TestClass _testClass;
    public Form1()
    {
        InitializeComponent();
        _testClass = new TestClass();
        _testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
    }

    private void UpdateStatus(object sender, ProgressEventArgs e)
    {
        SetStatus(e.Status);
    }

    private void SetStatus(string status)
    {
        label1.Text = status;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
         TestClass.Func();
    }

}

public class TestClass
{
    public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
    public event StatusUpdateHandler OnUpdateStatus;

    public static void Func()
    {
        //time consuming code
        UpdateStatus(status);
        // time consuming code
        UpdateStatus(status);
    }

    private void UpdateStatus(string status)
    {
        // Make sure someone is listening to event
        if (OnUpdateStatus == null) return;

        ProgressEventArgs args = new ProgressEventArgs(status);
        OnUpdateStatus(this, args);
    }
}

public class ProgressEventArgs : EventArgs
{
    public string Status { get; private set; }

    public ProgressEventArgs(string status)
    {
        Status = status;
    }
}

Seeing the console's output in Visual Studio 2010?

In Program.cs, between:

static int Main(string[] agrs)
{

and the rest of your code, add:

#if DEBUG
    int rtn = Main2(args);
    Console.WriteLine("return " + rtn);
    Console.WriteLine("ENTER to continue.");
    Console.Read();
    return rtn;
}

static int Main2(string[] args)
{
#endif

Ruby: How to post a file via HTTP as multipart/form-data?

I like RestClient. It encapsulates net/http with cool features like multipart form data:

require 'rest_client'
RestClient.post('http://localhost:3000/foo', 
  :name_of_file_param => File.new('/path/to/file'))

It also supports streaming.

gem install rest-client will get you started.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I was facing this issue in ionic and tried many solutions but solved this by running this.

For MAC: node --max-old-space-size=4096 /usr/local/bin/ionic cordova build android --prod

For Windows: node --max-old-space-size=4096 /Users/{your user}/AppData/Roaming/npm/node_modules/ionic/bin/ionic cordova build windows --prod

How to call getClass() from a static method in Java?

Simply use a class literal, i.e. NameOfClass.class

How do I get whole and fractional parts from double in JSP/Java?

public class MyMain2 {
    public static void main(String[] args) {
        double myDub;
        myDub=1234.5678;
        long myLong;
        myLong=(int)myDub;
        myDub=(myDub%1)*10000;
        int myInt=(int)myDub;
        System.out.println(myLong + "\n" + myInt);
    }
}

How to display HTML <FORM> as inline element?

You can accomplish what you want, I think, simply by including the submit button within the paragraph:

     <pre>
     <p>Read this sentence  <input  type='submit' value='or push this button'/></p>
     </pre>   

How to add local jar files to a Maven project?

You can add local dependencies directly (as mentioned in build maven project with propriatery libraries included) like this:

<dependency>
    <groupId>com.sample</groupId>
    <artifactId>sample</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/Name_Your_JAR.jar</systemPath>
</dependency>

Update

In new releases this feature is marked as deprecated but still working and not removed yet ( You just see warning in the log during maven start). An issue is raised at maven group about this https://issues.apache.org/jira/browse/MNG-6523 ( You can participate and describe why this feature is helpful in some cases). I hope this feature remains there!

If you are asking me, as long as the feature is not removed, I use this to make dependency to only one naughty jar file in my project which is not fit in repository. If this feature is removed, well, there are lots of good answers here which I can chose from later!

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

"Missing return statement" within if / for / while

That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function returns? The compiler needs to know what to return in every possible execution of your function

Checking Java documentation:

Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.

This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).

You can do to solve your problem:

public String myMethod()
{
    String result = null;
    if(condition)
    {
       result = x;
    }
    return result;
}

Error: Unexpected value 'undefined' imported by the module

Had the same exception when tried to compile an Angular 5 application.

Unexpected value 'undefined' imported by the module 'DemoAppModule'

In my case it turned out it was a circular dependency which I found by using a tool madge. Found the files containing circular dependency by running

npx madge --circular --extensions ts src/

Get output parameter value in ADO.NET

You can get your result by below code::

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add other parameters parameters

    //Add the output parameter to the command object
    SqlParameter outPutParameter = new SqlParameter();
    outPutParameter.ParameterName = "@Id";
    outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
    outPutParameter.Direction = System.Data.ParameterDirection.Output;
    cmd.Parameters.Add(outPutParameter);

    conn.Open();
    cmd.ExecuteNonQuery();

    //Retrieve the value of the output parameter
    string Id = outPutParameter.Value.ToString();

    // *** read output parameter here, how?
    conn.Close();
}

Drop unused factor levels in a subsetted data frame

For the sake of completeness, now there is also fct_drop in the forcats package http://forcats.tidyverse.org/reference/fct_drop.html.

It differs from droplevels in the way it deals with NA:

f <- factor(c("a", "b", NA), exclude = NULL)

droplevels(f)
# [1] a    b    <NA>
# Levels: a b <NA>

forcats::fct_drop(f)
# [1] a    b    <NA>
# Levels: a b

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

IIS error, Unable to start debugging on the webserver

In my case it looks like Chrome locking some resources, preventing from debugger to attach. After I closing Chrome, I able to attach again.

Count number of rows matching a criteria

to get the number of observations the number of rows from your Dataset would be more valid:

nrow(dat[dat$sCode == "CA",])

AngularJS : ng-click not working

For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

pyplot axes labels for subplots

Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.

import numpy as np
import matplotlib.pyplot as plt

def set_shared_ylabel(a, ylabel, labelpad = 0.01):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0].get_position().y1
    bottom = a[-1].get_position().y0

    # get the coordinates of the left side of the tick labels 
    x0 = 1
    for at in a:
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
    tick_label_left = x0

    # set position of label
    a[-1].set_ylabel(ylabel)
    a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)

length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)

f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')

enter image description here

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

What is difference between mutable and immutable String in java

Case 1:

String str = "Good";
str = str + " Morning";

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

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

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

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

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

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

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

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

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

Count words in a string method?

import java.util.; import java.io.;

public class Main {

public static void main(String[] args) {

    File f=new File("src/MyFrame.java");
    String value=null;
    int i=0;
    int j=0;
    int k=0;
try {
    Scanner  in =new Scanner(f);
    while(in.hasNextLine())
    {
    String a=in.nextLine();
    k++; 
    char chars[]=a.toCharArray();
    i +=chars.length;
    }
    in.close();
    Scanner in2=new Scanner(f);
    while(in2.hasNext())
            {

        String b=in2.next();
        System.out.println(b);
        j++;
            }
   in2.close();

    System.out.println("the number of chars is :"+i);
    System.out.println("the number of words is :"+j);
    System.out.println("the number of lines is :"+k);





}
catch (Exception e) {
    e.printStackTrace();

}


}

}

Hadoop/Hive : Loading data from .csv on a local machine

if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.

You will need to use "Local" keyword when writing your load command.

Syntax for hiveload command

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables

What does <a href="#" class="view"> mean?

Javascript may be hooking up to the click-event of the anchor, rather than injecting any href.

For example, jQuery:

$('a.view').click(function() { Alert('anchor without a href was clicked');});

Of course, the javascript can do anything it wants with the click event--such as navigate to some other page (in which case the href is never set, but the anchor still behaves as though it were)

Npm install cannot find module 'semver'

if you are in Linux server exit from the server and re ssh

PHP: maximum execution time when importing .SQL data file

Set Only 3 Parameters from php.ini file of your server

A. max_execution_time = 3000000 (Set as per your requirment)
B. post_max_size = 4096M
C. upload_max_filesize = 4096M

Edit C:\xampp\phpMyAdmin\libraries\config.default.php Page

$cfg['ExecTimeLimit'] = 0;

After all set, restart your server and import again your database.

Done

Jenkins - passing variables between jobs?

I faced the same issue when I had to pass a pom version to a downstream Rundeck job.

What I did, was using parameters injection via a properties file as such:

1) Creating properties in properties file via shell :

Build actions:

  • Execute a shell script
  • Inject environment variables

E.g : properties definition

2) Passing defined properties to the downstream job : Post Build Actions :

  • Trigger parameterized build on other project
  • Add parameters : Current build parameters
  • Add parameters : predefined parameters

E.g : properties sending

3) It was then possible to use $POM_VERSION as such in the downstream Rundeck job.

/!\ Jenkins Version : 1.636

/!\ For some reason when creating the triggered build, it was necessary to add the option 'Current build parameters' to pass the properties.

How to Sort Multi-dimensional Array by Value?

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"order");

Changing background color of text box input not working when empty

You could have the CSS first style the textbox, then have js change it:

<input type="text" style="background-color: yellow;" id="subEmail" />

js:

function changeColor() {
  document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to enable file sharing for my app?

If you find by alphabet in plist, it should be "Application supports iTunes file sharing".

Bootstrap radio button "checked" flag

In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.

component.html

<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
   <label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio1" value="option1" type="radio"> TRUE
   </label>
   <label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio2" value="option2" type="radio"> FALSE
   </label>
</div>

component.ts file

@Component({
  selector: '',
  templateUrl: './.component.html',
  styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
  checked = true;
}

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Float a DIV on top of another DIV

Just add position, right and top to your class .close-image

.close-image {
    cursor: pointer;
    display: block;
    float: right;  
    z-index: 3;
    position: absolute; /*newly added*/
    right: 5px; /*newly added*/
    top: 5px;/*newly added*/
}

Label word wrapping

Ironically, turning off AutoSize by setting it to false allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

RegEx match open tags except XHTML self-contained tags

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n?erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege???x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the transgression of a chi?ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c??o??rrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg?ex parsers for HTML will ins?tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil?l devour your HT?ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi?ght he com?e?s, ?h?i?s un?ho?ly radian?ce? destro?ying all enli??^?ghtenment, HTML tags lea?ki¸n?g fr?o?m ?yo??ur eye?s? ?l?ik?e liq?uid pain, the song of re?gular exp?ression parsing will exti?nguish the voices of mor?tal man from the sp?here I can see it can you see _????i^??t´??_??_? it is beautiful t?he final snuffing of the lie?s of Man ALL IS LOS´???????T ALL I?S LOST the pon?y he comes he c??omes he comes the ich?or permeates all MY FACE MY FACE ?h god no NO NOO?O?O NT stop the an?*?????¯????g????????l??????????e¯?s ?a¸??r?????e n?ot re`???a?l~??????? ZA????LG? IS?^??????_ TO???????? TH?E??? ?P???O??N?Y? H???¯?"????E????`´¸??? ???¸??_???C???????_??O??????M????????_?E?????????S??????????


Have you tried using an XML parser instead?


Moderator's Note

This post is locked to prevent inappropriate edits to its content. The post looks exactly as it is supposed to look - there are no problems with its content. Please do not flag it for our attention.

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Algorithm to randomly generate an aesthetically-pleasing color palette

I would use a color wheel and given a random position you could add the golden angle (137,5 degrees)

http://en.wikipedia.org/wiki/Golden_angle

in order to get different colours each time that do not overlap.

Adjusting the brightness for the color wheel you could get also different bright/dark color combinations.

I've found this blog post that explains really well the problem and the solution using the golden ratio.

http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

UPDATE: I've just found this other approach:

It's called RYB(red, yellow, blue) method and it's described in this paper:

http://threekings.tk/mirror/ryb_TR.pdf

as "Paint Inspired Color Compositing".

The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones.

Here you can find a a good implementation in javascript:

http://afriggeri.github.com/RYB/

UPDATE 2:

The Sciences Po Medialb have just released a tool called "I want Hue" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page.

http://tools.medialab.sciences-po.fr/iwanthue/index.php

How can I display an image from a file in Jupyter Notebook?

This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)

from IPython.display import display
from PIL import Image


path="/path/to/image.jpg"
display(Image.open(path))

You may need to install PIL

in Anaconda this is done by typing

conda install pillow

How can I send large messages with Kafka (over 15MB)?

One key thing to remember that message.max.bytes attribute must be in sync with the consumer's fetch.message.max.bytes property. the fetch size must be at least as large as the maximum message size otherwise there could be situation where producers can send messages larger than the consumer can consume/fetch. It might worth taking a look at it.
Which version of Kafka you are using? Also provide some more details trace that you are getting. is there some thing like ... payload size of xxxx larger than 1000000 coming up in the log?

What is the difference between the dot (.) operator and -> in C++?

The target. dot works on objects; arrow works on pointers to objects.

std::string str("foo");
std::string * pstr = new std::string("foo");

str.size ();
pstr->size ();

UITableViewCell Selected Background Color on Multiple Selection

The problem with Kersnowski's approach is that when the cell is redrawn the changes made when it's selected/deselected will be gone. So I would move the changes into the cell itself, which means subclassing is required here. For example:

class ICComplaintCategoryCell: UITableViewCell {
    @IBOutlet var label_title: UILabel!
    @IBOutlet var label_checkmark: UILabel!

    override func layoutSubviews() {
        super.layoutSubviews()
        reload()
    }
    func reload() {
        if isSelected {
            contentView.backgroundColor = UIColor.red
        }
        else if isHighlighted{
            contentView.backgroundColor = UIColor.red
        }
        else {
            contentView.backgroundColor = UIColor.white
        }
    }
}

And in your table view delegate just call reload:

if let cell = self.table.cellForRowAtIndexPath(path) as? ICComplaintCategoryCell {
    cell.reload()
}

Updated for Swift 3+, thanks @Bogy

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Pass arguments into C program from command line

Instead of getopt(), you may also consider using argp_parse() (an alternative interface to the same library).

From libc manual:

getopt is more standard (the short-option only version of it is a part of the POSIX standard), but using argp_parse is often easier, both for very simple and very complex option structures, because it does more of the dirty work for you.

But I was always happy with the standard getopt.

N.B. GNU getopt with getopt_long is GNU LGPL.

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

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

Angular - ng: command not found

In my case

OS Version: Ubuntu 18.04.4 LTS

Node version v12.16.0

Remove ng from /usr/local/bin by using below command.

sudo rm -r ng

After that, installed ng by using command mentioned below.

sudo npm install -g @angular/cli

javax.persistence.NoResultException: No entity found for query

You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?

if (query.list().size() == 1) 

Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.

How to refresh Android listview?

if you are not still satisfied with ListView Refreshment, you can look at this snippet,this is for loading the listView from DB, Actually what you have to do is simply reload the ListView,after you perform any CRUD Operation Its not a best way to code, but it will refresh the ListView as you wish..

It works for Me....if u find better solution,please Share...

.......
......
do your CRUD Operations..
......
.....
DBAdapter.open();
DBAdapter.insert_into_SingleList();
// Bring that DB_results and add it to list as its contents....
                                            ls2.setAdapter(new ArrayAdapter(DynTABSample.this,
    android.R.layout.simple_list_item_1,                        DBAdapter.DB_ListView));
                                            DBAdapter.close();

Executing Shell Scripts from the OS X Dock?

As long as your script is executable and doesn't have any extension you can drag it as-is to the right side (Document side) of the Dock and it will run in a terminal window when clicked instead of opening an editor.

If you want to have an extension (like foo.sh), you can go to the file info window in Finder and change the default application for that particular script from whatever it is (TextEdit, TextMate, whatever default is set on your computer for .sh files) to Terminal. It will then just execute instead of opening in a text editor. Again, you will have to drag it to the right side of the Dock.

Reset/remove CSS styles for element only

Let me answer this question thoroughly, because it's been a source of pain for me for several years and very few people really understand the problem and why it's important for it to be solved. If I were at all responsible for the CSS spec I'd be embarrassed, frankly, for having not addressed this in the last decade.

The Problem

You need to insert markup into an HTML document, and it needs to look a specific way. Furthermore, you do not own this document, so you cannot change existing style rules. You have no idea what the style sheets could be, or what they may change to.

Use cases for this are when you are providing a displayable component for unknown 3rd party websites to use. Examples of this would be:

  1. An ad tag
  2. Building a browser extension that inserts content
  3. Any type of widget

Simplest Fix

Put everything in an iframe. This has it's own set of limitations:

  1. Cross Domain limitations: Your content will not have access to the original document at all. You cannot overlay content, modify the DOM, etc.
  2. Display Limitations: Your content is locked inside of a rectangle.

If your content can fit into a box, you can get around problem #1 by having your content write an iframe and explicitly set the content, thus skirting around the issue, since the iframe and document will share the same domain.

CSS Solution

I've search far and wide for the solution to this, but there are unfortunately none. The best you can do is explicitly override all possible properties that can be overridden, and override them to what you think their default value should be.

Even when you override, there is no way to ensure a more targeted CSS rule won't override yours. The best you can do here is to have your override rules target as specifically as possible and hope the parent document doesn't accidentally best it: use an obscure or random ID on your content's parent element, and use !important on all property value definitions.

How to convert a PNG image to a SVG?

I just found this question and answers as I am trying to do the same thing! I did not want to use some of the other tools mentioned. (Don't want to give my email away, and don't want to pay). I found that Inkscape (v0.91) can do a pretty good job. This tutorial is quick to and easy to understand.

Its as simple as selecting your bitmap in Inkskape and Shift+Alt+B.

Edge Detection with Inksape Trace bitmap tool based on potrace

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

ORA-00972 identifier is too long alias column name

If you have recently upgraded springboot to 1.4.3, you might need to make changes to yml file:

yml in 1.3 :

jpa: 
  hibernate: 
    namingStrategy: org.hibernate.cfg.EJB3NamingStrategy

yml in 1.4.3 :

jpa: 
  hibernate: 
    naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How to use environment variables in docker compose

The best way is to specify environment variables outside the docker-compose.yml file. You can use env_file setting, and define your environment file within the same line. Then doing a docker-compose up again should recreate the containers with the new environment variables.

Here is how my docker-compose.yml looks like:

services:
  web:
    env_file: variables.env

Note: docker-compose expects each line in an env file to be in VAR=VAL format. Avoid using export inside the .env file. Also, the .env file should be placed in the folder where the docker-compose command is executed.

How do I import .sql files into SQLite 3?

Alternatively, you can do this from a Windows commandline prompt/batch file:

sqlite3.exe DB.db ".read db.sql"

Where DB.db is the database file, and db.sql is the SQL file to run/import.

Read input numbers separated by spaces

By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:

do {
   cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
   cin >> num;

   // reset your variables

   // your function stuff (calculations)
}
while (true); // or some condition

How does += (plus equal) work?

That is just a short form for:

sum = sum + value;

How can I check if a scrollbar is visible?

Here's my improvement: added parseInt. for some weird reason it didn't work without it.

// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
    $.fn.hasVerticalScrollBar = function() {
        return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
    };
})(jQuery);

Share cookie between subdomain and domain

Be careful if you are working on localhost ! If you store your cookie in js like this:

document.cookie = "key=value;domain=localhost"

It might not be accessible to your subdomain, like sub.localhost. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName localhost.com then you will be able to store your cookie on your domain and subdomain like this:

document.cookie = "key=value;domain=localhost.com"

svn : how to create a branch from certain revision of trunk

$ svn copy http://svn.example.com/repos/calc/trunk@192 \
   http://svn.example.com/repos/calc/branches/my-calc-branch \
   -m "Creating a private branch of /calc/trunk."

Where 192 is the revision you specify

You can find this information from the SVN Book, specifically here on the page about svn copy

What is Parse/parsing?

Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.

Example of parsing using indexOf to calculate the position of a string in another string:

String s="What a Beautiful day!";

int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8

paresInt essentially converts a String to a Integer.

String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);

Output:

Constructor method: 9876543

parseInt() method: 9876543

Node.js check if file exists

  fs.statSync(path, function(err, stat){
      if(err == null) {
          console.log('File exists');
          //code when all ok
      }else if (err.code == "ENOENT") {
        //file doesn't exist
        console.log('not file');

      }
      else {
        console.log('Some other error: ', err.code);
      }
    });

Using json_encode on objects in PHP (regardless of scope)

I didn't see this mentioned yet, but beans have a built-in method called getProperties().

So, to use it:

// What bean do we want to get?
$type = 'book';
$id = 13;

// Load the bean
$post = R::load($type,$id);

// Get the properties
$props = $post->getProperties();

// Print the JSON-encoded value
print json_encode($props);

This outputs:

{
    "id": "13",
    "title": "Oliver Twist",
    "author": "Charles Dickens"
}

Now take it a step further. If we have an array of beans...

// An array of beans (just an example)
$series = array($post,$post,$post);

...then we could do the following:

  • Loop through the array with a foreach loop.

  • Replace each element (a bean) with an array of the bean's properties.

So this...

foreach ($series as &$val) {
  $val = $val->getProperties();
}

print json_encode($series);

...outputs this:

[
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    }
]

Hope this helps!

Getting Image from URL (Java)

Try:

public class ImageComponent extends JComponent {
  private final BufferedImage img;

  public ImageComponent(URL url) throws IOException {
    img = ImageIO.read(url);
    setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));

  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
  }

  public static void main(String[] args) throws Exception {
    final URL kitten = new URL("https://placekitten.com/g/200/300");

    final ImageComponent image = new ImageComponent(kitten);

    JFrame frame = new JFrame("Test");
    frame.add(new JScrollPane(image));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}

Powershell Execute remote exe with command line arguments on remote computer

Are you trying to pass the command line arguments to the program AS you launch it? I am working on something right now that does exactly this, and it was a lot simpler than I thought. If I go into the command line, and type

C:\folder\app.exe/xC:\folder\file.txt

then my application launches, and creates a file in the specified directory with the specified name.

I wanted to do this through a Powershell script on a remote machine, and figured out that all I needed to do was put

$s = New-PSSession -computername NAME -credential LOGIN
    Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s

(I have a bunch more similar commands inside the session, this is just the minimum it requires to run) notice the space between the executable, and the command line arguments. It works for me, but I am not sure exactly how your application works, or if that is even how you pass arguments to it.

*I can also have my application push the file back to my own local computer by changing the script-block to

C:\folder\app.exe /x"\\LocalPC\DATA (C)\localfolder\localfile.txt"

You need the quotes if your file-path has a space in it.

EDIT: actually, this brought up some silly problems with Powershell launching the application as a service or something, so I did some searching, and figured out that you can call CMD to execute commands for you on the remote computer. This way, the command is carried out EXACTLY as if you had just typed it into a CMD window on the remote machine. Put the command in the scriptblock into double quotes, and then put a cmd.exe /C before it. like this:

cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"

this solved all of the problems that I have been having recently.

EDIT EDIT: Had more problems, and found a much better way to do it.

start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"

and this doesn't hang up your terminal window waiting for the remote process to end. Just make sure you have a way to terminate the process if it doesn't do that on it's own. (mine doesn't, required the coding of another argument)

Number of processors/cores in command line

The lscpu(1) command provided by the util-linux project might also be useful:

$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 58
Model name:            Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
Stepping:              9
CPU MHz:               3406.253
CPU max MHz:           3600.0000
CPU min MHz:           1200.0000
BogoMIPS:              5787.10
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3

Convert from List into IEnumerable format

Why not use a Single liner ...

IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;

How to remove error about glyphicons-halflings-regular.woff2 not found

For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2 MIME type, only about .woff. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2, then updated .woff.)

Second, and more importantly, I was bundling bootstrap.css along with some other files as "~/bundles/css/site". Meanwhile, my font files were in "~/fonts". bootstrap.css looks for the glyphicon fonts in "../fonts", which translated to "~/bundles/fonts" -- wrong path.

In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss", and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts" for the glyphicon files, which worked. Problem solved.

Before I fixed the second problem above, none of the glyphicon font files were loading. The symptom was that all instances of glyphicon glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.

SVN "Already Locked Error"

After discussing with the hosting of my SVN repository they gave me the following answer.

Apparently my repository is replicated to a remote repository using SVNSYNC. SVNSYNC has known limitations with enforcing locking across the replicated repositories and this is where the problem lies.

The locks were introduced by the AnkhSVN plugin in Visual Studio.

As the locks appears to be on the remote repository this explains why I can't actually see them using SVN commands.

The locks are being removed via the hosting company and hopefully all will soon be well again.

How to inflate one view with a layout

I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

Change input text border color without changing its height

This css solution worked for me:

input:active,
input:focus {
    border: 1px solid #red
}

input:active,
input:focus {
    padding: 2px solid #red /*for firefox and chrome*/
}

/* .ie is a class you would need to set at the html root level */
.ie input:active,
.ie input:focus {
    padding: 3px solid #red /* IE needs 1px extra padding*/
}

I understand it is not necessary on FF and Chrome, but IE needs it. And there are circumstances when you need it.

anaconda update all possible packages?

To answer more precisely to the question:

conda (which is conda for miniconda as for Anaconda) updates all but ONLY within a specific version of a package -> major and minor. That's the paradigm.

In the documentation you will find "NOTE: Conda updates to the highest version in its series, so Python 2.7 updates to the highest available in the 2.x series and 3.6 updates to the highest available in the 3.x series." doc

If Wang does not gives a reproducible example, one can only assist. e.g. is it really the virtual environment he wants to update or could Wang get what he/she wants with

conda update -n ENVIRONMENT --all

*PLEASE read the docs before executing "update --all"! This does not lead to an update of all packages by nature. Because conda tries to resolve the relationship of dependencies between all packages in your environment, this can lead to DOWNGRADED packages without warnings.


If you only want to update almost all, you can create a pin file

echo "conda ==4.0.0" >> ~/miniconda3/envs/py35/conda-meta/pinned
echo "numpy 1.7.*" >> ~/miniconda3/envs/py35/conda-meta/pinned

before running the update. conda issues not pinned

If later on you want to ignore the file in your env for an update, you can do:

conda update --all --no-pin

You should not do update --all. If you need it nevertheless you are saver to test this in a cloned environment.

First step should always be to backup your current specification:

conda list -n py35 --explicit 

(but even so there is not always a link to the source available - like for jupyterlab extensions)

Next you can clone and update:

conda create -n py356 --clone py35

conda activate py356
conda config --set pip_interop_enabled True # for conda>=4.6
conda update --all

conda config


update:

Because the idea of conda is nice but it is not working out very well for complex environments I personally prefer the combination of nix-shell (or lorri) and poetry [as superior pip/conda .-)] (intro poetry2nix).

Alternatively you can use nix and mach-nix (where you only need you requirements file. It resolves and builds environments best.


On Linux / macOS you could use nix like

nix-env -iA nixpkgs.python37

to enter an environment that has e.g. in this case Python3.7 (for sure you can change the version)

or as a very good Python (advanced) environment you can use mach-nix (with nix) like

mach-nix env ./env -r requirements.txt 

(which even supports conda [but currently in beta])

or via api like

nix-shell -p nixFlakes --run "nix run github:davhau/mach-nix#with.ipython.pandas.seaborn.bokeh.scikit-learn "

Finally if you really need to work with packages that are not compatible due to its dependencies, it is possible with technologies like NixOS/nix-pkgs.

Owl Carousel Won't Autoplay

Your Javascript should be

<script>
$("#intro").owlCarousel({

// Most important owl features

//Autoplay
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true
)}
</script>

Can I change the headers of the HTTP request sent by the browser?

I would partially disagree with Milan's suggestion of embedding the requested representation in the URI.

If anyhow possible, URIs should only be used for addressing resources and not for tunneling HTTP methods/verbs. Eventually, specific business action (edit, lock, etc.) could be embedded in the URI if create (POST) or update (PUT) alone do not serve the purpose:

POST http://shonzilla.com/orders/08/165;edit

In the case of requesting a particular representation in URI you would need to disrupt your URI design eventually making it uglier, mixing two distinct REST concepts in the same place (i.e. URI) and making it harder to generically process requests on the server-side. What Milan is suggesting and many are doing the same, incl. Flickr, is exactly this.

Instead, a more RESTful approach would be using a separate place to encode preferred representation by using Accept HTTP header which is used for content negotiation where client tells to the server which content types it can handle/process and server tries to fulfill client's request. This approach is a part of HTTP 1.1 standard, software compliant and supported by web browsers as well.

Compare this:

GET /orders/08/165.xml HTTP/1.1
or
GET /orders/08/165&format=xml HTTP/1.1

to this:

GET /orders/08/165 HTTP/1.1
Accept: application/xml

From a web browser you can request any content type by using setRequestHeader method of XMLHttpRequest object. For example:

function getOrder(year, yearlyOrderId, contentType) {
 var client = new XMLHttpRequest();
 client.open("GET", "/order/" + year + "/" + yearlyOrderId);
 client.setRequestHeader("Accept", contentType);
 client.send(orderDetails);
}

To sum it up: the address, i.e. the URI of a resource should be independent of its representation and XMLHttpRequest.setRequestHeader method allows you to request any representation using the Accept HTTP header.

Cheers!
Shonzilla

How can I change the color of a Google Maps marker?

MapIconMaker: a library for Google Maps v2

One way is to use the MapIconMaker(deadlink). There's an example here(deadlink). Google Maps default icons are 20px width and 34px height, so you could use something like this to emulate:

var newIcon = MapIconMaker.createMarkerIcon({width: 20, height: 34, primaryColor: "#0000FF", cornercolor:"#0000FF"});
var marker = new GMarker(map.getCenter(), {icon: newIcon});

You could even wrap it in some function to make things even easier on yourself:

function getIcon(color) {
    return MapIconMaker.createMarkerIcon({width: 20, height: 34, primaryColor: color, cornercolor:color});
}

That's what I personally use for all markers I create. I prefer to have the option to change colors of a whim.

Update: The Hex color of the default icon is "#FE7569". Also, you can setImage on a Marker rather than creating a new Marker with a new icon. So if you want a function to highlight you could go with something like this, using the function above:

function highlightMarker(marker, highlight) {
    var color = "#FE7569";
    if (highlight) {
        color = "#0000FF";
    }
    marker.setImage(getIcon(color).image);
}

StyledMarker: a library for Google Maps v3

Since V2 was replaced by V3 sometime ago I thought I should update this answer. I created a library for custom markers that can be found on the V3 Utility Library here(deadlink). It allows for different colors and shapes, and you can place text on the marker as well. It works by using the Google Charts API which has methods for creating Google Maps type markers. Feel free to look at the source code if you'd rather use the Google Charts API directly.

The thing about that library, however, is that it takes care of defining the clickable regions of these marker images for you, so, for instance, the longer bubble with text will have the clickable regions one expects, like this example(deadlink).

How to properly upgrade node using nvm

if you have 4.2 and want to install 5.0.0 then

nvm install v5.0.0 --reinstall-packages-from=4.2

the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

source: sitepoint

Error 1053 the service did not respond to the start or control request in a timely fashion

In case you have a windows form used for testing, ensure that the startup object is still the service and not the windows form

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

Perform an action in every sub-directory using Bash

find . -type d -print0 | xargs -0 -n 1 my_command

Get list of databases from SQL Server

Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:

    SELECT  db.[name] as dbname 
    FROM [master].[sys].[databases] db
    LEFT OUTER JOIN  [master].[sys].[sysusers] su on su.sid = db.owner_sid
    WHERE su.sid is null
    order by db.[name]

Can't import database through phpmyadmin file size too large

If you are using MySQL in Xampp then do the steps below.

Find the following in XAMPP control panel>Apach-Config> PHP (php.ini) file

  • post_max_size = 8M

  • upload_max_filesize = 2M

  • max_execution_time = 30
  • ut_time = 60enter code here memory_limit = 8M

And change their sizes according to your need. I'm using these values

post_max_size = 30M
upload_max_filesize = 30M
max_execution_time = 4500
max_input_time = 4500
memory_limit = 850M

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

What you're asking for is extremely hard. If possible, getting the user to specify the encoding is the best. Preventing an attack shouldn't be much easier or harder that way.

However, you could try doing this:

iconv(mb_detect_encoding($text, mb_detect_order(), true), "UTF-8", $text);

Setting it to strict might help you get a better result.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How to remove \xa0 from string in Python?

0xA0 (Unicode) is 0xC2A0 in UTF-8. .encode('utf8') will just take your Unicode 0xA0 and replace with UTF-8's 0xC2A0. Hence the apparition of 0xC2s... Encoding is not replacing, as you've probably realized now.

Can I scale a div's height proportionally to its width using CSS?

You could assign both the width and height of the element using either vw or vh. For example:

#anyElement {
    width: 20vh;
    height: 20vh;
}

This would set both the width and height to 20% of the browser's current height, retaining the aspect ratio. However, this only works if you want to scale proportionate to the viewport dimensions.

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

SQL Order By Count

You need to aggregate the data first, this can be done using the GROUP BY clause:

SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC

The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

Get the current cell in Excel VB

Have you tried:

For one cell:

ActiveCell.Select

For multiple selected cells:

Selection.Range

For example:

Dim rng As Range
Set rng = Range(Selection.Address)

Viewing local storage contents on IE

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

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

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

Removing Duplicate Values from ArrayList

     public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
                 if(((Contact)o1).getId().equalsIgnoreCase(((Contact)2).getId()) ) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);
    final List newList = new ArrayList(set);
    return newList;
}

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

ORDER_BY cast(registration_no as unsigned) ASC

gives the desired result with warnings.

Hence, better to go for

ORDER_BY registration_no + 0 ASC

for a clean result without any SQL warnings.

git visual diff between branches

Here is how to see the visual diff between whole commits, as opposed to single files, in Visual Studio (tested in VS 2017). Unfortunately, it works only for commits within one branch: In the "Team Explorer", choose the "Branches" view, right-click on the repo, and choose "View history" as in the following image.

enter image description here

Then the history of the current branch appears in the main area. (Where branches that ended as earlier commits on the current branch are marked by labels.) Now select a couple of commits with Ctrl-Left, then right click and select "Compare Commits..." from the pop-up menu.

For more on comparing branches in the Microsoft world, see this stackoverflow question: Differences between git branches using Visual Studio.

where does MySQL store database files?

another way from MySQL Workbench:

enter image description here

What do two question marks together mean in C#?

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

JavaScript: What are .extend and .prototype used for?

Some extend functions in third party libraries are more complex than others. Knockout.js for instance contains a minimally simple one that doesn't have some of the checks that jQuery's does:

function extend(target, source) {
    if (source) {
        for(var prop in source) {
            if(source.hasOwnProperty(prop)) {
                target[prop] = source[prop];
            }
        }
    }
    return target;
}

WebAPI to Return XML

If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.

If you return a string, you'll get a string.

How do I get hour and minutes from NSDate?

Swift 2.0

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
    let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
    print(String(hour))
    print(String(minute))

Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:

var hoursString = String(hour)
var minutesString = String(minute)

Then you can concatenate values like this:

var compoundString = "\(hour):\(minute)"
print(compoundString)

What are the rules for calling the superclass constructor?

If you have a constructor without arguments it will be called before the derived class constructor gets executed.

If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:

class base
{
  public:
  base (int arg)
  {
  }
};

class derived : public base
{
  public:
  derived () : base (number)
  {
  }
};

You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.

How do I get a list of files in a directory in C++?

If you're in Windows & using MSVC, the MSDN library has sample code that does this.

And here's the code from that link:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>

void ErrorHandler(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 2 is not longer than MAX_PATH.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 2))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
      return dwError;
   } 

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}


void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

What is the correct XPath for choosing attributes that contain "foo"?

John C is the closest, but XPath is case sensitive, so the correct XPath would be:

/bla/a[contains(@prop, 'Foo')]

How do I pass multiple attributes into an Angular.js attribute directive?

You do it exactly the same way as you would with an element directive. You will have them in the attrs object, my sample has them two-way binding via the isolate scope but that's not required. If you're using an isolated scope you can access the attributes with scope.$eval(attrs.sample) or simply scope.sample, but they may not be defined at linking depending on your situation.

app.directive('sample', function () {
    return {
        restrict: 'A',
        scope: {
            'sample' : '=',
            'another' : '='
        },
        link: function (scope, element, attrs) {
            console.log(attrs);
            scope.$watch('sample', function (newVal) {
                console.log('sample', newVal);
            });
            scope.$watch('another', function (newVal) {
                console.log('another', newVal);
            });
        }
    };
});

used as:

<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

How to loop through a collection that supports IEnumerable?

foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}

JavaScript - Use variable in string match

You have to use RegExp object if your pattern is string

var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);

If pattern is not dynamic string:

var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);

How is AngularJS different from jQuery

  1. While Angular 1 was a framework, Angular 2 is a platform. (ref)

To developers, Angular2 provides some features beyond showing data on screen. For example, using angular2 cli tool can help you "pre-compile" your code and generate necessary javascript code (tree-shaking) to shrink the download size down to 35Kish.

  1. Angular2 emulated Shadow DOM. (ref)

This opens a door for server rendering that can address SEO issue and work with Nativescript etc that don't work on browsers.

AngularJS is a framework. It has following features

  1. Two way data binding
  2. MVW pattern (MVC-ish)
  3. Template
  4. Custom-directive (reusable components, custom markup)
  5. REST-friendly
  6. Deep Linking (set up a link for any dynamic page)
  7. Form Validation
  8. Server Communication
  9. Localization
  10. Dependency injection
  11. Full testing environment (both unit, e2e)

check this presentation and this great introduction

Don't forget to read the official developer guide

Or learn it from these awesome video tutorials

If you want to watch more tutorial video, check out this post, Collection of best 60+ AngularJS tutorials.

You can use jQuery with AngularJS without any issue.

In fact, AngularJS uses jQuery lite in it, which is a great tool.

From FAQ

Does Angular use the jQuery library?

Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.

However, don't try to use jQuery to modify the DOM in AngularJS controllers, do it in your directives.

Update:

Angular2 is released. Here is a great list of resource for starters

Can I get JSON to load into an OrderedDict?

You could always write out the list of keys in addition to dumping the dict, and then reconstruct the OrderedDict by iterating through the list?

Safely casting long to int in Java

here is a solution, in case you don't care about value in case it is bigger then needed ;)

public static int safeLongToInt(long l) {
    return (int) Math.max(Math.min(Integer.MAX_VALUE, l), Integer.MIN_VALUE);
}

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.

mvn clean install

Mockito, JUnit and Spring

The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner. Check out this part of the documentation.

In your case you could write your Spring integration test and still use mocks like this:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    @InjectMocks
    TestTarget sut;

    @Mock
    Foo mockFoo;

    @Test
    public void someTest() {
         // ....
    }
}

How to execute a shell script from C in Linux?

You can use system:

system("/usr/local/bin/foo.sh");

This will block while executing it using sh -c, then return the status code.

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Fully custom validation error message with Rails

If you want to list them all in a nice list but without using the cruddy non human friendly name, you can do this...

object.errors.each do |attr,message|
  puts "<li>"+message+"</li>"
end

Remove an onclick listener

mTitleView.setOnClickListener(null) should do the trick.

A better design might be to do a check of the status in the OnClickListener and then determine whether or not the click should do something vs adding and clearing click listeners.

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

How to get object size in memory?

Unmanaged object:

  • Marshal.SizeOf(object yourObj);

Value Types:

  • sizeof(object val)

Managed object:

Font scaling based on width of container

Use CSS Variables

No one has mentioned CSS variables yet, and this approach worked best for me, so:

Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:

<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>

And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.

p {
  font-size: calc( var(--column-width) / 100 );
}

It's not a pure CSS approach, but it's pretty close.

Including dependencies in a jar with Maven

Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <descriptorRefs>
                <descriptorRef>dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>
</plugins>

Any way to Invoke a private method?

If the method accepts non-primitive data type then the following method can be used to invoke a private method of any class:

public static Object genericInvokeMethod(Object obj, String methodName,
            Object... params) {
        int paramCount = params.length;
        Method method;
        Object requiredObj = null;
        Class<?>[] classArray = new Class<?>[paramCount];
        for (int i = 0; i < paramCount; i++) {
            classArray[i] = params[i].getClass();
        }
        try {
            method = obj.getClass().getDeclaredMethod(methodName, classArray);
            method.setAccessible(true);
            requiredObj = method.invoke(obj, params);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return requiredObj;
    }

The Parameter accepted are obj, methodName and the parameters. For example

public class Test {
private String concatString(String a, String b) {
    return (a+b);
}
}

Method concatString can be invoked as

Test t = new Test();
    String str = (String) genericInvokeMethod(t, "concatString", "Hello", "Mr.x");

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

What is the idiomatic Go equivalent of C's ternary operator?

eold's answer is interesting and creative, perhaps even clever.

However, it would be recommended to instead do:

var index int
if val > 0 {
    index = printPositiveAndReturn(val)
} else {
    index = slowlyReturn(-val)  // or slowlyNegate(val)
}

Yes, they both compile down to essentially the same assembly, however this code is much more legible than calling an anonymous function just to return a value that could have been written to the variable in the first place.

Basically, simple and clear code is better than creative code.

Additionally, any code using a map literal is not a good idea, because maps are not lightweight at all in Go. Since Go 1.3, random iteration order for small maps is guaranteed, and to enforce this, it's gotten quite a bit less efficient memory-wise for small maps.

As a result, making and removing numerous small maps is both space-consuming and time-consuming. I had a piece of code that used a small map (two or three keys, are likely, but common use case was only one entry) But the code was dog slow. We're talking at least 3 orders of magnitude slower than the same code rewritten to use a dual slice key[index]=>data[index] map. And likely was more. As some operations that were previously taking a couple of minutes to run, started completing in milliseconds.\

How to check if command line tools is installed

From a programmatic perspective the Homebrew folks have a check for the existence of various files to determine if the command line tools are installed. Currently it always checks for /Library/Developer/CommandLineTools/usr/bin/git and will also check for /usr/include/iconv.h if the OS version is 10.13 or below.

How to add custom method to Spring Data JPA

If you want to be able to do more sophisticated operations you might need access to Spring Data's internals, in which case the following works (as my interim solution to DATAJPA-422):

public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    private JpaEntityInformation<Account, ?> entityInformation;

    @PostConstruct
    public void postConstruct() {
        this.entityInformation = JpaEntityInformationSupport.getMetadata(Account.class, entityManager);
    }

    @Override
    @Transactional
    public Account saveWithReferenceToOrganisation(Account entity, long referralId) {
        entity.setOrganisation(entityManager.getReference(Organisation.class, organisationId));
        return save(entity);
    }

    private Account save(Account entity) {
        // save in same way as SimpleJpaRepository
        if (entityInformation.isNew(entity)) {
            entityManager.persist(entity);
            return entity;
        } else {
            return entityManager.merge(entity);
        }
    }

}

'setInterval' vs 'setTimeout'

setInterval()

setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

if you want to loop code for animations or clocks Then use setInterval.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

"Eliminate render-blocking CSS in above-the-fold content"

Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Good Java graph algorithm library?

http://neo4j.org/ is a graph database that contains many of graph algorithms and scales better than most in-memory libraries.

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

How to substitute shell variables in complex text files

Call the perl binary, in search and replace per line mode ( the -pi ) by running the perl code ( the -e) in the single quotes, which iterates over the keys of the special %ENV hash containing the exported variable names as keys and the exported variable values as the keys' values and for each iteration simple replace a string containing a $<<key>> with its <<value>>.

 perl -pi -e 'foreach $key(sort keys %ENV){ s/\$$key/$ENV{$key}/g}' file

Caveat: An additional logic handling is required for cases in which two or more vars start with the same string ...

How to convert xml into array in php?

The method used in the accepted answer drop attributes when encountering child elements with only a text node. For example:

$xml = '<container><element attribute="123">abcd</element></container>';
print_r(json_decode(json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)),1));

Array
(
    [element] => abcd
)

My solution (and I wish I could give credit here because I'm sure I adapted this from something):

function XMLtoArray($xml) {
    $previous_value = libxml_use_internal_errors(true);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false; 
    $dom->loadXml($xml);
    libxml_use_internal_errors($previous_value);
    if (libxml_get_errors()) {
        return [];
    }
    return DOMtoArray($dom);
}

function DOMtoArray($root) {
    $result = array();

    if ($root->hasAttributes()) {
        $attrs = $root->attributes;
        foreach ($attrs as $attr) {
            $result['@attributes'][$attr->name] = $attr->value;
        }
    }

    if ($root->hasChildNodes()) {
        $children = $root->childNodes;
        if ($children->length == 1) {
            $child = $children->item(0);
            if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE])) {
                $result['_value'] = $child->nodeValue;
                return count($result) == 1
                    ? $result['_value']
                    : $result;
            }

        }
        $groups = array();
        foreach ($children as $child) {
            if (!isset($result[$child->nodeName])) {
                $result[$child->nodeName] = DOMtoArray($child);
            } else {
                if (!isset($groups[$child->nodeName])) {
                    $result[$child->nodeName] = array($result[$child->nodeName]);
                    $groups[$child->nodeName] = 1;
                }
                $result[$child->nodeName][] = DOMtoArray($child);
            }
        }
    }
    return $result;
}

$xml = '
    <aaaa Version="1.0">
       <bbb>
         <cccc>
           <dddd id="123" />
           <eeee name="john" age="24" />
           <ffff type="employee">Supervisor</ffff>
         </cccc>
       </bbb>
    </aaaa>
';
print_r(XMLtoArray($xml));

Array
(
    [aaaa] => Array
        (
            [@attributes] => Array
                (
                    [Version] => 1.0
                )

            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [id] => 123
                                        )

                                )

                            [eeee] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [name] => john
                                            [age] => 24
                                        )

                                )

                            [ffff] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [type] => employee
                                        )

                                    [_value] => Supervisor
                                )

                        )

                )

        )

)

Can we open pdf file using UIWebView on iOS?

NSString *folderName=[NSString stringWithFormat:@"/documents/%@",[tempDictLitrature objectForKey:@"folder"]];
NSString *fileName=[tempDictLitrature objectForKey:@"name"];
[self.navigationItem setTitle:fileName];
NSString *type=[tempDictLitrature objectForKey:@"type"];

NSString *path=[[NSBundle mainBundle]pathForResource:fileName ofType:type inDirectory:folderName];

NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 730)];
[webView setBackgroundColor:[UIColor lightGrayColor]];
webView.scalesPageToFit = YES;

[[webView scrollView] setContentOffset:CGPointZero animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];

Video streaming over websockets using JavaScript

It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video> element will be the way to go, but that will lack support for a little while.

Understanding typedefs for function pointers in C

cdecl is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.

As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:

typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);

rather than:

typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);

cdecl can help you out with this stuff:

cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )

And is (in fact) exactly how I generated that crazy mess above.

Clicking at coordinates without identifying element

    WebElement button = driver.findElement(By.xpath("//button[@type='submit']"));
    int height = button.getSize().getHeight();
    int width = button.getSize().getWidth();
    Actions act = new Actions(driver);
    act.moveToElement(button).moveByOffset((width/2)+2,(height/2)+2).click();

E11000 duplicate key error index in mongodb mongoose

Check indexes of that collection in MongoDB compass and remove those indexes which are not related to it or for try remove all indexes(Not from code but in db).

Calling a PHP function from an HTML form in the same file

in case you don't want to use Ajax , and want your page to reload .

<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}    
?>

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

Why would a JavaScript variable start with a dollar sign?

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).

In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?

I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.

For example:

var $get = function(id) { return document.getElementById(id); }

That seems like a reasonable convention.

Simple search MySQL database using php

Just with the above answer I hope it was the problem.

$_POST['search'] instead of $_post['search']

And again use LIKE '%$name%' instead of LIKE '%{$name}%'

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

What is the difference between String.slice and String.substring?

substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

sample code for 'slice' in string

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]

python: order a list of numbers without built-in sort, min, max function

Here's a more readable example of an in-place Insertion sort algorithm.

a = [3, 1, 5, 2, 4]

for i in a[1:]:
    j = a.index(i)
    while j > 0 and a[j-1] > a[j]:
        a[j], a[j-1] = a[j-1], a[j]
        j = j - 1

Determine what attributes were changed in Rails after_save callback?

The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed? methods don't return true for changed attributes in the after_update hook, only in the before_update hook. I was able to get it to work using the (new?) around_update hook:

class SomeModel < ActiveRecord::Base
  around_update :send_notification_after_change

  def send_notification_after_change
    should_send_it = self.published_changed? && self.published == true

    yield

    Notification.send(...) if should_send_it
  end

end

Server Client send/receive simple text

The following code send and recieve the current date and time from and to the server

//The following code is for the server application:

namespace Server
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";

        static void Main(string[] args)
        {
            //---listen at the specified IP and port no.---
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            Console.WriteLine("Listening...");
            listener.Start();

            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);

            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);
            client.Close();
            listener.Stop();
            Console.ReadLine();
        }
    }
}

//this is the code for the client

namespace Client
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";
        static void Main(string[] args)
        {
            //---data to send to the server---
            string textToSend = DateTime.Now.ToString();

            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
            Console.ReadLine();
            client.Close();
        }
    }
}

How to install SimpleJson Package for Python

Download the source code, unzip it to and directory, and execute python setup.py install.

iOS - UIImageView - how to handle UIImage image orientation

I converted the code in Anomie's answer here (copy-pasted above by suvish valsan) into Swift:

func fixOrientation() -> UIImage {
    if self.imageOrientation == UIImageOrientation.Up {
        return self
    }

    var transform = CGAffineTransformIdentity

    switch self.imageOrientation {
    case .Down, .DownMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI));

    case .Left, .LeftMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, 0);
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));

    case .Right, .RightMirrored:
        transform = CGAffineTransformTranslate(transform, 0, self.size.height);
        transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));

    case .Up, .UpMirrored:
        break
    }

    switch self.imageOrientation {

    case .UpMirrored, .DownMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, 0)
        transform = CGAffineTransformScale(transform, -1, 1)

    case .LeftMirrored, .RightMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.height, 0)
        transform = CGAffineTransformScale(transform, -1, 1);

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx = CGBitmapContextCreate(
        nil,
        Int(self.size.width),
        Int(self.size.height),
        CGImageGetBitsPerComponent(self.CGImage),
        0,
        CGImageGetColorSpace(self.CGImage),
        UInt32(CGImageGetBitmapInfo(self.CGImage).rawValue)
    )

    CGContextConcatCTM(ctx, transform);

    switch self.imageOrientation {
    case .Left, .LeftMirrored, .Right, .RightMirrored:
        // Grr...
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height,self.size.width), self.CGImage);

    default:
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width,self.size.height), self.CGImage);
        break;
    }

    // And now we just create a new UIImage from the drawing context
    let cgimg = CGBitmapContextCreateImage(ctx)

    let img = UIImage(CGImage: cgimg!)

    return img;
}

(I replaced all occurencies of the parameter image with self, because my code is an extension on UIImage).


EDIT: Swift 3 version.

The method returns an optional, because many of the intermediate calls can fail and I don't like to use !.

func fixOrientation() -> UIImage? {

    guard let cgImage = self.cgImage else {
        return nil
    }

    if self.imageOrientation == UIImageOrientation.up {
        return self
    }

    let width  = self.size.width
    let height = self.size.height

    var transform = CGAffineTransform.identity

    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: width, y: height)
        transform = transform.rotated(by: CGFloat.pi)

    case .left, .leftMirrored:
        transform = transform.translatedBy(x: width, y: 0)
        transform = transform.rotated(by: 0.5*CGFloat.pi)

    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: height)
        transform = transform.rotated(by: -0.5*CGFloat.pi)

    case .up, .upMirrored:
        break
    }

    switch self.imageOrientation {
    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: height, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    guard let colorSpace = cgImage.colorSpace else {
        return nil
    }

    guard let context = CGContext(
        data: nil,
        width: Int(width),
        height: Int(height),
        bitsPerComponent: cgImage.bitsPerComponent,
        bytesPerRow: 0,
        space: colorSpace,
        bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue)
        ) else {
            return nil
    }

    context.concatenate(transform);

    switch self.imageOrientation {

    case .left, .leftMirrored, .right, .rightMirrored:
        // Grr...
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))

    default:
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
    }

    // And now we just create a new UIImage from the drawing context
    guard let newCGImg = context.makeImage() else {
        return nil
    }

    let img = UIImage(cgImage: newCGImg)

    return img;
}

(Note: Swift 3 version odes compile under Xcode 8.1, but haven't tested it actually works. There might be a typo somewhere, mixed up width/height, etc. Feel free to point/fix any errors).

How to create an Array, ArrayList, Stack and Queue in Java?

I am guessing you're confused with the parameterization of the types:

// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>(); 


// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();

PHP-FPM doesn't write to error log

There are multiple php config files, but THIS is the one you need to edit:

/etc/php(version)?/fpm/pool.d/www.conf

uncomment the line that says:

catch_workers_output

That will allow PHPs stderr to go to php-fpm's error log instead of /dev/null.

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

How to loop through a plain JavaScript object with the objects as members?

p is the value

for (var key in p) {
  alert(key + ' => ' + p[key]);
}

OR

Object.keys(p).forEach(key => { console.log(key, p[key]) })

What is the difference between URI, URL and URN?

URI (Uniform Resource Identifier) according to Wikipedia:

a string of characters used to identify a resource.

URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.

URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax

IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

Iterate through dictionary values?

Depending on your version:

Python 2.x:

for key, val in PIX0.iteritems():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python 3.x:

for key, val in PIX0.items():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

You should also get in the habit of using the new string formatting syntax ({} instead of % operator) from PEP 3101:

https://www.python.org/dev/peps/pep-3101/

PHP If Statement with Multiple Conditions

An elegant way is building an array on the fly and using in_array():

if (in_array($var, array("abc", "def", "ghi")))

The switch statement is also an alternative:

switch ($var) {
case "abc":
case "def":
case "hij":
    echo "yes";
    break;
default:
    echo "no";
}

Convert Float to Int in Swift

You can convert Float to Int in Swift like this:

var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"

You can also achieve this result with @paulm's comment:

var myIntValue = Int(myFloatValue)

Git Diff with Beyond Compare

For MAC after doing lot of research it worked for me..! 1. Install the beyond compare and this will be installed in below location

/Applications/Beyond\ Compare.app/Contents/MacOS/bcomp

Please follow these steps to make bc as diff/merge tool in git http://www.scootersoftware.com/support.php?zz=kb_mac

What characters are allowed in an email address?

The accepted answer refers to a Wikipedia article when discussing the valid local-part of an email address, but Wikipedia is not an authority on this.

IETF RFC 3696 is an authority on this matter, and should be consulted at section 3. Restrictions on email addresses on page 5:

Contemporary email addresses consist of a "local part" separated from a "domain part" (a fully-qualified domain name) by an at-sign ("@"). The syntax of the domain part corresponds to that in the previous section. The concerns identified in that section about filtering and lists of names apply to the domain names used in an email context as well. The domain name can also be replaced by an IP address in square brackets, but that form is strongly discouraged except for testing and troubleshooting purposes.

The local part may appear using the quoting conventions described below. The quoted forms are rarely used in practice, but are required for some legitimate purposes. Hence, they should not be rejected in filtering routines but, should instead be passed to the email system for evaluation by the destination host.

The exact rule is that any ASCII character, including control characters, may appear quoted, or in a quoted string. When quoting is needed, the backslash character is used to quote the following character. For example

  Abc\@[email protected]

is a valid form of an email address. Blank spaces may also appear, as in

  Fred\ [email protected]

The backslash character may also be used to quote itself, e.g.,

  Joe.\\[email protected]

In addition to quoting using the backslash character, conventional double-quote characters may be used to surround strings. For example

  "Abc@def"@example.com

  "Fred Bloggs"@example.com

are alternate forms of the first two examples above. These quoted forms are rarely recommended, and are uncommon in practice, but, as discussed above, must be supported by applications that are processing email addresses. In particular, the quoted forms often appear in the context of addresses associated with transitions from other systems and contexts; those transitional requirements do still arise and, since a system that accepts a user-provided email address cannot "know" whether that address is associated with a legacy system, the address forms must be accepted and passed into the email environment.

Without quotes, local-parts may consist of any combination of
alphabetic characters, digits, or any of the special characters

  ! # $ % & ' * + - / = ?  ^ _ ` . { | } ~

period (".") may also appear, but may not be used to start or end the local part, nor may two or more consecutive periods appear. Stated differently, any ASCII graphic (printing) character other than the at-sign ("@"), backslash, double quote, comma, or square brackets may appear without quoting. If any of that list of excluded characters are to appear, they must be quoted. Forms such as

  [email protected]

  customer/[email protected]

  [email protected]

  !def!xyz%[email protected]

  [email protected]

are valid and are seen fairly regularly, but any of the characters listed above are permitted.

As others have done, I submit a regex that works for both PHP and JavaScript to validate email addresses:

/^[a-z0-9!'#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!'#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-zA-Z]{2,}$/i

How can I debug a HTTP POST in Chrome?

Another option that may be useful is a dedicated HTTP debugging tool. There's a few available, I'd suggest HTTP Toolkit: an open-source project I've been working on (yeah, I might be biased) to solve this same problem for myself.

The main difference is usability & power. The Chrome dev tools are good for simple things, and I'd recommend starting there, but if you're struggling to understand the information there, and you need either more explanation or more power then proper focused tools can be useful!

For this case, it'll show you the full POST body you're looking for, with a friendly editor and highlighting (all powered by VS Code) so you can dig around. It'll give you the request & response headers of course, but with extra info like docs from MDN (the Mozilla Developer Network) for every standard header and status code you can see.

A picture is worth a thousand StackOverflow answers:

A screenshot of HTTP Toolkit showing a POST request and its body

Could not find main class HelloWorld

You are not setting a classpath that includes your compiled class! java can't find any classes if you don't tell it where to look.

java -cp [compiler outpur dir] HelloWorld

Incidentally you do not need to set CLASSPATH the way you have done.

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting the painted border false?

JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);

It works on my mac :)

How to distinguish between left and right mouse click with jQuery

event.which === 1 ensures it's a left-click (when using jQuery).

But you should also think about modifier keys: ctrlcmdshiftalt

If you're only interested in catching simple, unmodified left-clicks, you can do something like this:

var isSimpleClick = function (event) {
  return !(
    event.which !== 1 || // not a left click
    event.metaKey ||     // "open link in new tab" (mac)
    event.ctrlKey ||     // "open link in new tab" (windows/linux)
    event.shiftKey ||    // "open link in new window"
    event.altKey         // "save link as"
  );
};

$('a').on('click', function (event) {
  if (isSimpleClick(event)) {
    event.preventDefault();
    // do something...
  }
});

SyntaxError: missing ) after argument list

I faced the same issue in below scenario yesterday. However I fixed it as shown below. But it would be great if someone can explain me as to why this error was coming specifically in my case.

pasted content of index.ejs file that gave the error in the browser when I run my node file "app.js". It has a route "/blogs" that redirects to "index.ejs" file.

<%= include partials/header %>
<h1>Index Page</h1>
<% blogs.forEach(function(blog){ %>
    <div>
        <h2><%= blog.title %></h2>
        <image src="<%= blog.image %>">
        <span><%= blog.created %></span>
        <p><%= blog.body %></p>
    </div>
<% }) %>
<%= include partials/footer %>

The error that came on the browser :

SyntaxError: missing ) after argument list in /home/ubuntu/workspace/RESTful/RESTfulBlogApp/views/index.ejs while compiling ejs

How I fixed it : I removed "=" in the include statements at the top and the bottom and it worked fine.

Powershell import-module doesn't find modules

I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules

Styling JQuery UI Autocomplete

Bootstrap styling for jQuery UI Autocomplete

    .ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
}

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
}

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
}