Programs & Examples On #Type systems

Type systems impose constraints on what programs may be written, by providing a syntactic method for operating with those constraints.

Dynamic type languages versus static type languages

The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).

A good take on the issue is from Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages by Erik Meijer and Peter Drayton at Microsoft:

Advocates of static typing argue that the advantages of static typing include earlier detection of programming mistakes (e.g. preventing adding an integer to a boolean), better documentation in the form of type signatures (e.g. incorporating number and types of arguments when resolving names), more opportunities for compiler optimizations (e.g. replacing virtual calls by direct calls when the exact type of the receiver is known statically), increased runtime efficiency (e.g. not all values need to carry a dynamic type), and a better design time developer experience (e.g. knowing the type of the receiver, the IDE can present a drop-down menu of all applicable members). Static typing fanatics try to make us believe that “well-typed programs cannot go wrong”. While this certainly sounds impressive, it is a rather vacuous statement. Static type checking is a compile-time abstraction of the runtime behavior of your program, and hence it is necessarily only partially sound and incomplete. This means that programs can still go wrong because of properties that are not tracked by the type-checker, and that there are programs that while they cannot go wrong cannot be type-checked. The impulse for making static typing less partial and more complete causes type systems to become overly complicated and exotic as witnessed by concepts such as “phantom types” [11] and “wobbly types” [10]. This is like trying to run a marathon with a ball and chain tied to your leg and triumphantly shouting that you nearly made it even though you bailed out after the first mile.

Advocates of dynamically typed languages argue that static typing is too rigid, and that the softness of dynamically languages makes them ideally suited for prototyping systems with changing or unknown requirements, or that interact with other systems that change unpredictably (data and application integration). Of course, dynamically typed languages are indispensable for dealing with truly dynamic program behavior such as method interception, dynamic loading, mobile code, runtime reflection, etc. In the mother of all papers on scripting [16], John Ousterhout argues that statically typed systems programming languages make code less reusable, more verbose, not more safe, and less expressive than dynamically typed scripting languages. This argument is parroted literally by many proponents of dynamically typed scripting languages. We argue that this is a fallacy and falls into the same category as arguing that the essence of declarative programming is eliminating assignment. Or as John Hughes says [8], it is a logical impossibility to make a language more powerful by omitting features. Defending the fact that delaying all type-checking to runtime is a good thing, is playing ostrich tactics with the fact that errors should be caught as early in the development process as possible.

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

How to align linearlayout to vertical center?

You can change set orientation of linearlayout programmatically by:

LinearLayout linearLayout =new linearLayout(this);//just to give the clarity
linearLayout.setOrientation(LinearLayout.VERTICAL);

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Converting between datetime and Pandas Timestamp objects

You can use the to_pydatetime method to be more explicit:

In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)

In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)

It's also available on a DatetimeIndex:

In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')

In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
       datetime.datetime(2011, 1, 11, 0, 0),
       datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

Getting the minimum of two values in SQL

This works for up to 5 dates and handles nulls. Just couldn't get it to work as an Inline function.

CREATE FUNCTION dbo.MinDate(@Date1 datetime = Null,
                            @Date2 datetime = Null,
                            @Date3 datetime = Null,
                            @Date4 datetime = Null,
                            @Date5 datetime = Null)
RETURNS Datetime AS
BEGIN
--USAGE select dbo.MinDate('20120405',null,null,'20110305',null)
DECLARE @Output datetime;

WITH Datelist_CTE(DT)
AS (
        SELECT @Date1 AS DT WHERE @Date1 is not NULL UNION
        SELECT @Date2 AS DT WHERE @Date2 is not NULL UNION
        SELECT @Date3 AS DT WHERE @Date3 is not NULL UNION
        SELECT @Date4 AS DT WHERE @Date4 is not NULL UNION
        SELECT @Date5 AS DT WHERE @Date5 is not NULL
   )
Select @Output=Min(DT) FROM Datelist_CTE

RETURN @Output
END

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

java SSL and cert keystore

Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":

javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType

The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.

Display html text in uitextview

You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

https://github.com/AliSoftware/OHAttributedLabel

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

SQL get the last date time record

select max(dates)
from yourTable
group by dates
having count(status) > 1

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

checking memory_limit in PHP

If you are interested in CLI memory limit:

cat /etc/php/[7.0]/cli/php.ini | grep "memory_limit"

FPM / "Normal"

cat /etc/php/[7.0]/fpm/php.ini | grep "memory_limit"

How to convert a string with Unicode encoding to a string of letters

Actually, I wrote an Open Source library that contains some utilities. One of them is converting a Unicode sequence to String and vise-versa. I found it very useful. Here is the quote from the article about this library about Unicode converter:

Class StringUnicodeEncoderDecoder has methods that can convert a String (in any language) into a sequence of Unicode characters and vise-versa. For example a String "Hello World" will be converted into

"\u0048\u0065\u006c\u006c\u006f\u0020 \u0057\u006f\u0072\u006c\u0064"

and may be restored back.

Here is the link to entire article that explains what Utilities the library has and how to get the library to use it. It is available as Maven artifact or as source from Github. It is very easy to use. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison

How do I share a global variable between c files?

Use the extern keyword to declare the variable in the other .c file. E.g.:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

Difference between sh and bash

bash and sh are two different shells. Basically bash is sh, with more features and better syntax. Most commands work the same, but they are different.Bash (bash) is one of many available (yet the most commonly used) Unix shells. Bash stands for "Bourne Again SHell",and is a replacement/improvement of the original Bourne shell (sh).

Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. In practice, however, "shell script" and "bash script" are often used interchangeably, unless the shell in question is not Bash.

Having said that, you should realize /bin/sh on most systems will be a symbolic link and will not invoke sh. In Ubuntu /bin/sh used to link to bash, typical behavior on Linux distributions, but now has changed to linking to another shell called dash. I would use bash, as that is pretty much the standard (or at least most common, from my experience). In fact, problems arise when a bash script will use #!/bin/sh because the script-maker assumes the link is to bash when it doesn't have to be.

How to check if a particular service is running on Ubuntu

You can use the below command to check the list of all services.

ps aux 

To check your own service:

ps aux | grep postgres

C: printf a float value

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

Creating a Zoom Effect on an image on hover using CSS?

 -webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;  

just want to make a note on the above transitions only need

 -webkit-transition: all 1s ease; /* Safari and Chrome */
transition: all 1s ease;

and -ms- certainly doenst work for IE 9 i dont know where you got that idea from.

how to calculate binary search complexity

It doesn't half search time, that wouldn't make it log(n). It decreases it logarithmicly. Think about this for a moment. If you had 128 entries in a table and had to search linearly for your value, it would probably take around 64 entries on average to find your value. That's n/2 or linear time. With a binary search, you eliminate 1/2 the possible entries each iteration, such that at most it would only take 7 compares to find your value (log base 2 of 128 is 7 or 2 to the 7 power is 128.) This is the power of binary search.

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

How to get back to the latest commit after checking out a previous commit?

You can use one of the following git command for this:

git checkout master
git checkout branchname

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Android findViewById() in Custom View

You can try something like this:

Inside customview constructor:

mContext = context;

Next inside customview you can call:

((MainActivity) mContext).updateText( text );

Inside MainAcivity define:

public void updateText(final String text) {

     TextView txtView = (TextView) findViewById(R.id.text);
     txtView.setText(text);
}

It works for me.

What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.

The limits for int (32 bit) are:

int: –2147483648 to 2147483647 
uint: 0 to 4294967295 

And for long (64 bit):

long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615

Java JRE 64-bit download for Windows?

The trick is to visit the original page using the 64-bit version of Internet Explorer. The site will then offer you the appropriate download options.

How to detect when keyboard is shown and hidden

Swift 5

There answers above are correct. Although I would prefer to create a helper to wrap up the notification's observers.

The benefit:

  1. You don't have to repeat each time you handle the keyboard behaviors.
  2. You can extend other notification by implement other enum value
  3. It's useful when you have to deal with keyboard in several controllers.

Sample code:

extension KeyboardHelper {
    enum Animation {
        case keyboardWillShow
        case keyboardWillHide
    }

    typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void
}

final class KeyboardHelper {
    private let handleBlock: HandleBlock

    init(handleBlock: @escaping HandleBlock) {
        self.handleBlock = handleBlock
        setupNotification()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    private func setupNotification() {
        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillShow, notification: notification)
            }

        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillHide, notification: notification)
            }
    }

    private func handle(animation: Animation, notification: Notification) {
        guard let userInfo = notification.userInfo,
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        else { return }

        handleBlock(animation, keyboardFrame, duration)
    }
}

How to use:

private var keyboardHelper: KeyboardHelper?
...

override func viewDidLoad() {
   ...
   keyboardHelper = KeyboardHelper { [unowned self] animation, keyboardFrame, duration in
        switch animation {
        case .keyboardWillShow:
            print("keyboard will show")
        case .keyboardWillHide:
            print("keyboard will hide")
        }
    }

}

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

How to adjust text font size to fit textview

I had this pain in my projects for soooo long until I found this library:

compile 'me.grantland:autofittextview:0.2.+'

You just need to add the xml by your needs and it's done. For example:

<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:maxLines="2"
android:textSize="40sp"
autofit:minTextSize="16sp"
/>

Difference between "char" and "String" in Java

char have any but one character (letters, numbers,...)

char example = 'x';

string can have zero characters or as many as you want

String example = "Here you can have anything";

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

The free Tamper Data Firefox extension is pretty good. Allows you to view, filter and modify all requests.

Determine SQL Server Database Size

I always liked going after it directly:

SELECT 
    DB_NAME( dbid ) AS DatabaseName, 
    CAST( ( SUM( size ) * 8 ) / ( 1024.0 * 1024.0 ) AS decimal( 10, 2 ) ) AS DbSizeGb 
FROM 
    sys.sysaltfiles 
GROUP BY 
    DB_NAME( dbid )

Iterate all files in a directory using a 'for' loop

In my case I had to delete all the files and folders underneath a temp folder. So this is how I ended up doing it. I had to run two loops one for file and one for folders. If files or folders have spaces in their names then you have to use " "

cd %USERPROFILE%\AppData\Local\Temp\
rem files only
for /r %%a in (*) do (
echo deleting file "%%a" ...
if exist "%%a" del /s /q "%%a"
)
rem folders only
for /D %%a in (*) do (
echo deleting folder "%%a" ...
if exist "%%a" rmdir /s /q "%%a"
)

Short rot13 function - Python

You can also use this also

def n3bu1A(n):
    o=""
    key = {
       'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
    for x in n:
        v = x in key.keys()
        if v == True:
            o += (key[x])   
        else:
            o += x
    return o

Yes = n3bu1A("N zhpu fvzcyre jnl gb fnl Guvf vf zl Zragbe!!")
print(Yes)

How to reverse a 'rails generate'

Suppose I have created a controller named "sample" like:

rails generate controller sample

If I have to destroy this controller, all I have to do is swap generate with destroy, as in

rails destroy controller sample.

If you want to reverse the generation, all you have to do is swap generate with destroy.

SQL: IF clause within WHERE clause

USE AdventureWorks2012;
GO
IF 
(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
PRINT 'There are more than 5 Touring-3000 bicycles.'
ELSE PRINT 'There are 5 or less Touring-3000 bicycles.' ;
GO

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

How to convert a 3D point into 2D perspective projection?

Thanks to @Mads Elvenheim for a proper example code. I have fixed the minor syntax errors in the code (just a few const problems and obvious missing operators). Also, near and far have vastly different meanings in vs.

For your pleasure, here is the compileable (MSVC2013) version. Have fun. Mind that I have made NEAR_Z and FAR_Z constant. You probably dont want it like that.

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

#define M_PI 3.14159

#define NEAR_Z 0.5
#define FAR_Z 2.5

struct Vector
{
    float x;
    float y;
    float z;
    float w;

    Vector() : x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}
    Vector( float a, float b, float c ) : x( a ), y( b ), z( c ), w( 1 ) {}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt( x*x + y*y + z*z );
    }
    Vector& operator*=(float fac) noexcept
    {
        x *= fac;
        y *= fac;
        z *= fac;
        return *this;
    }
    Vector  operator*(float fac) const noexcept
    {
        return Vector(*this)*=fac;
    }
    Vector& operator/=(float div) noexcept
    {
        return operator*=(1/div);   // avoid divisions: they are much
                                    // more costly than multiplications
    }

    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if (mag < epsilon) {
            std::out_of_range e( "" );
            throw e;
        }
        return Vector(*this)/=mag;
    }
};

inline float Dot( const Vector& v1, const Vector& v2 )
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
public:
    Matrix() : data( 16 )
    {
        Identity();
    }
    void Identity()
    {
        std::fill( data.begin(), data.end(), float( 0 ) );
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[]( size_t index )
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    const float& operator[]( size_t index ) const
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    Matrix operator*( const Matrix& m ) const
    {
        Matrix dst;
        int col;
        for (int y = 0; y<4; ++y) {
            col = y * 4;
            for (int x = 0; x<4; ++x) {
                for (int i = 0; i<4; ++i) {
                    dst[x + col] += m[i + col] * data[x + i * 4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=( const Matrix& m )
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix( float fov, float aspectRatio )
    {
        Identity();
        float f = 1.0f / std::tan( fov * 0.5f );
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (FAR_Z + NEAR_Z) / (FAR_Z- NEAR_Z);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*NEAR_Z*FAR_Z) / (NEAR_Z - FAR_Z);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};


inline Vector operator*( const Vector& v, Matrix& m )
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip( int width, int height, const VecArr& vertex )
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix( 60.0f * (M_PI / 180.0f), aspect);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping
    by checking if the x, y and z components are inside the range of [-w, w].
    One checks each vector component seperately against each plane. Per-vertex
    data like colours, normals and texture coordinates need to be linearly
    interpolated for clipped edges to reflect the change. If the edge (v0,v1)
    is tested against the positive x plane, and v1 is outside, the interpolant
    becomes: (v1.x - w) / (v1.x - v0.x)
    I skip this stage all together to be brief.
    */
    for (VecArr::const_iterator i = vertex.begin(); i != vertex.end(); ++i) {
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back( v );
    }

    /* TODO: Clipping here */

    for (VecArr::iterator i = dst.begin(); i != dst.end(); ++i) {
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}
#pragma once

Simple way to read single record from MySQL

Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:

$sql = "SELECT id FROM games LIMIT 1";  // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];

This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.

Excel VBA: Copying multiple sheets into new workbook

Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

Sub NewWBandPasteSpecialALLSheets()
   MyBook = ActiveWorkbook.Name ' Get name of this book
   Workbooks.Add ' Open a new workbook
   NewBook = ActiveWorkbook.Name ' Save name of new book

   Workbooks(MyBook).Activate ' Back to original book

   Set WB = ActiveWorkbook

   Dim SH As Worksheet

   For Each SH In WB.Worksheets

       SH.Range("WholePrintArea").Copy

       Workbooks(NewBook).Activate

       With SH.Range("A1")
        .PasteSpecial (xlPasteColumnWidths)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlValues)

       End With

     Next

End Sub

But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

Sub NewWBandPasteSpecialALLSheets()
   Dim wb As Workbook
   Dim wbNew As Workbook
   Dim sh As Worksheet
   Dim shNew As Worksheet

   Set wb = ThisWorkbook
   Workbooks.Add ' Open a new workbook
   Set wbNew = ActiveWorkbook

   On Error Resume Next

   For Each sh In wb.Worksheets
      sh.Range("WholePrintArea").Copy

      'add new sheet into new workbook with the same name
      With wbNew.Worksheets

          Set shNew = Nothing
          Set shNew = .Item(sh.Name)

          If shNew Is Nothing Then
              .Add After:=.Item(.Count)
              .Item(.Count).Name = sh.Name
              Set shNew = .Item(.Count)
          End If
      End With

      With shNew.Range("A1")
          .PasteSpecial (xlPasteColumnWidths)
          .PasteSpecial (xlFormats)
          .PasteSpecial (xlValues)
      End With
   Next
End Sub

Use of min and max functions in C++

fmin and fmax are specifically for use with floating point numbers (hence the "f"). If you use it for ints, you may suffer performance or precision losses due to conversion, function call overhead, etc. depending on your compiler/platform.

std::min and std::max are template functions (defined in header <algorithm>) which work on any type with a less-than (<) operator, so they can operate on any data type that allows such a comparison. You can also provide your own comparison function if you don't want it to work off <.

This is safer since you have to explicitly convert arguments to match when they have different types. The compiler won't let you accidentally convert a 64-bit int into a 64-bit float, for example. This reason alone should make the templates your default choice. (Credit to Matthieu M & bk1e)

Even when used with floats the template may win in performance. A compiler always has the option of inlining calls to template functions since the source code is part of the compilation unit. Sometimes it's impossible to inline a call to a library function, on the other hand (shared libraries, absence of link-time optimization, etc.).

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

Why is vertical-align:text-top; not working in CSS

You could apply position: relative; to the div and then position: absolute; top: 0; to a paragraph or span inside of it containing the text.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

Max parallel http connections in a browser?

  1. Yes, wildcard domain will work for you.
  2. Not aware of any limits on connections. Limits if any will be browser specific.

Creating a class object in c++

In the first case you are creating the object on the heap using new. In the second case you are creating the object on the stack, so it will be disposed of when going out of scope. In C++ you'll need to delete objects on the heapexplicitly using delete when you don't Need them anymore.

To call a static method from a class, do

Singleton* singleton = Singleton::get_sample();

in your main-function or wherever.

MVC 4 client side validation not working

Use:

@Html.EditorFor

Instead of:

@Html.TextBoxFor

Python convert set to string and vice versa

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

How do I increase modal width in Angular UI Bootstrap?

I use a css class like so to target the modal-dialog class:

.app-modal-window .modal-dialog {
  width: 500px;
}

Then in the controller calling the modal window, set the windowClass:

    $scope.modalButtonClick = function () {
        var modalInstance = $modal.open({
            templateUrl: 'App/Views/modalView.html',
            controller: 'modalController',
            windowClass: 'app-modal-window'
        });
        modalInstance.result.then(
            //close
            function (result) {
                var a = result;
            },
            //dismiss
            function (result) {
                var a = result;
            });
    };

How to Get a Sublist in C#

You want List::GetRange(firstIndex, count). See http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

// I have a List called list
List sublist = list.GetRange(5, 5); // (gets elements 5,6,7,8,9)
List anotherSublist = list.GetRange(0, 4); // gets elements 0,1,2,3)

Is that what you're after?

If you're looking to delete the sublist items from the original list, you can then do:

// list is our original list
// sublist is our (newly created) sublist built from GetRange()
foreach (Type t in sublist)
{
    list.Remove(t);
}

How do I escape double quotes in attributes in an XML String in T-SQL?

In Jelly.core to test a literal string one would use:

&lt;core:when test="${ name == 'ABC' }"&gt; 

But if I have to check for string "Toy's R Us":

&lt;core:when test="${ name == &amp;quot;Toy&apos;s R Us&amp;quot; }"&gt;

It would be like this, if the double quotes were allowed inside:

&lt;core:when test="${ name == "Toy's R Us" }"&gt; 

Difference between PACKETS and FRAMES

Packet

A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).

Frame

1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)

2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.

3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.

4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.

5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.

Convert XmlDocument to String

There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    xmlDoc.WriteTo(xmlTextWriter);
    xmlTextWriter.Flush();
    return stringWriter.GetStringBuilder().ToString();
}

Editor does not contain a main type in Eclipse

Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

Split string with PowerShell and do something with each token

To complement Justus Thane's helpful answer:

  • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

    • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
      • Leading and trailing whitespace is ignored.
      • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
  • In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object cmdlet became available: the .ForEach() array (collection) method, as described in this blog post (alongside the .Where() method, a more powerful, expression-based alternative to Where-Object).

Here's a solution based on these features:

PS> (-split '   One      for the money   ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]

Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One and for were treated as a single separator.

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

C# DateTime to "YYYYMMDDHHMMSS" format

DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

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

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

Determining complexity for recursive functions (Big O notation)

One of the best ways I find for approximating the complexity of the recursive algorithm is drawing the recursion tree. Once you have the recursive tree:

Complexity = length of tree from root node to leaf node * number of leaf nodes
  1. The first function will have length of n and number of leaf node 1 so complexity will be n*1 = n
  2. The second function will have the length of n/5 and number of leaf nodes again 1 so complexity will be n/5 * 1 = n/5. It should be approximated to n

  3. For the third function, since n is being divided by 5 on every recursive call, length of recursive tree will be log(n)(base 5), and number of leaf nodes again 1 so complexity will be log(n)(base 5) * 1 = log(n)(base 5)

  4. For the fourth function since every node will have two child nodes, the number of leaf nodes will be equal to (2^n) and length of the recursive tree will be n so complexity will be (2^n) * n. But since n is insignificant in front of (2^n), it can be ignored and complexity can be only said to be (2^n).

  5. For the fifth function, there are two elements introducing the complexity. Complexity introduced by recursive nature of function and complexity introduced by for loop in each function. Doing the above calculation, the complexity introduced by recursive nature of function will be ~ n and complexity due to for loop n. Total complexity will be n*n.

Note: This is a quick and dirty way of calculating complexity(nothing official!). Would love to hear feedback on this. Thanks.

Count number of days between two dates

(end_date - start_date)/1000/60/60/24

any one have best practice please comment below

Does a `+` in a URL scheme/host/path represent a space?

Try below:

<script type="text/javascript">

function resetPassword() {
   url: "submitForgotPassword.html?email="+fixEscape(Stringwith+char);
}
function fixEscape(str)
{
    return escape(str).replace( "+", "%2B" );
}
</script>

Set background image on grid in WPF using C#

I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.

  ImageBrush myBrush = new ImageBrush();
  Image image = new Image();
  image.Source = new BitmapImage(
      new Uri(
         "pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
  myBrush.ImageSource = image.Source;
  Grid grid = new Grid();
  grid.Background = myBrush;          

Chart creating dynamically. in .net, c#

Yep.

// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart).  Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;


namespace Dino.Tools.WebMonitor
{
    public class FakeChartForm1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;

        public FakeChartForm1 ()
        {
            InitializeComponent();
        }

        private double f(int i)
        {
            var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
            return f1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Series.Clear();
            var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name = "Series1",
                Color = System.Drawing.Color.Green,
                IsVisibleInLegend = false,
                IsXValueIndexed = true,
                ChartType = SeriesChartType.Line
            };

            this.chart1.Series.Add(series1);

            for (int i=0; i < 100; i++)
            {
                series1.Points.AddXY(i, f(i));
            }
            chart1.Invalidate();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            //
            // chart1
            //
            chartArea1.Name = "ChartArea1";
            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(0, 50);
            this.chart1.Name = "chart1";
            // this.chart1.Size = new System.Drawing.Size(284, 212);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.chart1);
            this.Name = "Form1";
            this.Text = "FakeChart";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FakeChartForm1());
        }
    }
}

UI:

enter image description here

Bootstrap 3 with remote Modal

As much as I dislike modifying Bootstrap code (makes upgrading more difficult), you can simply add ".find('.modal-body') to the load statement in modal.js as follows:

// original code
// if (this.options.remote) this.$element.load(this.options.remote)

// modified code
if (this.options.remote) this.$element.find('.modal-body').load(this.options.remote)

What is "not assignable to parameter of type never" error in typescript?

All you have to do is define your result as a string array, like the following:

const result : string[] = [];

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

How to get a list of column names

Yes, you can achieve this by using the following commands:

sqlite> .headers on
sqlite> .mode column

The result of a select on your table will then look like:

id          foo         bar         age         street      address
----------  ----------  ----------  ----------  ----------  ----------
1           val1        val2        val3        val4        val5
2           val6        val7        val8        val9        val10

Android OnClickListener - identify a button

You will learn the way to do it, in an easy way, is:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

Or, if you are working with just one clicklistener, you can do:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}

Though, I don't recommend doing it that way since you will have to add an if for each button you use. That's hard to maintain.

How can I use xargs to copy files that have spaces and quotes in their names?

Just don't use xargs. It is a neat program but it doesn't go well with find when faced with non trivial cases.

Here is a portable (POSIX) solution, i.e. one that doesn't require find, xargs or cp GNU specific extensions:

find . -name "*FooBar*" -exec sh -c 'cp -- "$@" ~/foo/bar' sh {} +

Note the ending + instead of the more usual ;.

This solution:

  • correctly handles files and directories with embedded spaces, newlines or whatever exotic characters.

  • works on any Unix and Linux system, even those not providing the GNU toolkit.

  • doesn't use xargs which is a nice and useful program, but requires too much tweaking and non standard features to properly handle find output.

  • is also more efficient (read faster) than the accepted and most if not all of the other answers.

Note also that despite what is stated in some other replies or comments quoting {} is useless (unless you are using the exotic fishshell).

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

W3WP.EXE using 100% CPU - where to start?

This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.

So, it would be simple enough to ensure that they are building and deploying in release mode.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Does C# have extension properties?

No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.

At this point the best you can do is GetXXX style extension methods.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Difference between res.send and res.json in Express.js

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the send method doesn't have:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

Best Practice for Forcing Garbage Collection in C#

Large objects are allocated on LOH (large object heap), not on gen 0. If you're saying that they don't get garbage-collected with gen 0, you're right. I believe they are collected only when the full GC cycle (generations 0, 1 and 2) happens.

That being said, I believe on the other side GC will adjust and collect memory more aggressively when you work with large objects and the memory pressure is going up.

It is hard to say whether to collect or not and in which circumstances. I used to do GC.Collect() after disposing of dialog windows/forms with numerous controls etc. (because by the time the form and its controls end up in gen 2 due to creating many instances of business objects/loading much data - no large objects obviously), but actually didn't notice any positive or negative effects in the long term by doing so.

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

Unzip files programmatically in .net

We have used SharpZipLib successfully on many projects. I know it's a third party tool, but source code is included and could provide some insight if you chose to reinvent the wheel here.

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

How to return a specific element of an array?

(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:

array3[i]=e1

Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How to break out from a ruby block?

If you want your block to return a useful value (e.g. when using #map, #inject, etc.), next and break also accept an argument.

Consider the following:

def contrived_example(numbers)
  numbers.inject(0) do |count, x|
    if x % 3 == 0
      count + 2
    elsif x.odd?
      count + 1
    else 
      count
    end
  end
end

The equivalent using next:

def contrived_example(numbers)
  numbers.inject(0) do |count, x|
    next count if x.even?
    next (count + 2) if x % 3 == 0
    count + 1
  end
end

Of course, you could always extract the logic needed into a method and call that from inside your block:

def contrived_example(numbers)
  numbers.inject(0) { |count, x| count + extracted_logic(x) }
end

def extracted_logic(x)
  return 0 if x.even?
  return 2 if x % 3 == 0
  1
end

How to Get Element By Class in JavaScript?

document.querySelectorAll(".your_class_name_here");

That will work in "modern" browsers that implement that method (IE8+).

function ReplaceContentInContainer(selector, content) {
  var nodeList = document.querySelectorAll(selector);
  for (var i = 0, length = nodeList.length; i < length; i++) {
     nodeList[i].innerHTML = content;
  }
}

ReplaceContentInContainer(".theclass", "HELLO WORLD");

If you want to provide support for older browsers, you could load a stand-alone selector engine like Sizzle (4KB mini+gzip) or Peppy (10K mini) and fall back to it if the native querySelector method is not found.

Is it overkill to load a selector engine just so you can get elements with a certain class? Probably. However, the scripts aren't all that big and you will may find the selector engine useful in many other places in your script.

How do we control web page caching, across all browsers?

in my case i fix the problem in chrome with this

<form id="form1" runat="server" autocomplete="off">

where i need to clear the content of a previus form data when the users click button back for security reasons

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

PHPDoc type hinting for array of objects?

Use:

/* @var $objs Test[] */
foreach ($objs as $obj) {
    // Typehinting will occur after typing $obj->
}

when typehinting inline variables, and

class A {
    /** @var Test[] */
    private $items;
}

for class properties.

Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:

The best you can do is say,

foreach ($Objs as $Obj)
{
    /* @var $Obj Test */
    // You should be able to get hinting after the preceding line if you type $Obj->
}

I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.

How can I detect when an Android application is running in the emulator?

Google uses this code in the device-info plugin from Flutter to determine if the device is an emulator:

private boolean isEmulator() {
    return (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
        || Build.FINGERPRINT.startsWith("generic")
        || Build.FINGERPRINT.startsWith("unknown")
        || Build.HARDWARE.contains("goldfish")
        || Build.HARDWARE.contains("ranchu")
        || Build.MODEL.contains("google_sdk")
        || Build.MODEL.contains("Emulator")
        || Build.MODEL.contains("Android SDK built for x86")
        || Build.MANUFACTURER.contains("Genymotion")
        || Build.PRODUCT.contains("sdk_google")
        || Build.PRODUCT.contains("google_sdk")
        || Build.PRODUCT.contains("sdk")
        || Build.PRODUCT.contains("sdk_x86")
        || Build.PRODUCT.contains("vbox86p")
        || Build.PRODUCT.contains("emulator")
        || Build.PRODUCT.contains("simulator");
}

Pandas: Creating DataFrame from Series

Here is how to create a DataFrame where each series is a row.

For a single Series (resulting in a single-row DataFrame):

series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])

For multiple series with identical indices:

cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)

For multiple series with possibly different indices:

list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()

To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose(). However, the latter approach is inefficient if the columns have different data types.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Here is a link to VeriSign's SSL Certificate Installation Checker: https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR1130

Enter your URL, click "Test this Web Server" and it will tell you if there are issues with your intermediate certificate authority.

mongodb how to get max value from collections

you can use group and max:

db.getCollection('kids').aggregate([
    {
        $group: {
            _id: null,
            maxQuantity: {$max: "$age"}
        }
    }
])

Direct casting vs 'as' operator?

Since nobody mentioned it, the closest to instanceOf to Java by keyword is this:

obj.GetType().IsInstanceOfType(otherObj)

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

Why do some functions have underscores "__" before and after the function name?

The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods.

While you can call these methods directly ([10, 20].__len__() for example), the presence of the underscores is a hint that these methods are intended to be invoked indirectly (len([10, 20]) for example). Most python operators have an associated "magic" method (for example, a[x] is the usual way of invoking a.__getitem__(x)).

How to convert an image to base64 encoding?

Very simple and to be commonly used:

function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:'.$type.';base64,'.base64_encode(file_get_contents($imagePath));
}

//Use the above function like below:
echo '<img src="'.getDataURI('./images/my-file.svg').'" alt="">';
echo '<img src="'.getDataURI('./images/my-file.png').'" alt="">';

Note: The Mime-Type of the file will be added automatically (taking help from this PHP documentation).

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

Generating random whole numbers in JavaScript in a specific range?

I know this question is already answered but my answer could help someone.

I found this simple method on W3Schools:

Math.floor((Math.random() * max) + min);

Hope this would help someone.

Angular : Manual redirect to route

Angular Redirection manually: Import @angular/router, Inject in constructor() then call this.router.navigate().

import {Router} from '@angular/router';
... 
...

constructor(private router: Router) {
  ...
}

onSubmit() {
  ...
  this.router.navigate(['/profile']); 
}

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Java: Check if enum contains a given string?

I created the next class for this validation

public class EnumUtils {

    public static boolean isPresent(Enum enumArray[], String name) {
        for (Enum element: enumArray ) {
            if(element.toString().equals(name))
                return true;
        }
        return false;
    }

}

example of usage :

public ArrivalEnum findArrivalEnum(String name) {

    if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
        throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");

    return ArrivalEnum.valueOf(name);
}

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

Initializing a dictionary in python with a key value and no corresponding values

q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

What is the App_Data folder used for in Visual Studio?

App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

If you're using the EntityDataSource in your project, the solution is in Fix: 'Unable to load one or more of the requested types' Errors. You should set the ContextTypeName="ProjectNameNameSpace.EntityContainerName" '

This solved my problems...

When should we use intern method of String on String literals

As you said, that string intern() method will first find from the String pool, if it finds, then it will return the object that points to that, or will add a new String into the pool.

    String s1 = "Hello";
    String s2 = "Hello";
    String s3 = "Hello".intern();
    String s4 = new String("Hello");

    System.out.println(s1 == s2);//true
    System.out.println(s1 == s3);//true
    System.out.println(s1 == s4.intern());//true

The s1 and s2 are two objects pointing to the String pool "Hello", and using "Hello".intern() will find that s1 and s2. So "s1 == s3" returns true, as well as to the s3.intern().

How do you scroll up/down on the console of a Linux VM

Fn + Up/Down can scroll Terminal in Mac OS X 10.11

jQuery UI Slider (setting programmatically)

I wanted to update slider as well as the inputbox. For me following is working

a.slider('value',1520);
$("#labelAID").val(1520);

where a is object as following.

 var a= $( "<div id='slider' style='width:200px;margin-left:20px;'></div>" ).insertAfter( "#labelAID" ).slider({
            min: 0,
            max: 2000,
            range: "min",
            value: 111,
            slide: function( event, ui ) {

                $("#labelAID").val(ui.value    );
            }
        });

        $( "#labelAID" ).keyup(function() {
            a.slider( "value",$( "#labelAID" ).val()  );
        });

push multiple elements to array

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

How to set the title text color of UIButton?

This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

button.setTitleColor(.red, for: .normal)

If you want some custom colours, then create an extension for a UIColor as below first.

import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

Then use it for your button as below.

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

JAXB: How to ignore namespace during unmarshalling XML document?

Another way to add a default namespace to an XML Document before feeding it to JAXB is to use JDom:

  1. Parse XML to a Document
  2. Iterate through and set namespace on all Elements
  3. Unmarshall using a JDOMSource

Like this:

public class XMLObjectFactory {
    private static Namespace DEFAULT_NS = Namespace.getNamespace("http://tempuri.org/");

    public static Object createObject(InputStream in) {
        try {
            SAXBuilder sb = new SAXBuilder(false);
            Document doc = sb.build(in);
            setNamespace(doc.getRootElement(), DEFAULT_NS, true);
            Source src = new JDOMSource(doc);
            JAXBContext context = JAXBContext.newInstance("org.tempuri");
            Unmarshaller unmarshaller = context.createUnmarshaller();
            JAXBElement root = unmarshaller.unmarshal(src);
            return root.getValue();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create Object", e);
        }
    }

    private static void setNamespace(Element elem, Namespace ns, boolean recurse) {
        elem.setNamespace(ns);
        if (recurse) {
            for (Object o : elem.getChildren()) {
                setNamespace((Element) o, ns, recurse);
            }
        }
    }

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

Do you use source control for your database items?

The databases themselves? No

The scripts that create them, including static data inserts, stored procedures and the like; of course. They're text files, they are included in the project and are checked in and out like everything else.

Of course in an ideal world your database management tool would do this; but you just have to be disciplined about it.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

Static variables in JavaScript

So what I see with the other answers is that they don't address the fundamental architectural requirement of a static attribute in object oriented programming.

Object oriented programming actually has two different styles one is 'class based' (C++, C#, Java etc), the other is 'prototypal' (Javascript). In class based languages a 'static attribute' is supposed to be associated with the class and not the instantiated objects. This concept actually works much more intuitively in a prototypal languages like Javascript because you just assign the attribute as a value of the parent prototype like so.

function MyObject() {};
MyObject.prototype.staticAttribute = "some value";

And access it from every one of the objects that is instantiated from this constructor like so...

var childObject1 = new MyObject(); // Instantiate a child object
var childObject2 = new MyObject(); // Instantiate another child object
console.log(childObject.staticAttribute); // Access the static Attribute from child 1
console.log(childObject.staticAttribute); // Access the static Attribute from child 2

Now if you go ahead and change the MyObject.prototype.staticAttribute the change will cascade down to the child objects that immediately inherit it.

However there are a few 'gotchas' that could significantly undermine the 'static' nature of this attribute, or just leave security vulnerability...

First make sure to hide the constructor from the Global namespace by enclosing it inside another function like the jQuery ready method

 $(document).ready(function () {
    function MyObject() {
        // some constructor instructions
    };
    MyObject.prototype.staticAttribute = "some value";
    var childObject = new MyObject(); // instantiate child object
    console.log(childObject.staticAttribute); // test attribute
});

Second and lastly, even if you do this, the attribute is still editable from any of the other parts of your own script, so it could be the case that a bug in your code writes over the attribute on one of the child objects and detaches it from the parent prototype, so if you change the parent attribute it will no longer cascade and change the static attribute for the child object. See this jsfiddle. In different scenarios we could either Object.freeze(obj) to stop any changes to the child object, or we could set up a setter and getter method in the constructor and access a closure, both of these have associated complexities.

It seems to me that there is not a perfect analogue between the class-based idea of a 'static attribute' and this Javascript implementation. So I think it might be better in the long run to use a different code pattern that is more Javascript friendly. Such as a central datastore or cache or even a dedicated helper object to hold all the necessary static variables.

Is it possible to forward-declare a function in Python?

What you can do is to wrap the invocation into a function of its own.

So that

foo()

def foo():
    print "Hi!"

will break, but

def bar():
    foo()

def foo():
    print "Hi!"

bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

Add SUM of values of two LISTS into new LIST

j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]

RE error: illegal byte sequence on Mac OS X

My workaround had been using gnu sed. Worked fine for my purposes.

Why shouldn't I use "Hungarian Notation"?

Im my experience, it is bad because:

1 - then you break all the code if you need to change the type of a variable (i.e. if you need to extend a 32 bits integer to a 64 bits integer);

2 - this is useless information as the type is either already in the declaration or you use a dynamic language where the actual type should not be so important in the first place.

Moreover, with a language accepting generic programming (i.e. functions where the type of some variables is not determine when you write the function) or with dynamic typing system (i.e. when the type is not even determine at compile time), how would you name your variables? And most modern languages support one or the other, even if in a restricted form.

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

How to open a new tab using Selenium WebDriver

Almost all answers here are out of date.

(Ruby examples)

WebDriver now has support for opening tabs:

browser = Selenium::WebDriver.for :chrome
new_tab = browser.manage.new_window

Will open a new tab. Opening a window has actually become the non-standard case:

browser.manage.new_window(:window)

The tab or window will not automatically be focussed. To switch to it:

browser.switch_to.window new_tab

Hibernate Error executing DDL via JDBC Statement

I got this same error when i was trying to make a table with name "admin". Then I used @Table annotation and gave table a different name like @Table(name = "admins"). I think some words are reserved (like :- keywords in java) and you can not use them.

@Entity
@Table(name = "admins")
public class Admin extends TrackedEntity {

}

How do I drop a foreign key constraint only if it exists in sql server?

Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.

IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

How to set cursor position in EditText?

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());

How do I redirect to another webpage?

It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

Note that the current page in the example is handled differently in the code and with CSS.

If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.

$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

Kill Attached Screen in Linux

You could create a function to kill all existing sessions. take a look at Kill all detached screen sessions

to list all active sessions use screen -r

when listed, select with your mouse the session you are interested in and paste it. like this

screen -r

How to import Google Web Font in CSS file?

Add the Below code in your CSS File to import Google Web Fonts.

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

Replace the Open+Sans parameter value with your Font name.

Your CSS file should look like:

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

body{
   font-family: 'Open Sans',serif;
}

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

How to play an android notification sound

If you want a default notification sound to be played, then you can use setDefaults(int) method of NotificationCompat.Builder class:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(someText)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true);

I believe that's the easiest way to accomplish your task.

How to get duration, as int milli's and float seconds from <chrono>?

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

Remove object from a list of objects in python

del array[0]

where 0 is the index of the object in the list (there is no array in python)

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I have the same problem with angular 6, that's what worked for me :

@NgModule({
...
entryComponents: [ConfirmComponent],
providers:[ConfirmService]

})

If you have a service like ConfirmService, have to be declare in providers of current module instead of root

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

How to convert a String to Bytearray

UTF-16 Byte Array

JavaScript encodes strings as UTF-16, just like C#'s UnicodeEncoding, so the byte arrays should match exactly using charCodeAt(), and splitting each returned byte pair into 2 separate bytes, as in:

function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
  }
  return bytes;
}

For example:

strToUtf16Bytes(''); 
// [ 60, 216, 53, 223 ]

However, If you want to get a UTF-8 byte array, you must transcode the bytes.

UTF-8 Byte Array

The solution feels somewhat non-trivial, but I used the code below in a high-traffic production environment with great success (original source).

Also, for the interested reader, I published my unicode helpers that help me work with string lengths reported by other languages such as PHP.

/**
 * Convert a string to a unicode byte array
 * @param {string} str
 * @return {Array} of bytes
 */
export function strToUtf8Bytes(str) {
  const utf8 = [];
  for (let ii = 0; ii < str.length; ii++) {
    let charCode = str.charCodeAt(ii);
    if (charCode < 0x80) utf8.push(charCode);
    else if (charCode < 0x800) {
      utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
    } else if (charCode < 0xd800 || charCode >= 0xe000) {
      utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    } else {
      ii++;
      // Surrogate pair:
      // UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
      // splitting the 20 bits of 0x0-0xFFFFF into two halves
      charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
      utf8.push(
        0xf0 | (charCode >> 18),
        0x80 | ((charCode >> 12) & 0x3f),
        0x80 | ((charCode >> 6) & 0x3f),
        0x80 | (charCode & 0x3f),
      );
    }
  }
  return utf8;
}

How to use a keypress event in AngularJS?

What about this?:

<form ng-submit="chat.sendMessage()">
    <input type="text" />
    <button type="submit">
</form>

Now when you push enter key after write something in your input, the form know how to handle it.

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Leap year calculation

You really should try to google first.

Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.

More about the math around it can be found in the article Calendar Algorithms.

Exit Shell Script Based on Process Exit Code

After each command, the exit code can be found in the $? variable so you would have something like:

ls -al file.ext
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

You need to be careful of piped commands since the $? only gives you the return code of the last element in the pipe so, in the code:

ls -al file.ext | sed 's/^/xx: /"

will not return an error code if the file doesn't exist (since the sed part of the pipeline actually works, returning 0).

The bash shell actually provides an array which can assist in that case, that being PIPESTATUS. This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]}:

pax> false | true ; echo ${PIPESTATUS[0]}
1

Note that this is getting you the result of the false command, not the entire pipeline. You can also get the entire list to process as you see fit:

pax> false | true | false; echo ${PIPESTATUS[*]}
1 0 1

If you wanted to get the largest error code from a pipeline, you could use something like:

true | true | false | true | false
rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done
echo $rc

This goes through each of the PIPESTATUS elements in turn, storing it in rc if it was greater than the previous rc value.

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

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
    }
}

How can I force a long string without any blank to be wrapped?

If you're using PHP then the wordwrap function works well for this: http://php.net/manual/en/function.wordwrap.php

The CSS solution word-wrap: break-word; does not seem to be consistent across all browsers.

Other server-side languages have similar functions - or can be hand built.

Here's how the the PHP wordwrap function works:

$string = "ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA";

$wrappedstring = wordwrap($string,50,"&lt;br&gt;",true);

This wraps the string at 50 characters with a <br> tag. The 'true' parameter forces the string to be cut.

What is a deadlock?

Above some explanations are nice. Hope this may also useful: https://ora-data.blogspot.in/2017/04/deadlock-in-oracle.html

In a database, when a session (e.g. ora) wants a resource held by another session (e.g. data), but that session (data) also wants a resource which is held by the first session (ora). There can be more than 2 sessions involved also but idea will be the same. Actually, Deadlocks prevent some transactions from continuing to work. For example: Suppose, ORA-DATA holds lock A and requests lock B And SKU holds lock B and requests lock A.

Thanks,

Windows Scipy Install: No Lapack/Blas Resources Found

Using resources at http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy will solve the problem. However, you should be careful about versions compatibility. After trying for several times, finally I decided to uninstall python and then installed a fresh version of python along with numpy and then installed scipy and this resolved my problem.

Mask for an Input to allow phone numbers?

Angular5 and 6:

angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property

remove host and add @HostListener

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io

Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask

Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2 and 4:

Plunker >= RC.5

original

One way you could do it is using a directive that injects NgControl and manipulates the value

(for details see inline comments)

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMask {
  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    // special handling of backspace necessary otherwise
    // deleting of non-numeric characters is not recognized
    // this laves room for improvement for example if you delete in the 
    // middle of the string
    if (backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    } 

    // don't show braces for empty value
    if (newVal.length == 0) {
      newVal = '';
    } 
    // don't show braces for empty groups at the end
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="form">
    <input type="text" phone [(ngModel)]="data" ngControl="phone"> 
  </form>
  `,
  directives: [PhoneMask]
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      phone: ['']
    })
  }
}

Plunker example <= RC.5

Returning value from Thread

How about this solution?

It doesn't use the Thread class, but it IS concurrent, and in a way it does exactly what you request

ExecutorService pool = Executors.newFixedThreadPool(2); // creates a pool of threads for the Future to draw from

Future<Integer> value = pool.submit(new Callable<Integer>() {
    @Override
    public Integer call() {return 2;}
});

Now all you do is say value.get() whenever you need to grab your returned value, the thread is started the very second you give value a value so you don't ever have to say threadName.start() on it.

What a Future is, is a promise to the program, you promise the program that you'll get it the value it needs sometime in the near future

If you call .get() on it before it's done, the thread that's calling it will simply just wait until it's done

Check if a parameter is null or empty in a stored procedure

you can use:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')

Most efficient way to append arrays in C#?

If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.

Dependent DLL is not getting copied to the build output folder in Visual Studio

VS2019 V16.6.3

For me the problem was somehow the main .proj file ended up with an entry like this for the project whose DLL wasn't getting copied to the parent project bin folder:

<ProjectReference Include="Project B.csproj">
  <Project>{blah blah}</Project>
  <Name>Project B</Name>
  <Private>True</Private>
</ProjectReference>

I manually deleted the line <Private>True</Private> and the DLL was then copied to the main project bin folder on every build of the main project.

If you go to the reference of the problem project in the references folder of the main project, click it and view properties there is a "Copy Local" setting. The private tag equates to this setting, but for me for some reason changing copy local had no effect on the private tag in the .proj file.

Annoyingly I didn't change the copy local value for the reference, no idea how it got set that way and another day wasted tracking down a stupid problem with VS.

Thanks to all the other answers that helped zone me in on the cause.

HTH

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

How to replace unicode characters in string with something else python?

  1. Decode the string to Unicode. Assuming it's UTF-8-encoded:

    str.decode("utf-8")
    
  2. Call the replace method and be sure to pass it a Unicode string as its first argument:

    str.decode("utf-8").replace(u"\u2022", "*")
    
  3. Encode back to UTF-8, if needed:

    str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
    

(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)

How to debug a Flask app

Quick tip - if you use a PyCharm, go to Edit Configurations => Configurations and enable FLASK_DEBUG checkbox, restart the Run.

JavaScript Chart Library

We just bought a license of TechOctave Charts Suite for our new startup. I highly recommend them. Licensing is simple. Charts look great! It was easy to get started and has a powerful API for when we need it. I was shocked by how clean and extensible the code is. Really happy with our choice.

android studio 0.4.2: Gradle project sync failed error

same here, updating to 0.4.2 also broke everything in my case... It has nothing to do with memory usage : I've got 8 gig of memory and I have 3.5 gig free atm, so not having enough memory to start up a JVM is bullocks...

Actually it might have something to do with Gradle versions, I looked into the error log and found this :

2014-01-14 09:00:30,918 [ 61112] WARN - nal.AbstractExternalSystemTask - Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files.

You are using Gradle version 1.8, which is not supported. Please use version 1.9. Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.) com.intellij.openapi.externalSystem.model.ExternalSystemException: Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files

-

You are using Gradle version 1.8, which is not supported. Please use version 1.9.

Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.)

OK, I fixed it myself... In the project directory go to /gradle/wrapper directory and edit the gradle-wrapper properties file to this :

distributionUrl=http\://services.gradle.org/distributions/gradle-1.9-all.zip

After open your project in Android Studio and select the build.gradle file in the /src directory and edit it to this :

dependencies {
        classpath 'com.android.tools.build:gradle:0.7.+'
    }

After fixing it like this I discovered this article : http://tools.android.com/recent/androidstudio040released

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me

$date = '15-12-2016';
$nameOfDay = date('D', strtotime($date));
echo $nameOfDay;

Use l instead of D, if you prefer the full textual representation of the name

Doctrine - How to print out the real sql, not just the prepared statement?

There is no other real query, this is how prepared statements work. The values are bound in the database server, not in the application layer.

See my answer to this question: In PHP with PDO, how to check the final SQL parametrized query?

(Repeated here for convenience:)

Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.

So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....

You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.

Print a list in reverse order with range()?

The requirement in this question calls for a list of integers of size 10 in descending order. So, let's produce a list in python.

# This meets the requirement.
# But it is a bit harder to wrap one's head around this. right?
>>> range(10-1, -1, -1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# let's find something that is a bit more self-explanatory. Sounds good?
# ----------------------------------------------------

# This returns a list in ascending order.
# Opposite of what the requirement called for.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# This returns an iterator in descending order.
# Doesn't meet the requirement as it is not a list.
>>> reversed(range(10))
<listreverseiterator object at 0x10e14e090>

# This returns a list in descending order and meets the requirement
>>> list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

How can I trigger a JavaScript event click

.click() does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:

function fireClick(node){
    if (document.createEvent) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if (document.createEventObject) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function') {
        node.onclick(); 
    }
}

From this post

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

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

Put your wamp server onlineenter image description here

and then go to control panel > system and security > windows firewall and turn windows firewall off

now you can access your wamp server from another computer over local network by the network IP of computer which have wamp server installed like http://192.168.2.34/mysite

What are bitwise shift (bit-shift) operators and how do they work?

Let's say we have a single byte:

0110110

Applying a single left bitshift gets us:

1101100

The leftmost zero was shifted out of the byte, and a new zero was appended to the right end of the byte.

The bits don't rollover; they are discarded. That means if you left shift 1101100 and then right shift it, you won't get the same result back.

Shifting left by N is equivalent to multiplying by 2N.

Shifting right by N is (if you are using ones' complement) is the equivalent of dividing by 2N and rounding to zero.

Bitshifting can be used for insanely fast multiplication and division, provided you are working with a power of 2. Almost all low-level graphics routines use bitshifting.

For example, way back in the olden days, we used mode 13h (320x200 256 colors) for games. In Mode 13h, the video memory was laid out sequentially per pixel. That meant to calculate the location for a pixel, you would use the following math:

memoryOffset = (row * 320) + column

Now, back in that day and age, speed was critical, so we would use bitshifts to do this operation.

However, 320 is not a power of two, so to get around this we have to find out what is a power of two that added together makes 320:

(row * 320) = (row * 256) + (row * 64)

Now we can convert that into left shifts:

(row * 320) = (row << 8) + (row << 6)

For a final result of:

memoryOffset = ((row << 8) + (row << 6)) + column

Now we get the same offset as before, except instead of an expensive multiplication operation, we use the two bitshifts...in x86 it would be something like this (note, it's been forever since I've done assembly (editor's note: corrected a couple mistakes and added a 32-bit example)):

mov ax, 320; 2 cycles
mul word [row]; 22 CPU Cycles
mov di,ax; 2 cycles
add di, [column]; 2 cycles
; di = [row]*320 + [column]

; 16-bit addressing mode limitations:
; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov

Total: 28 cycles on whatever ancient CPU had these timings.

Vrs

mov ax, [row]; 2 cycles
mov di, ax; 2
shl ax, 6;  2
shl di, 8;  2
add di, ax; 2    (320 = 256+64)
add di, [column]; 2
; di = [row]*(256+64) + [column]

12 cycles on the same ancient CPU.

Yes, we would work this hard to shave off 16 CPU cycles.

In 32 or 64-bit mode, both versions get a lot shorter and faster. Modern out-of-order execution CPUs like Intel Skylake (see http://agner.org/optimize/) have very fast hardware multiply (low latency and high throughput), so the gain is much smaller. AMD Bulldozer-family is a bit slower, especially for 64-bit multiply. On Intel CPUs, and AMD Ryzen, two shifts are slightly lower latency but more instructions than a multiply (which may lead to lower throughput):

imul edi, [row], 320    ; 3 cycle latency from [row] being ready
add  edi, [column]      ; 1 cycle latency (from [column] and edi being ready).
; edi = [row]*(256+64) + [column],  in 4 cycles from [row] being ready.

vs.

mov edi, [row]
shl edi, 6               ; row*64.   1 cycle latency
lea edi, [edi + edi*4]   ; row*(64 + 64*4).  1 cycle latency
add edi, [column]        ; 1 cycle latency from edi and [column] both being ready
; edi = [row]*(256+64) + [column],  in 3 cycles from [row] being ready.

Compilers will do this for you: See how GCC, Clang, and Microsoft Visual C++ all use shift+lea when optimizing return 320*row + col;.

The most interesting thing to note here is that x86 has a shift-and-add instruction (LEA) that can do small left shifts and add at the same time, with the performance as an add instruction. ARM is even more powerful: one operand of any instruction can be left or right shifted for free. So scaling by a compile-time-constant that's known to be a power-of-2 can be even more efficient than a multiply.


OK, back in the modern days... something more useful now would be to use bitshifting to store two 8-bit values in a 16-bit integer. For example, in C#:

// Byte1: 11110000
// Byte2: 00001111

Int16 value = ((byte)(Byte1 >> 8) | Byte2));

// value = 000011111110000;

In C++, compilers should do this for you if you used a struct with two 8-bit members, but in practice they don't always.

window.print() not working in IE

function functionname() {

    var divToPrint = document.getElementById('divid');
    newWin= window.open();
    newWin.document.write(divToPrint.innerHTML);
    newWin.location.reload();
    newWin.focus();
    newWin.print();
    newWin.close();
}

How to check if a string "StartsWith" another string?

var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
    return true;
else
    return false;

Adding a new value to an existing ENUM Type

When using Navicat you can go to types (under view -> others -> types) - get the design view of the type - and click the "add label" button.

Is an entity body allowed for an HTTP DELETE request?

In case anyone is running into this issue testing, No it is not universally supported.

I am currently testing with Sahi Pro and it is very apparent a http DELETE call strips any provided body data (a large list of id's to delete in bulk as per endpoint design).

I have been in contact with them several times as well as sent in three separate packages of scrips, images, logs for them to review and they still have not confirmed this. A failed patch, and a missed conference calls by their support later and I still haven't gotten a solid answer.

I am certain Sahi does not support this, and I would imagine many other tools follow suite.

C# Convert List<string> to Dictionary<string, string>

You can use:

var dictionary = myList.ToDictionary(x => x);

Proper MIME type for OTF fonts

There are a number of font formats that one can set MIME types for, on both Apache and IIS servers. I've traditionally had luck with the following:

svg   as "image/svg+xml"                  (W3C: August 2011)
ttf   as "application/x-font-ttf"         (IANA: March 2013)
      or "application/x-font-truetype"
otf   as "application/x-font-opentype"    (IANA: March 2013)
woff  as "application/font-woff"          (IANA: January 2013)
woff2 as "application/font-woff2"         (W3C W./E.Draft: May 2014/March 2016)
eot   as "application/vnd.ms-fontobject"  (IANA: December 2005)
sfnt  as "application/font-sfnt"          (IANA: March 2013) 

According to the Internet Engineering Task Force who maintain the initial document regarding Multipurpose Internet Mail Extensions (MIME types) here: http://tools.ietf.org/html/rfc2045#section-5 ... it says in specifics:

"It is expected that additions to the larger set of supported types can generally be accomplished by the creation of new subtypes of these initial types. In the future, more top-level types may be defined only by a standards-track extension to this standard. If another top-level type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid a potential conflict with a future official name."

As it were, and over time, additional MIME types get added as standards are created and accepted, therefor we see examples of vendor specific MIME types such as vnd.ms-fontobject and the like.

UPDATE August 16, 2013: WOFF was formally registered at IANA on January 3, 2013 and Webkit has been updated on March 5, 2013 and browsers that are sourcing this update in their latest versions will start issuing warnings about the server MIME types with the old x-font-woff declaration. Since the warnings are only annoying I would recommend switching to the approved MIME type right away. In an ideal world, the warnings will resolve themselves in time.

UPDATE February 26, 2015: WOFF2 is now in the W3C Editor's Draft with the proposed mime-type. It should likely be submitted to IANA in the next year (possibly by end of 2016) following more recent progress timelines. As well SFNT, the scalable/spline container font format used in the backbone table reference of Google Web Fonts with their sfntly java library and is already registered as a mime type with IANA and could be added to this list as well dependent on individual need.

UPDATE October 4, 2017: We can follow the progression of the WOFF2 format here with a majority of modern browsers supporting the format successfully. As well, we can follow the IETF's "font" Top-Level Media Type request for comments (RFC) tracker and document regarding the latest set of proposed font types for approval.


For those wishing to embed the typeface in the proper order in your CSS please visit this article. But again, I've had luck with the following order:

@font-face {
    font-family: 'my-web-font';
    src: url('webfont.eot');
    src: url('webfont.eot?#iefix') format('embedded-opentype'),
         url('webfont.woff2') format('woff2'),
         url('webfont.woff') format('woff'),
         url('webfont.ttf') format('truetype'),
         url('webfont.svg#webfont') format('svg');
    font-weight: normal;
    font-style: normal;
}

For Subversion auto-properties, these can be listed as:

# Font formats
svg   = svn:mime-type=image/svg+xml
ttf   = svn:mime-type=application/x-font-ttf
otf   = svn:mime-type=application/x-font-opentype
woff  = svn:mime-type=application/font-woff
woff2 = svn:mime-type=application/font-woff2
eot   = svn:mime-type=application/vnd.ms-fontobject
sfnt  = svn:mime-type=application/font-sfnt

node and Error: EMFILE, too many open files

You're reading too many files. Node reads files asynchronously, it'll be reading all files at once. So you're probably reading the 10240 limit.

See if this works:

var fs = require('fs')
var events = require('events')
var util = require('util')
var path = require('path')

var FsPool = module.exports = function(dir) {
    events.EventEmitter.call(this)
    this.dir = dir;
    this.files = [];
    this.active = [];
    this.threads = 1;
    this.on('run', this.runQuta.bind(this))
};
// So will act like an event emitter
util.inherits(FsPool, events.EventEmitter);

FsPool.prototype.runQuta = function() {
    if(this.files.length === 0 && this.active.length === 0) {
        return this.emit('done');
    }
    if(this.active.length < this.threads) {
        var name = this.files.shift()

        this.active.push(name)
        var fileName = path.join(this.dir, name);
        var self = this;
        fs.stat(fileName, function(err, stats) {
            if(err)
                throw err;
            if(stats.isFile()) {
                fs.readFile(fileName, function(err, data) {
                    if(err)
                        throw err;
                    self.active.splice(self.active.indexOf(name), 1)
                    self.emit('file', name, data);
                    self.emit('run');

                });
            } else {
                self.active.splice(self.active.indexOf(name), 1)
                self.emit('dir', name);
                self.emit('run');
            }
        });
    }
    return this
};
FsPool.prototype.init = function() {
    var dir = this.dir;
    var self = this;
    fs.readdir(dir, function(err, files) {
        if(err)
            throw err;
        self.files = files
        self.emit('run');
    })
    return this
};
var fsPool = new FsPool(__dirname)

fsPool.on('file', function(fileName, fileData) {
    console.log('file name: ' + fileName)
    console.log('file data: ', fileData.toString('utf8'))

})
fsPool.on('dir', function(dirName) {
    console.log('dir name: ' + dirName)

})
fsPool.on('done', function() {
    console.log('done')
});
fsPool.init()

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

How to locate the Path of the current project directory in Java (IDE)?

I've just used this :

System.out.println(System.getenv().get("PWD"));

Using OpenJDK 11

What is the difference between Serializable and Externalizable in Java?

Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.

  ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("/Users/Desktop/files/temp.txt"));
        oos.writeObject(linkedListHead); //writing head of linked list
        oos.close();

But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:

public class MyExternalizable implements Externalizable
{

private String userName;
private String passWord;
private Integer roll;

public MyExternalizable()
{

}

public MyExternalizable(String userName, String passWord, Integer roll)
{
    this.userName = userName;
    this.passWord = passWord;
    this.roll = roll;
}

@Override
public void writeExternal(ObjectOutput oo) throws IOException 
{
    oo.writeObject(userName);
    oo.writeObject(roll);
}

@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException 
{
    userName = (String)oi.readObject();
    roll = (Integer)oi.readObject();
}

public String toString()
{
    StringBuilder b = new StringBuilder();
    b.append("userName: ");
    b.append(userName);
    b.append("  passWord: ");
    b.append(passWord);
    b.append("  roll: ");
    b.append(roll);

    return b.toString();
}
public static void main(String[] args)
{
    try
    {
        MyExternalizable m  = new MyExternalizable("nikki", "student001", 20);
        System.out.println(m.toString());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
        oos.writeObject(m);
        oos.close();

        System.out.println("***********************************************************************");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
        MyExternalizable mm = (MyExternalizable)ois.readObject();
        mm.toString();
        System.out.println(mm.toString());
    } 
    catch (ClassNotFoundException ex) 
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch(IOException ex)
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

Here if you comment the default constructer then the code will throw below exception:

 java.io.InvalidClassException: javaserialization.MyExternalizable;     
 javaserialization.MyExternalizable; no valid constructor.

We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.

The output of the above code is as per below:

userName: nikki  passWord: student001  roll: 20
***********************************************************************
userName: nikki  passWord: null  roll: 20

We can observe as we are not setting the value of passWord so it's null.

The same can also be achieved by declaring the password field as transient.

private transient String passWord;

Hope it helps. I apologize if i made any mistakes. Thanks.

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

How does Python return multiple values from a function?

mentioned also here, you can use this:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

MAMP mysql server won't start. No mysql processes are running

What worked for me was removing all files (but not directories) in the mysql dir.

Edit #2 As per answers below, you only need to delete the log files: [ib_logfile0, ib_logfile1]

So quit MAMP and then in the terminal:

rm /Applications/MAMP/db/mysql/ib_logfile* #(or wherever your MAMP is installed)

Edit!: A few people have mentioned that you may want to back up these files first in case anything goes wrong, so maybe just use mv instead:

mv /Applications/MAMP/db/mysql/*  /tmp/.

If this doesn't work go back and kill all processes: sudo killall -9 mysqld

This is also duplicated here: mysql server won't start MAMP

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

How to create a file name with the current date & time in Python?

While not using datetime, this solves your problem (answers your question) of getting a string with the current time and date format you specify:

import time
timestr = time.strftime("%Y%m%d-%H%M%S")
print timestr

yields:

20120515-155045

so your filename could append or use this string.

Android: Internet connectivity change listener

implementation 'com.treebo:internetavailabilitychecker:1.0.1'

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        InternetAvailabilityChecker.init(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
    }
}

Calculating text width

My solution

$.fn.textWidth = function(){
    var self = $(this),
        children = self.children(),
        calculator = $('<span style="display: inline-block;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

Basically an improvement over Rune's, that doesn't use .html so lightly

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

Where to place the 'assets' folder in Android Studio?

File > New > folder > assets Folder

Assets Folder

Twitter Bootstrap Datepicker within modal window

// re initialze datepicker
$(".bootstrap-datepicker").bsdatepicker({
    format: "yyyy-mm-dd",
    autoclose: true,
}).on('changeDate', function (ev) {
    $(this).bsdatepicker('hide');
});
//
$(".dropdown-menu").css({'z-index':'1100'});

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

This worked for me allowing me to co-locate javascript and html for partial view in same file. Helps with thought process to see html and related part in same partial view file.


In View which uses Partial View called "_MyPartialView.cshtml"

<div>
    @Html.Partial("_MyPartialView",< model for partial view>,
            new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>

@section scripts{

    @Html.Partial("_MyPartialView",<model for partial view>, 
                  new ViewDataDictionary { { "Region", "ScriptSection" } })

 }

In Partial View file

@model SomeType

@{
    var region = ViewData["Region"] as string;
}

@if (region == "HTMLSection")
{


}

@if (region == "ScriptSection")
{
        <script type="text/javascript">
    </script">
}

assignment operator overloading in c++

#include<iostream>

using namespace std;

class employee
{
    int idnum;
    double salary;
    public:
        employee(){}

        employee(int a,int b)
        {
            idnum=a;
            salary=b;
        }

        void dis()
        {
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
        }

        void operator=(employee &emp)
        {
            idnum=emp.idnum;
            salary=emp.salary;
        }

        void show()
        {
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
        }
};

main()
{
    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    cin>>a>>b;
    employee e1(a,b);
    e1.dis();
    employee e2;
    e2=e1;
    e2.show();  
}

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Reason is the old database credentials are cached /bootstap/cache/config.php

In the .env file, I modified it as follow

 DB_HOST=localhost
 DB_DATABASE=homestead
 DB_USERNAME=homestead
 DB_PASSWORD=secret

Then removed that file

/bootstap/cache/config.php 

If the issue still there you might try the following.

php artisan config:clear php artisan cache:clear php artisan config:cache

Exit vagrant by writing the exit command Then restart vargarnt/homestead config

vagrant reload --provision

Then opened vagrant again

Vagrant Up
Vagrant ssh