Programs & Examples On #Xwork

XWork is a command-pattern framework that is used to power Struts 2 as well as other applications.

How to parse a JSON object to a TypeScript Object

The reason that the compiler lets you cast the object returned from JSON.parse to a class is because typescript is based on structural subtyping.
You don't really have an instance of an Employee, you have an object (as you see in the console) which has the same properties.

A simpler example:

class A {
    constructor(public str: string, public num: number) {}
}

function logA(a: A) {
    console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);
}

let a1 = { str: "string", num: 0, boo: true };
let a2 = new A("stirng", 0);
logA(a1); // no errors
logA(a2);

(code in playground)

There's no error because a1 satisfies type A because it has all of its properties, and the logA function can be called with no runtime errors even if what it receives isn't an instance of A as long as it has the same properties.

That works great when your classes are simple data objects and have no methods, but once you introduce methods then things tend to break:

class A {
    constructor(public str: string, public num: number) { }

    multiplyBy(x: number): number {
        return this.num * x;
    }
}

// this won't compile:
let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'

// but this will:
let a2 = { str: "string", num: 0 } as A;

// and then you get a runtime error:
a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function

(code in playground)


Edit

This works just fine:

const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';
let employee1 = JSON.parse(employeeString);
console.log(employee1);

(code in playground)

If you're trying to use JSON.parse on your object when it's not a string:

let e = {
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 3,
    "username": "<anystring>",
    "permissions": "<anystring>",
    "lastUpdate": "<anydate>"
}
let employee2 = JSON.parse(e);

Then you'll get the error because it's not a string, it's an object, and if you already have it in this form then there's no need to use JSON.parse.

But, as I wrote, if you're going with this way then you won't have an instance of the class, just an object that has the same properties as the class members.

If you want an instance then:

let e = new Employee();
Object.assign(e, {
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 3,
    "username": "<anystring>",
    "permissions": "<anystring>",
    "lastUpdate": "<anydate>"
});

Maven Java EE Configuration Marker with Java Server Faces 1.2

You should check your project facets in the project configuration. This is where you may uncheck the JSF dependency.

enter image description here

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

You can remove this limitation by adding the following configuration section to your machine.config file:

<configuration>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="65535"/>
    </connectionManagement>
  </system.net>
</configuration>

You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

MSDN Documentation for System.Net.connectionManagement

Another Great Resource for understanding ConnectManagement in .NET

Hope this solves your problem!

EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

Vim for Windows - What do I type to save and exit from a file?

Instead of telling you how you could execute a certain command (Esc:wq), I can provide you two links that may help you with VIM:

However, the best way to learn Vim is not only using it for Git commits, but as a regular editor for your everyday work.

If you're not going to switch to Vim, it's nonsense to keep its commands in mind. In that case, go and set up your favourite editor to use with Git.

Regular expression for excluding special characters

I strongly suspect it's going to be easier to come up with a list of the characters that ARE allowed vs. the ones that aren't -- and once you have that list, the regex syntax becomes quite straightforward. So put me down as another vote for "whitelist".

Converting from longitude\latitude to Cartesian coordinates

Coordinate[] coordinates = new Coordinate[3];
coordinates[0] = new Coordinate(102, 26);
coordinates[1] = new Coordinate(103, 25.12);
coordinates[2] = new Coordinate(104, 16.11);
CoordinateSequence coordinateSequence = new CoordinateArraySequence(coordinates);

Geometry geo = new LineString(coordinateSequence, geometryFactory);

CoordinateReferenceSystem wgs84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem cartesinaCrs = DefaultGeocentricCRS.CARTESIAN;

MathTransform mathTransform = CRS.findMathTransform(wgs84, cartesinaCrs, true);

Geometry geo1 = JTS.transform(geo, mathTransform);

Including a css file in a blade template?

Work with this code :

{!! include ('css/app.css') !!}

find the array index of an object with a specific key value in underscore

findIndex was added in 1.8:

index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })

See: http://underscorejs.org/#findIndex

Alternatively, this also works, if you don't mind making another temporary list:

index = _.indexOf(_.pluck(tv, 'id'), voteId);

See: http://underscorejs.org/#pluck

How can I indent multiple lines in Xcode?

Another way to quickly reformat indenting is a quick cut and paste. ?+x and ?+v. I often find it faster than ?+[ or ?+] as you can do it with one hand (versus two) and it will reformat to the correct indent level in one shot.

Copy rows from one table to another, ignoring duplicates

Have you tried SELECT DISTINCT ?

INSERT INTO destTable
SELECT DISTINCT * FROM srcTable

Underscore prefix for property and method names in JavaScript

That's only a convention. The Javascript language does not give any special meaning to identifiers starting with underscore characters.

That said, it's quite a useful convention for a language that doesn't support encapsulation out of the box. Although there is no way to prevent someone from abusing your classes' implementations, at least it does clarify your intent, and documents such behavior as being wrong in the first place.

"Could not find Developer Disk Image"

This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:

ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

How to export and import environment variables in windows?

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

show and hide divs based on radio button click

This worked for me:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
        <script type="text/javascript">
            function show(str){
                document.getElementById('sh2').style.display = 'none';
                document.getElementById('sh1').style.display = 'block';
            }
            function show2(sign){
                document.getElementById('sh2').style.display = 'block';
                document.getElementById('sh1').style.display = 'none';
            }
        </script>
    </head>

    <body>
        <p>
            <input type="radio" name="r1" id="e1" onchange="show2()"/>&nbsp;I Am New User&nbsp;&nbsp;&nbsp;
            <input type="radio" checked="checked" name="r1" onchange="show(this.value)"/>&nbsp;Existing Member
        </p>
        <div id="sh1">Hello There !!</div>
        <p>&nbsp;</p>
        <div id="sh2" style="display:none;">Hey Watz up !!</div>
    </body>
</html>

Detect Windows version in .net

Like R. Bemrose suggested, if you are doing Windows 7 specific features, you should look at the Windows® API Code Pack for Microsoft® .NET Framework.

It contains a CoreHelpers class that let you determine the OS you are currently on (XP and above only, its a requirement for .NET nowaday)

It also provide multiple helper methods. For example, suppose that you want to use the jump list of Windows 7, there is a class TaskbarManager that provide a property called IsPlatformSupported and it will return true if you are on Windows 7 and above.

How to convert char to int?

int val = '1' - '0';

This can be done using ascii codes where '0' is the lowest and the number characters count up from there

Visual Studio breakpoints not being hit

Solved. Ended up being an incorrect configuration selected in the debug menu. I had mistakenly switched it to a release configuration that could not load the symbols for the document. Switched it to a debug configuration and the breakpoints hit just fine now.

To add on to what Abacus mentioned below, it could also be a web.config transform that is messing with your build. In our case, we have Release configurations that remove the debug attribute from the web.config's compilation section. Below is a screenshot of an example and Visual Studio's dropdown list of build configurations.

NOTE: Also make sure your Platform is correct along with the configuration. In my case, Dev.Debug|Mixed Platforms does not correctly build the solution but Dev.Debug|Any CPU will.

Build Configuration List

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

Java method to sum any number of ints

 public static void main(String args[])
 {
 System.out.println(SumofAll(12,13,14,15));//Insert your number here.
   {
      public static int SumofAll(int...sum)//Call this method in main method.
          int total=0;//Declare a variable which will hold the total value.
            for(int x:sum)
          {
           total+=sum;
           }
  return total;//And return the total variable.
    }
 }

Setting the focus to a text field

For me the easiest way to get it to work, is to put the component.requestFocus(); line, after the setVisible(true); line, at the bottom of your frame or panel constructor.

This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.

How to get the current taxonomy term ID (not the slug) in WordPress?

If you are in taxonomy page.

That's how you get all details about the taxonomy.

get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

This is how you get the taxonomy id

$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;

But if you are in post page (taxomony -> child)

$terms = wp_get_object_terms( get_queried_object_id(), 'taxonomy-name');
$term_id = $terms[0]->term_id;

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

Android Studio: Where is the Compiler Error Output Window?

Just click on the "Build" node in the Build Output

enter image description here

From some reason the "Compilation failed" node just started being automatically selected and for that the description window is very unhelpful.

Datetime equal or greater than today in MySQL

The below code worked for me.

declare @Today date

Set @Today=getdate() --date will equal today    

Select *

FROM table_name
WHERE created <= @Today

getResources().getColor() is deprecated

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

It is not deprecated in API Level 21, according to the documentation.

It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor() that takes the color resource ID and a Resources.Theme object) is only available in the M Developer Preview.

Hence, right now, continue using the single-parameter getColor() method. Later this year, consider using the two-parameter getColor() method on Android M devices, falling back to the deprecated single-parameter getColor() method on older devices.

Swift convert unix time to date and time

Convert timestamp into Date object.

If timestamp object is invalid then return current date.

class func toDate(_ timestamp: Any?) -> Date? {
    if let any = timestamp {
        if let str = any as? NSString {
            return Date(timeIntervalSince1970: str.doubleValue)
        } else if let str = any as? NSNumber {
            return Date(timeIntervalSince1970: str.doubleValue)
        }
    }
    return nil
}

How do I get the value of a textbox using jQuery?

Possible Duplicate:

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

 var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

 var txt=$('input:text[name=DrugDurationLength]').val();

What is the equivalent of "!=" in Excel VBA?

Try to use <> instead of !=.

Difference between \b and \B in regex

\B is not \b e.g. negative \b

pass-key here is no word boundary beside - so it matches \B in your first example there are word boundary beside cat so it matches \b

similar rules apply for others too. \W is negative of \w \UPPER CASE is negative of \LOWER CASE

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

You need to use an SSH key to login to your instance.

The GCE documentation explains the process here.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

No Persistence provider for EntityManager named

You need to add the hibernate-entitymanager-x.jar in the classpath.

In Hibernate 4.x, if the jar is present, then no need to add the org.hibernate.ejb.HibernatePersistence in persistence.xml file.

What does the regex \S mean in JavaScript?

The \s metacharacter matches whitespace characters.

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

If you happen to be using date in a MacOS environment, try this:

ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03

Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)

How to remove border of drop down list : CSS

You can't style the drop down box itself, only the input field. The box is rendered by the operating system.

enter image description here

If you want more control over the look of your input fields, you can always look into JavaScript solutions.

If, however, your intent was to remove the border from the input itself, your selector is wrong. Try this instead:

select#xyz {
    border: none;
}

Laravel 5 How to switch from Production mode

Laravel 5 gets its enviroment related variables from the .env file located in the root of your project. You just need to set APP_ENV to whatever you want, for example:

APP_ENV=development

This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:

APP_DEBUG=true

The role of the .env file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env file settings would be different from your local development enviroment.

In Java, how to append a string more efficiently?

Use StringBuilder class. It is more efficient at what you are trying to do.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Copy and paste content from one file to another file in vi

  1. Make sure you have the Vim version compiled with clipboard support
    • :echo has('clipboard') should return 1
    • if it returns 0 (for example Mac OS X, at least v10.11 (El Capitan), v10.9 (Mavericks) and v10.8 (Mountain Lion) - comes with a Vim version lacking clipboard support), you have to install a Vim version with clipboard support, say via brew install vim (don't forget to relaunch your terminal(s) after the installation)
  2. Enter a visual mode (V - multiline, v - plain, or Ctrlv - block-visual)
  3. Select line(s) you wish to copy
  4. "*y - to copy selected
  5. "*p - to paste copied

P.S:

  • you can replace steps 2-5 with the instructions from the answer by JayG, if you need to copy and paste a single line
  • to ease selecting lines, you can add set mouse+=a to your .vimrc - it will allow you to select lines in Vim using the mouse, while not selecting extraneous elements (like line numbers, etc.) NOTICE: it will block the ability to copy mouse-selected text to the system clipboard from Vim.

Get name of current class?

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

It is accessible from within the very definition of a class or a function, so for instance:

class Foo:
    print(__qualname__)

will effectively print Foo. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the . character.

However, there is no way to get an actual handle on the class being defined.

>>> class Foo:
...     print('Foo' in globals())
... 
False

How to query all the GraphQL type fields without writing a long query?

I faced this same issue when I needed to load location data that I had serialized into the database from the google places API. Generally I would want the whole thing so it works with maps but I didn't want to have to specify all of the fields every time.

I was working in Ruby so I can't give you the PHP implementation but the principle should be the same.

I defined a custom scalar type called JSON which just returns a literal JSON object.

The ruby implementation was like so (using graphql-ruby)

module Graph
  module Types
    JsonType = GraphQL::ScalarType.define do
      name "JSON"
      coerce_input -> (x) { x }
      coerce_result -> (x) { x }
    end
  end
end

Then I used it for our objects like so

field :location, Types::JsonType

I would use this very sparingly though, using it only where you know you always need the whole JSON object (as I did in my case). Otherwise it is defeating the object of GraphQL more generally speaking.

Closure in Java 7

Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Why don't self-closing script elements work?

To add to what Brad and squadette have said, the self-closing XML syntax <script /> actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml in the HTTP Content-Type header (and not as text/html).

However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html.

From w3:

In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.

I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script> syntax with text/html (HTML syntax + HTML mimetype).

If your server sends the text/html type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script /> will not work (this is a change, Firefox was previously less strict).

This will happen regardless of any fiddling with http-equiv meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />.

Read large files in Java

You can consider using memory-mapped files, via FileChannels .

Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.

Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

What is an idiomatic way of representing enums in Go?

I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types

package main

import "fmt"

type Enum interface {
    name() string
    ordinal() int
    values() *[]string
}

type GenderType uint

const (
    MALE = iota
    FEMALE
)

var genderTypeStrings = []string{
    "MALE",
    "FEMALE",
}

func (gt GenderType) name() string {
    return genderTypeStrings[gt]
}

func (gt GenderType) ordinal() int {
    return int(gt)
}

func (gt GenderType) values() *[]string {
    return &genderTypeStrings
}

func main() {
    var ds GenderType = MALE
    fmt.Printf("The Gender is %s\n", ds.name())
}

This is by far one of the idiomatic ways we could create Enumerated types and use in Go.

Edit:

Adding another way of using constants to enumerate

package main

import (
    "fmt"
)

const (
    // UNSPECIFIED logs nothing
    UNSPECIFIED Level = iota // 0 :
    // TRACE logs everything
    TRACE // 1
    // INFO logs Info, Warnings and Errors
    INFO // 2
    // WARNING logs Warning and Errors
    WARNING // 3
    // ERROR just logs Errors
    ERROR // 4
)

// Level holds the log level.
type Level int

func SetLogLevel(level Level) {
    switch level {
    case TRACE:
        fmt.Println("trace")
        return

    case INFO:
        fmt.Println("info")
        return

    case WARNING:
        fmt.Println("warning")
        return
    case ERROR:
        fmt.Println("error")
        return

    default:
        fmt.Println("default")
        return

    }
}

func main() {

    SetLogLevel(INFO)

}

What is it exactly a BLOB in a DBMS context

BLOB :

BLOB (Binary Large Object) is a large object data type in the database system. BLOB could store a large chunk of data, document types and even media files like audio or video files. BLOB fields allocate space only whenever the content in the field is utilized. BLOB allocates spaces in Giga Bytes.

USAGE OF BLOB :

You can write a binary large object (BLOB) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB value to your database, issue the appropriate INSERT or UPDATE statement and pass the BLOB value as an input parameter. If your BLOB is stored as text, such as a SQL Server text field, you can pass the BLOB as a string parameter. If the BLOB is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.

A useful link : Storing documents as BLOB in Database - Any disadvantages ?

How do I make a batch file terminate upon encountering an error?

The shortest:

command || exit /b

If you need, you can set the exit code:

command || exit /b 666

And you can also log:

command || echo ERROR && exit /b

Good Free Alternative To MS Access

Much in line with Aurelio's answer, I now work in Ruby on Rails on some applications that I might formerly have done in MS Access. The back end database for a Rails App. is usually, MySql (works well enough and is available on most shared Web hosting) or PostgreSQL (the better choice when possible).

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Webrtc is a part of peer to peer connection. We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection. And websockets play the role of handshaking process.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

How to change navbar/container width? Bootstrap 3

Hello this working you try! in your case is .navbar-fixed-top{}

.navbar-fixed-bottom{
    width:1200px;
    left:20%;
}

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

Nesting await in Parallel.ForEach

I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;

 Parallel.ForEach(ids, i =>
{
    ICustomerRepo repo = new CustomerRepo();
    // Run this in thread which Parallel library occupied.
    var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
    customers.Add(cust);
});

C# cannot convert method to non delegate type

As @Antonijn stated, you need to execute getTitle method, by adding parentheses:

 string t = obj.getTitle();

But I want to add, that you are doing Java programming in C#. There is concept of properties (pair of get and set methods), which should be used in such cases:

public class Pin
{
    private string _title;

    // you don't need to define empty constructor
    // public Pin() { }

    public string Title 
    {
        get { return _title; }
        set { _title = value; }
    }  
}

And even more, in this case you can ask compiler not only for get and set methods generation, but also for back storage generation, via auto-impelemented property usage:

public class Pin
{
    public string Title { get; set; }
}

And now you don't need to execute method, because properties used like fields:

foreach (Pin obj in ClassListPin.pins)
{
     string t = obj.Title;
}

How to hide the border for specified rows of a table?

Add programatically noborder class to specific row to hide it

<style>
     .noborder
      {
        border:none;
      }
    </style>

<table>

    <tr>
       <th>heading1</th>
       <th>heading2</th>
    </tr>


    <tr>
       <td>content1</td>
       <td>content2</td>
    </tr>
    /*no border for this row */
    <tr class="noborder">
       <td>content1</td>
       <td>content2</td>
    </tr>

</table>

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.

Algorithm to calculate the number of divisors of a given number

Number theory textbooks call the divisor-counting function tau. The first interesting fact is that it's multiplicative, ie. t(ab) = t(a)t(b) , when a and b have no common factor. (Proof: each pair of divisors of a and b gives a distinct divisor of ab).

Now note that for p a prime, t(p**k) = k+1 (the powers of p). Thus you can easily compute t(n) from its factorisation.

However factorising large numbers can be slow (the security of RSA crytopraphy depends on the product of two large primes being hard to factorise). That suggests this optimised algorithm

  1. Test if the number is prime (fast)
  2. If so, return 2
  3. Otherwise, factorise the number (slow if multiple large prime factors)
  4. Compute t(n) from the factorisation

Get list of all tables in Oracle?

select * from dba_tables

gives all the tables of all the users only if the user with which you logged in is having the sysdba privileges.

Validate SSL certificates with Python

Here's an example script which demonstrates certificate validation:

import httplib
import re
import socket
import sys
import urllib2
import ssl

class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
    def __init__(self, host, cert, reason):
        httplib.HTTPException.__init__(self)
        self.host = host
        self.cert = cert
        self.reason = reason

    def __str__(self):
        return ('Host %s returned an invalid certificate (%s) %s\n' %
                (self.host, self.reason, self.cert))

class CertValidatingHTTPSConnection(httplib.HTTPConnection):
    default_port = httplib.HTTPS_PORT

    def __init__(self, host, port=None, key_file=None, cert_file=None,
                             ca_certs=None, strict=None, **kwargs):
        httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
        self.key_file = key_file
        self.cert_file = cert_file
        self.ca_certs = ca_certs
        if self.ca_certs:
            self.cert_reqs = ssl.CERT_REQUIRED
        else:
            self.cert_reqs = ssl.CERT_NONE

    def _GetValidHostsForCert(self, cert):
        if 'subjectAltName' in cert:
            return [x[1] for x in cert['subjectAltName']
                         if x[0].lower() == 'dns']
        else:
            return [x[0][1] for x in cert['subject']
                            if x[0][0].lower() == 'commonname']

    def _ValidateCertificateHostname(self, cert, hostname):
        hosts = self._GetValidHostsForCert(cert)
        for host in hosts:
            host_re = host.replace('.', '\.').replace('*', '[^.]*')
            if re.search('^%s$' % (host_re,), hostname, re.I):
                return True
        return False

    def connect(self):
        sock = socket.create_connection((self.host, self.port))
        self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                          certfile=self.cert_file,
                                          cert_reqs=self.cert_reqs,
                                          ca_certs=self.ca_certs)
        if self.cert_reqs & ssl.CERT_REQUIRED:
            cert = self.sock.getpeercert()
            hostname = self.host.split(':', 0)[0]
            if not self._ValidateCertificateHostname(cert, hostname):
                raise InvalidCertificateException(hostname, cert,
                                                  'hostname mismatch')


class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
    def __init__(self, **kwargs):
        urllib2.AbstractHTTPHandler.__init__(self)
        self._connection_args = kwargs

    def https_open(self, req):
        def http_class_wrapper(host, **kwargs):
            full_kwargs = dict(self._connection_args)
            full_kwargs.update(kwargs)
            return CertValidatingHTTPSConnection(host, **full_kwargs)

        try:
            return self.do_open(http_class_wrapper, req)
        except urllib2.URLError, e:
            if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
                raise InvalidCertificateException(req.host, '',
                                                  e.reason.args[1])
            raise

    https_request = urllib2.HTTPSHandler.do_request_

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "usage: python %s CA_CERT URL" % sys.argv[0]
        exit(2)

    handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
    opener = urllib2.build_opener(handler)
    print opener.open(sys.argv[2]).read()

validation of input text field in html using javascript

If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.

HTML:

<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>

JavaScript:

function validateForm(form) {

    var nameField = form.name;
    var addressLine01 = form.addressLine01;

    if (isNotEmpty(nameField)) {
        if(isNotEmpty(addressLine01)) {
            return true;
        {
    {
    return false;
}

function isNotEmpty(field) {

    var fieldData = field.value;

    if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {

        field.className = "FieldError"; //Classs to highlight error
        alert("Please correct the errors in order to continue.");
        return false;
    } else {

        field.className = "FieldOk"; //Resets field back to default
        return true; //Submits form
    }
}

The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.

Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.

If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

Difference between setTimeout with and without quotes and parentheses

i think the setTimeout function that you write is not being run. if you use jquery, you can make it run correctly by doing this :

    function alertMsg() {
      //your func
    }

    $(document).ready(function() {
       setTimeout(alertMsg,3000); 
       // the function you called by setTimeout must not be a string.
    });

How can I disable mod_security in .htaccess file?

For anyone that simply are looking to bypass the ERROR page to display the content on shared hosting. You might wanna try and use redirect in .htaccess file. If it is say 406 error, on UnoEuro it didn't seem to work simply deactivating the security. So I used this instead:

ErrorDocument 406 /

Then you can always change the error status using PHP. But be aware that in my case doing so means I am opening a door to SQL injections as I am bypassing WAF. So you will need to make sure that you either have your own security measures or enable the security again asap.

PHP - auto refreshing page

you can use

<meta http-equiv="refresh" content="10" > 

just add it after the head tags

where 10 is the time your page will refresh itself

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here


Source added - Agile Web Development with Rails 4

How do I fetch only one branch of a remote Git repository?

I know there are a lot of answers already, but these are the steps that worked for me:

  1. git fetch <remote_name> <branch_name>
  2. git branch <branch_name> FETCH_HEAD
  3. git checkout <branch_name>

These are based on the answer by @Abdulsattar Mohammed, the comment by @Christoph on that answer, and these other stack overflow questions and their answers:

Like Operator in Entity Framework?

For EfCore here is a sample to build LIKE expression

protected override Expression<Func<YourEntiry, bool>> BuildLikeExpression(string searchText)
    {
        var likeSearch = $"%{searchText}%";

        return t => EF.Functions.Like(t.Code, likeSearch)
                    || EF.Functions.Like(t.FirstName, likeSearch)
                    || EF.Functions.Like(t.LastName, likeSearch);
    }

//Calling method

var query = dbContext.Set<YourEntity>().Where(BuildLikeExpression("Text"));

error: Your local changes to the following files would be overwritten by checkout

Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).

Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not pushed); or - use stash:

git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop

git stash save will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.

How can I use a batch file to write to a text file?

You can use echo, and redirect the output to a text file (see notes below):

rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt

Output:

D:\Temp>WriteText

D:\Temp>type test.txt
This is a test
123
245.67

D:\Temp>

Notes:

  • @echo off turns off printing of each command to the console
  • Unless you give it a specific path name, redirection with > or >> will write to the current directory (the directory the code is being run in).
  • The echo This is a test > test.txt uses one > to overwrite any file that already exists with new content.
  • The remaining echo statements use two >> characters to append to the text file (add to), instead of overwriting it.
  • The type test.txt simply types the file output to the command window.

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

Select single item from a list

Maybe I'm missing something here, but usually calling .SingleOrDefault() is the way to go to return either the single element in the list, or a default value (null for reference or nullable types) if the list is empty. It generates an exception if the list contains more than one element.

Use FirstOrDefault() to cover the case where you could have more than one.

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

How can I initialize a String array with length 0 in Java?

As others have said,

new String[0]

will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:

private static final String[] EMPTY_ARRAY = new String[0];

and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.

Command to find information about CPUs on a UNIX machine

Try psrinfo to find the processor type and the number of physical processors installed on the system.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

Get source jar files attached to Eclipse for Maven-managed dependencies

If you are using meclipse do

window --> maven --> Download Artifact Sources (select check)

(If you still get attach source window, then click on attach file button and close the attach source window. The next time you try to see the source it will open the correct source)

Surajz

How do I find duplicates across multiple columns?

You have to self join stuff and match name and city. Then group by count.

select 
   s.id, s.name, s.city 
from stuff s join stuff p ON (
   s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1

Focus Input Box On Load

This is what works fine for me:

<form name="f" action="/search">
    <input name="q" onfocus="fff=1" />
</form>

fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.

<body onload="if(!this.fff)document.f.q.focus();">
    <!-- ... the rest of the page ... -->
</body>

From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html

adding directory to sys.path /PYTHONPATH

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

How to submit http form using C#

Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.

For example: there is a class called System.Net.WebClient with simple methods:

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

For more documentation and features, refer to the MSDN page.

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

angular.element vs document.getElementById or jQuery selector with spin (busy) control

This worked for me well.

angular.forEach(element.find('div'), function(node)
{
  if(node.id == 'someid'){
    //do something
  }
  if(node.className == 'someclass'){
    //do something
  }
});

How to use onBlur event on Angular2?

HTML

<input name="email" placeholder="Email"  (blur)="$event.target.value=removeSpaces($event.target.value)" value="">

TS

removeSpaces(string) {
 let splitStr = string.split(' ').join('');
  return splitStr;
}

How to use log levels in java

the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.

Proper way of checking if row exists in table in PL/SQL block

Many ways to skin this cat. I put a simple function in each table's package...

function exists( id_in in yourTable.id%type ) return boolean is
  res boolean := false;
begin
  for c1 in ( select 1 from yourTable where id = id_in and rownum = 1 ) loop
    res := true;
    exit; -- only care about one record, so exit.
  end loop;
  return( res );
end exists;

Makes your checks really clean...

IF pkg.exists(someId) THEN
...
ELSE
...
END IF;

Check if URL has certain string with PHP

This worked for me:

// Check if URL contains the word "car" or "CAR"
   if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false){
   echo "Car here";
   } else {
   echo "No car here";
   }
If you want to use HTML in the echo, be sure to use ' ' instead of " ".
I use this code to show an alert on my webpage https://geaskb.nl/ 
where the URL contains the word "Omnik" 
but hide the alert on pages that do not contain the word "Omnik" in the URL.

Explanation stripos : https://www.php.net/manual/en/function.stripos

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Assuming the value is nvarchar type for that only we are using N''

How do I delete multiple rows in Entity Framework (without foreach)

In EF 6.2 this works perfectly, sending the delete directly to the database without first loading the entities:

context.Widgets.Where(predicate).Delete();

With a fixed predicate it's quite straightforward:

context.Widgets.Where(w => w.WidgetId == widgetId).Delete();

And if you need a dynamic predicate have a look at LINQKit (Nuget package available), something like this works fine in my case:

Expression<Func<Widget, bool>> predicate = PredicateBuilder.New<Widget>(x => x.UserID == userID);
if (somePropertyValue != null)
{
    predicate = predicate.And(w => w.SomeProperty == somePropertyValue);
}
context.Widgets.Where(predicate).Delete();

TimePicker Dialog from clicking EditText

You can use the below code in the onclick listener of edittext

  TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
    new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {

            tv_time.setText(hourOfDay + ":" + minute);
        }
    }, hour, minute, false);
     timePickerDialog.show();

You can see the full code at Android timepicker example

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

How can I delete Docker's images?

The reason for the error is that even though the image did not have any tag, there still exists a container created on that image which might be in the exited state. So you need to ensure that you have stopped and deleted all containers created on those images. The following command helps you in removing all containers that are not running:

docker rm `docker ps -aq --no-trunc --filter "status=exited"`

Now this removes all the dangling non-intermediate <none> images:

docker rmi `docker images --filter 'dangling=true' -q --no-trunc`

Note: To stops all running containers:

docker stop `docker ps -q`

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

Android, landscape only orientation?

Just two steps needed:

  1. Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); after setContentView().

  2. In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />

Hope it helps and happy coding :)

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Circle drawing with SVG's arc path

These answers are much too complicated.

A simpler way to do this without creating two arcs or convert to different coordinate systems..

This assumes your canvas area has width w and height h.

`M${w*0.5 + radius},${h*0.5}
 A${radius} ${radius} 0 1 0 ${w*0.5 + radius} ${h*0.5001}`

Just use the "long arc" flag, so the full flag is filled. Then make the arcs 99.9999% the full circle. Visually it is the same. Avoid the sweep flag by just starting the circle at the rightmost point in the circle (one radius directly horizontal from the center).

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

There are two times when you can update a record through a view:

  1. If the view has no joins or procedure calls and selects data from a single underlying table.
  2. If the view has an INSTEAD OF INSERT trigger associated with the view.

Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.

How to print colored text to the terminal?

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

How to completely uninstall Android Studio on Mac?

Execute these commands in the terminal (excluding the lines with hashtags - they're comments):

# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*

If you would like to delete all projects:

rm -Rf ~/AndroidStudioProjects

To remove gradle related files (caches & wrapper)

rm -Rf ~/.gradle

Use the below command to delete all Android Virtual Devices(AVDs) and keystores.

Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)

rm -Rf ~/.android

To delete Android SDK tools

rm -Rf ~/Library/Android*

Emulator Console Auth Token

rm -Rf ~/.emulator_console_auth_token

Thanks to those who commented/improved on this answer!


Notes

  1. The flags for rm are case-sensitive1 (as with most other commands), which means that the f flag must be in lower case. However, the r flag can also be capitalised.
  2. The flags for rm can be either combined together or separated. They don't have to be combined.

What the flags indicate

  1. The r flag indicates that the rm command should-

    attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for rm (See man rm for more info)

  2. The f flag indicates that the rm command should-

    attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for rm (See man rm for more info)

Redirect Windows cmd stdout and stderr to a single file

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
    {
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        va_end(argumentsToPass);
        for(int n = numOfArgs - 1; n >= 0; n--)
        {
            char next;
            next = list[n];
            __asm push next;
        }
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);
    }

Initialize a byte array to a certain value, other than the default null?

You could speed up the initialization and simplify the code by using the the Parallel class (.NET 4 and newer):

public static void PopulateByteArray(byte[] byteArray, byte value)
{
    Parallel.For(0, byteArray.Length, i => byteArray[i] = value);
}

Of course you can create the array at the same time:

public static byte[] CreateSpecialByteArray(int length, byte value)
{
    var byteArray = new byte[length];
    Parallel.For(0, length, i => byteArray[i] = value);
    return byteArray;
}

Write to file, but overwrite it if it exists

To overwrite one file's content to another file. use cat eg.

echo  "this is foo" > foobar.txt
cat foobar.txt

echo "this is bar" > bar.txt
cat bar.txt

Now to overwrite foobar we can use a cat command as below

cat bar.txt >> foobar.txt
cat foobar.txt

enter image description here

Handling ExecuteScalar() when no results are returned

If you either want the string or an empty string in case something is null, without anything can break:

using (var cmd = new OdbcCommand(cmdText, connection))
{
    var result = string.Empty;
    var scalar = cmd.ExecuteScalar();
    if (scalar != DBNull.Value) // Case where the DB value is null
    {
        result = Convert.ToString(scalar); // Case where the query doesn't return any rows. 
        // Note: Convert.ToString() returns an empty string if the object is null. 
        //       It doesn't break, like scalar.ToString() would have.
    }
    return result;
}

How do you convert epoch time in C#?

Here is my solution:

public long GetTime()
{
    DateTime dtCurTime = DateTime.Now.ToUniversalTime();

    DateTime dtEpochStartTime = Convert.ToDateTime("1/1/1970 0:00:00 AM");

    TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);

    double epochtime;

    epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);   

    return Convert.ToInt64(epochtime);
}

SVN commit command

First add the new files:

svn add fileName

Then commit all new and modified files

svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"

If non source files are to be committed then

svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"

How to close IPython Notebook properly?

These commands worked for me:

jupyter notebook list # shows the running notebooks and their port-numbers
                      # (for instance: 8080)
lsof -n -i4TCP:[port-number] # shows PID.
kill -9 [PID] # kill the process.

This answer was adapted from here.

How to get HTTP response code for a URL in Java?

Its a old question, but lets to show in the REST way (JAX-RS):

import java.util.Arrays;
import javax.ws.rs.*

(...)

Response response = client
    .target( url )
    .request()
    .get();

// Looking if response is "200", "201" or "202", for example:
if( Arrays.asList( Status.OK, Status.CREATED, Status.ACCEPTED ).contains( response.getStatusInfo() ) ) {
    // lets something...
}

(...)

How can I calculate divide and modulo for integers in C#?

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

How to fill a Javascript object literal with many static key/value pairs efficiently?

It works fine with the object literal notation:

var map = { key : { "aaa", "rrr" }, 
            key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
          }

Btw, the common way to instantiate arrays

var array = [];
// directly with values:
var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];

and objects

var object = {};

Also you can do either:

obj.property     // this is prefered but you can also do
obj["property"]  // this is the way to go when you have the keyname stored in a var

var key = "property";
obj[key] // is the same like obj.property

How to get absolute value from double - c-language

Use fabs instead of abs to find absolute value of double (or float) data types. Include the <math.h> header for fabs function.

double d1 = fabs(-3.8951);

How to remove package using Angular CLI?

I don't know about CLI, I had tried, but I couldn't. I deleted using IDE Idea history.

If You use an Intellij Idea, just open History changes.

Tap by main folder of the project -> right click -> local history -> show history.

Then from top to bottom revert changes.

enter image description here

It should help! Good luck!=)

Can MySQL convert a stored UTC time to local timezone?

select convert_tz(now(),@@session.time_zone,'+03:00')

For get the time only use:

time(convert_tz(now(),@@session.time_zone,'+03:00'))

How to implement the --verbose or -v option into a script?

There could be a global variable, likely set with argparse from sys.argv, that stands for whether the program should be verbose or not. Then a decorator could be written such that if verbosity was on, then the standard input would be diverted into the null device as long as the function were to run:

import os
from contextlib import redirect_stdout
verbose = False

def louder(f):
    def loud_f(*args, **kwargs):
        if not verbose:
            with open(os.devnull, 'w') as void:
                with redirect_stdout(void):
                    return f(*args, **kwargs)
        return f(*args, **kwargs)
    return loud_f

@louder
def foo(s):
    print(s*3)

foo("bar")

This answer is inspired by this code; actually, I was going to just use it as a module in my program, but I got errors I couldn't understand, so I adapted a portion of it.

The downside of this solution is that verbosity is binary, unlike with logging, which allows for finer-tuning of how verbose the program can be. Also, all print calls are diverted, which might be unwanted for.

Tab space instead of multiple non-breaking spaces ("nbsp")?

The &nbsp; unit is font size dependent. To understand that dependency, consider em and rem units of measure, using this CSS/HTML method.

CSS

.tab { margin-left: 1rem; }

HTML

<div class=“tab> ...p and h elements... </div>

DISPLAY

1em approximately equals 4 &nbsp; but &nbsp; em unit and &nbsp; rem unit display depend on element and style use, indenting something like this.

--------h1 indented 1em
--p indented 1em
----h1 indented 1rem
----p indented 1rem

Both margin-left and padding-left work. There is no tab unit of length in HTML or CSS. A .tab class selector can be used.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

static_cast is the first cast you should attempt to use. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating static_cast isn't necessary, but it's important to note that the T(something) syntax is equivalent to (T)something and should be avoided (more on that later). A T(something, something_else) is safe, however, and guaranteed to call the constructor.

static_cast can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through virtual inheritance. It does not do checking, however, and it is undefined behavior to static_cast down a hierarchy to a type that isn't actually the type of the object.


const_cast can be used to remove or add const to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast). It is important to note that modifying a formerly const value is only undefined if the original variable is const; if you use it to take the const off a reference to something that wasn't declared with const, it is safe. This can be useful when overloading member functions based on const, for instance. It can also be used to add const to an object, such as to call a member function overload.

const_cast also works similarly on volatile, though that's less common.


dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can't, it will return nullptr in the case of a pointer, or throw std::bad_cast in the case of a reference.

dynamic_cast has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using virtual inheritance. It also can only go through public inheritance - it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare.


reinterpret_cast is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int, or all sorts of other nasty things. Largely, the only guarantee you get with reinterpret_cast is that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.


C-style cast and function-style cast are casts using (type)object or type(object), respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:

  • const_cast
  • static_cast (though ignoring access restrictions)
  • static_cast (see above), then const_cast
  • reinterpret_cast
  • reinterpret_cast, then const_cast

It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a reinterpret_cast, and the latter should be preferred when explicit casting is needed, unless you are sure static_cast will succeed or reinterpret_cast will fail. Even then, consider the longer, more explicit option.

C-style casts also ignore access control when performing a static_cast, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.

Simple java program of pyramid

This code will print a pyramid of dollars.

public static void main(String[] args) {

     for(int i=0;i<5;i++) {
         for(int j=0;j<5-i;j++) {
             System.out.print(" ");
         }
        for(int k=0;k<=i;k++) {
            System.out.print("$ ");
        }
        System.out.println();  
    }

}

OUPUT :

     $ 
    $ $ 
   $ $ $ 
  $ $ $ $ 
 $ $ $ $ $

How to view the contents of an Android APK file?

There is also zzos. (Full disclosure: I wrote it). It only decompiles the actual resources, not the dex part (baksmali, which I did not write, does an excellent job of handling that part).

Zzos is much less known than apktool, but there are some APKs that are better handled by it (and vice versa - more on that later). Mostly, APKs containing custom resource types (not modifiers) were not handled by apktool the last time I checked, and are handled by zzos. There are also some cases with escaping that zzos handles better.

On the negative side of things, zzos (current version) requires a few support tools to install. It is written in perl (as opposed to APKTool, which is written in Java), and uses aapt for the actual decompilation. It also does not decompile attrib resources yet (which APKTool does).

The meaning of the name is "aapt", Android's resource compiler, shifted down one letter.

How to highlight cell if value duplicate in same column for google spreadsheet?

Highlight duplicates (in column C):

=COUNTIF(C:C, C1) > 1

Explanation: The C1 here doesn't refer to the first row in C. Because this formula is evaluated by a conditional format rule, instead, when the formula is checked to see if it applies, the C1 effectively refers to whichever row is currently being evaluated to see if the highlight should be applied. (So it's more like INDIRECT(C &ROW()), if that means anything to you!). Essentially, when evaluating a conditional format formula, anything which refers to row 1 is evaluated against the row that the formula is being run against. (And yes, if you use C2 then you asking the rule to check the status of the row immediately below the one currently being evaluated.)

So this says, count up occurences of whatever is in C1 (the current cell being evaluated) that are in the whole of column C and if there is more than 1 of them (i.e. the value has duplicates) then: apply the highlight (because the formula, overall, evaluates to TRUE).

Highlight the first duplicate only:

=AND(COUNTIF(C:C, C1) > 1, COUNTIF(C$1:C1, C1) = 1)

Explanation: This only highlights if both of the COUNTIFs are TRUE (they appear inside an AND()).

The first term to be evaluated (the COUNTIF(C:C, C1) > 1) is the exact same as in the first example; it's TRUE only if whatever is in C1 has a duplicate. (Remember that C1 effectively refers to the current row being checked to see if it should be highlighted).

The second term (COUNTIF(C$1:C1, C1) = 1) looks similar but it has three crucial differences:

It doesn't search the whole of column C (like the first one does: C:C) but instead it starts the search from the first row: C$1 (the $ forces it to look literally at row 1, not at whichever row is being evaluated).

And then it stops the search at the current row being evaluated C1.

Finally it says = 1.

So, it will only be TRUE if there are no duplicates above the row currently being evaluated (meaning it must be the first of the duplicates).

Combined with that first term (which will only be TRUE if this row has duplicates) this means only the first occurrence will be highlighted.

Highlight the second and onwards duplicates:

=AND(COUNTIF(C:C, C1) > 1, NOT(COUNTIF(C$1:C1, C1) = 1), COUNTIF(C1:C, C1) >= 1)

Explanation: The first expression is the same as always (TRUE if the currently evaluated row is a duplicate at all).

The second term is exactly the same as the last one except it's negated: It has a NOT() around it. So it ignores the first occurence.

Finally the third term picks up duplicates 2, 3 etc. COUNTIF(C1:C, C1) >= 1 starts the search range at the currently evaluated row (the C1 in the C1:C). Then it only evaluates to TRUE (apply highlight) if there is one or more duplicates below this one (and including this one): >= 1 (it must be >= not just > otherwise the last duplicate is ignored).

What's the meaning of System.out.println in Java?

Check following link:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

You will clearly see that:

System is a class in the java.lang package.

out is a static member of the System class, and is an instance of java.io.PrintStream.

println is a method of java.io.PrintStream. This method is overloaded to print message to output destination, which is typically a console or file.

Eclipse executable launcher error: Unable to locate companion shared library

My experience and advice: Install Eclipse Juno on C: drive.

After download the zip, put it on C:, click the right mouse button -> extract here. Then a folder called eclipse will be created in C: drive.

Then go to Eclipse executable, run it, and all will be ok.

How to add column if not exists on PostgreSQL?

This is basically the solution from sola, but just cleaned up a bit. It's different enough that I didn't just want to "improve" his solution (plus, I sort of think that's rude).

Main difference is that it uses the EXECUTE format. Which I think is a bit cleaner, but I believe means that you must be on PostgresSQL 9.1 or newer.

This has been tested on 9.1 and works. Note: It will raise an error if the schema/table_name/or data_type are invalid. That could "fixed", but might be the correct behavior in many cases.

CREATE OR REPLACE FUNCTION add_column(schema_name TEXT, table_name TEXT, 
column_name TEXT, data_type TEXT)
RETURNS BOOLEAN
AS
$BODY$
DECLARE
  _tmp text;
BEGIN

  EXECUTE format('SELECT COLUMN_NAME FROM information_schema.columns WHERE 
    table_schema=%L
    AND table_name=%L
    AND column_name=%L', schema_name, table_name, column_name)
  INTO _tmp;

  IF _tmp IS NOT NULL THEN
    RAISE NOTICE 'Column % already exists in %.%', column_name, schema_name, table_name;
    RETURN FALSE;
  END IF;

  EXECUTE format('ALTER TABLE %I.%I ADD COLUMN %I %s;', schema_name, table_name, column_name, data_type);

  RAISE NOTICE 'Column % added to %.%', column_name, schema_name, table_name;

  RETURN TRUE;
END;
$BODY$
LANGUAGE 'plpgsql';

usage:

select add_column('public', 'foo', 'bar', 'varchar(30)');

Does PHP have threading?

Here is an example of what Wilco suggested:

$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);

Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:

exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
     // less than 2 rows in the ps, therefore report is complete
}

There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

make html text input field grow as I type?

For those strictly looking for a solution that works for input or textarea, this is the simplest solution I've came across. Only a few lines of CSS and one line of JS.

The JavaScript sets a data-* attribute on the element equal to the value of the input. The input is set within a CSS grid, where that grid is a pseudo-element that uses that data-* attribute as its content. That content is what stretches the grid to the appropriate size based on the input value.

How to remove focus border (outline) around text/input boxes? (Chrome)

Please use the following syntax to remove the border of text box and remove the highlighted border of browser style.

input {
    background-color:transparent;
    border: 0px solid;
    height:30px;
    width:260px;
}
input:focus {
    outline:none;
}

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my app I have app delegate and other classes that need to be accessed by the tests as public. As outlined here, I then import my my app into my tests.

When I recently created two new classes ,their test targets were both the main and testing parts. Removing them from their membership from the tests solved the issue.

Assembly code vs Machine code vs Object code?

Assembly code is a human readable representation of machine code:

mov eax, 77
jmp anywhere

Machine code is pure hexadecimal code:

5F 3A E3 F1

I assume you mean object code as in an object file. This is a variant of machine code, with a difference that the jumps are sort of parameterized such that a linker can fill them in.

An assembler is used to convert assembly code into machine code (object code) A linker links several object (and library) files to generate an executable.

I have once written an assembler program in pure hex (no assembler available) luckily this was way back on the good old (ancient) 6502. But I'm glad there are assemblers for the pentium opcodes.

How can I measure the similarity between two images?

Well, not to answer your question directly, but I have seen this happen. Microsoft recently launched a tool called PhotoSynth which does something very similar to determine overlapping areas in a large number of pictures (which could be of different aspect ratios).

I wonder if they have any available libraries or code snippets on their blog.

Angular 2 : No NgModule metadata found

I had the same problem but none of all those solutions worked for me. After further investigation, I found out that an undesired import was in one of my component.

I use setTimeout function in app.component but for any reason Visual Studio added import { setTimeout } from 'timer'; where it was not needed. Removing this line fixed the issue.

So remember to check your imports before going further. Hope it may help someone.

Android fastboot waiting for devices

Just use sudo, fast boot needs Root Permission

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

How do I find the PublicKeyToken for a particular dll?

Just adding more info, I wasn't able to find sn.exe utility in the mentioned locations, in my case it was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

How to get label text value form a html page?

For cases where the data element is inside the label like in this example:

<label for="subscription">Subscription period
    <select id='subscription' name='subscription'>
        <option></option>
        <option>1 year</option>
        <option>2 years</option>
        <option>3 years</option>
    </select>
</label>

all the previous answers will give an unexpected result:

"Subscription period


                    1 year
                    2 years
                    3 years

            "

While the expected result would be:

"Subscription period"

So, the correct solution will be like this:

const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
    .call(label.childNodes, x => x.nodeName === "#text")
    .map(x => x.textContent)
    .join(" ")
    .trim();

Can I add background color only for padding?

Another option with pure CSS would be something like this:

nav {
    margin: 0px auto;
    width: 100%;
    height: 50px;
    background-color: white;
    float: left;
    padding: 10px;
    border: 2px solid red;
    position: relative;
    z-index: 10;
}

nav:after {
    background-color: grey;
    content: '';
    display: block;
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    z-index: -1;
}

Demo here

How to style the UL list to a single line

HTML code:

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

CSS code:

ul.list li{
  width: auto;
  float: left;
}

Inserting a value into all possible locations in a list

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')

arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')

arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

Here's some example code:

import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
    print perm

will print out

('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

How do you loop in a Windows batch file?

@echo off
echo.
set /p num1=Enter Prelim:
echo.
set /p num2=Enter Midterm:
echo.
set /p num3=Enter Semi:
echo.
set /p num4=Enter Finals:
echo.
set /a ans=%num1%+%num2%+%num3%+%num4%
set /a avg=%ans%/4
ECHO %avg%
if %avg%>=`95` goto true
:true
echo The two numbers you entered were the same.
echo.
pause
exit

Android Studio error: "Environment variable does not point to a valid JVM installation"

Do step by step as shown in this YouTube Video

Go to: System -> Advanced system settings -> Environment Variables

Add a new variable to you profile NAME=JAVA_HOME STRING: Program Files/java/"your string" Save and Start Android Studio ;)

enter image description here

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Good question.

  • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

  • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

  • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

  • IDENTITY(): used when declaring a column in a table as an identity column.

For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.

To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

Android Facebook style slide

I've implemented facebook-like slideout navigation in this library project.

You can easy built it into your application, your UI and navigation. You will need to implement only one Activity and one Fragment, let library know about it - and library will provide all wanted animations and navigation.

Inside the repo you can find demo-project, with how to use the lib to implement facebook-like navigation. Here is short video with record of demo project.

Also this lib should be compatible this ActionBar pattern, because is based on Activities transactions and TranslateAnimations (not Fragments transactions and custom Views).

Right now, the most problem is to make it work well for application, which support both portrait and landscape mode. If you have any feedback, please provide it via github.

All the best,
Alex

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

Edit

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

How to make rectangular image appear circular with CSS

For those who use Bootstrap 3, it has a great CSS class to do the job:

<img src="..." class="img-circle">

How to calculate a Mod b in Casio fx-991ES calculator

type normal division first and then type shift + S->d

ReferenceError: describe is not defined NodeJs

Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.

So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.

Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

What, why or when it is better to choose cshtml vs aspx?

While the syntax is certainly different between Razor (.cshtml/.vbhtml) and WebForms (.aspx/.ascx), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).

This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.

Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.

Read from file or stdin

Just testing for end of file with feof would do, I think.

How to sort ArrayList<Long> in decreasing order?

You can also sort an ArrayList with a TreeSet instead of a comparator. Here's an example from a question I had before for an integer array. I'm using "numbers" as a placeholder name for the ArrayList.


     import.java.util.*;
        class MyClass{
        public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<Integer>(); 

        TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
        numbers = new ArrayList<Integer>(ts);
        System.out.println("\nThe numbers in ascending order are:");
        for(int i=0; i<numbers.size(); i++)
        System.out.print(numbers.get(i).intValue()+" ");
        System.out.println("\nThe numbers in descending order are:");
        for(int i=numbers.size()-1; i>=0; i--)
        System.out.print(numbers.get(i).intValue()+" ");
    }
}

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

How to split data into trainset and testset randomly?

You could also use numpy. When your data is stored in a numpy.ndarray:

import numpy as np
from random import sample
l = 100 #length of data 
f = 50  #number of elements you need
indices = sample(range(l),f)

train_data = data[indices]
test_data = np.delete(data,indices)

Random float number generation

If you know that your floating point format is IEEE 754 (almost all modern CPUs including Intel and ARM) then you can build a random floating point number from a random integer using bit-wise methods. This should only be considered if you do not have access to C++11's random or Boost.Random which are both much better.

float rand_float()
{
    // returns a random value in the range [0.0-1.0)

    // start with a bit pattern equating to 1.0
    uint32_t pattern = 0x3f800000;

    // get 23 bits of random integer
    uint32_t random23 = 0x7fffff & (rand() << 8 ^ rand());

    // replace the mantissa, resulting in a number [1.0-2.0)
    pattern |= random23;

    // convert from int to float without undefined behavior
    assert(sizeof(float) == sizeof(uint32_t));
    char buffer[sizeof(float)];
    memcpy(buffer, &pattern, sizeof(float));
    float f;
    memcpy(&f, buffer, sizeof(float));

    return f - 1.0;
}

This will give a better distribution than one using division.

How do you implement a re-try-catch?

Below snippet execute some code snippet. If you got any error while executing the code snippet, sleep for M milliseconds and retry. Reference link.

public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
  throws InterruptedException {

 int currentExecutionCount = 0;
 boolean codeExecuted = false;

 while (currentExecutionCount < noOfTimesToRetry) {
  try {
   codeSnippet.errorProneCode();
   System.out.println("Code executed successfully!!!!");
   codeExecuted = true;
   break;
  } catch (Exception e) {
   // Retry after 100 milliseconds
   TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
   System.out.println(e.getMessage());
  } finally {
   currentExecutionCount++;
  }
 }

 if (!codeExecuted)
  throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
}

How do I check if the mouse is over an element in jQuery?

This code illustrates what happytime harry and I are trying to say. When the mouse enters, a tooltip comes out, when the mouse leaves it sets a delay for it to disappear. If the mouse enters the same element before the delay is triggered, then we destroy the trigger before it goes off using the data we stored before.

$("someelement").mouseenter(function(){
    clearTimeout($(this).data('timeoutId'));
    $(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
    var someElement = $(this),
        timeoutId = setTimeout(function(){
            someElement.find(".tooltip").fadeOut("slow");
        }, 650);
    //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
    someElement.data('timeoutId', timeoutId); 
});

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

How do I use floating-point division in bash?

As others have indicated, bash does not have built-in floating-point operators.

You can implement floating-point in bash, even without using calculator programs like bc and awk, or any external programs for that matter.

I'm doing exactly this in my project, shellmath, in three basic steps:

  1. Break the numbers down into their integer and fractional parts
  2. Use the built-in integer operators to process the parts separately while being careful about place-value and carrying
  3. Recombine the results

As a teaser, I've added a demo script that calculates e using its Taylor series centered at x=0.

Please check it out if you have a moment. I welcome your feedback!

How can a add a row to a data frame in R?

Like @Khashaa and @Richard Scriven point out in comments, you have to set consistent column names for all the data frames you want to append.

Hence, you need to explicitly declare the columns names for the second data frame, de, then use rbind(). You only set column names for the first data frame, df:

df<-data.frame("hi","bye")
names(df)<-c("hello","goodbye")

de<-data.frame("hola","ciao")
names(de)<-c("hello","goodbye")

newdf <- rbind(df, de)

How to import CSV file data into a PostgreSQL table?

Use this SQL code

    copy table_name(atribute1,attribute2,attribute3...)
    from 'E:\test.csv' delimiter ',' csv header

the header keyword lets the DBMS know that the csv file have a header with attributes

for more visit http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/

Could not create the Java virtual machine

I had this issue today, and for me the problem was that I had allocated too much memory:

-Xmx1024M -XX:MaxPermSize=1024m

Once I reduced the PermGen space, everything worked fine:

-Xmx1024M -XX:MaxPermSize=512m

I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.

How do I vertical center text next to an image in html/css?

This might get you started.

I always fall back on this solution. Not too hack-ish and gets the job done.

EDIT: I should point out that you might achieve the effect you want with the following code (forgive the inline styles; they should be in a separate sheet). It seems that the default alignment on an image (baseline) will cause the text to align to the baseline; setting that to middle gets things to render nicely, at least in FireFox 3.

_x000D_
_x000D_
<div>_x000D_
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg" style="vertical-align: middle;" width="100px"/>_x000D_
    <span style="vertical-align: middle;">Here is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Netbeans 8.0.2 The module has not been deployed

I had the same error here but with glassfish server. Maybe it can help. I needed to configure the glassfish-web.xml file with the content inside the <resources> from glassfish-resources.xml. As I got another error I could find this annotation in the server log:

Caused by: java.lang.RuntimeException: Error in parsing WEB-INF/glassfish-web.xml for archive [file:/C:/Users/Win/Documents/NetBeansProjects/svad/build/web/]: The xml element should be [glassfish-web-app] rather than [resources]

All I did then was to change the <resources> tag and apply <glassfish-web-app> in the glassfish-web.xml file.

How can I truncate a double to only two decimal places in Java?

DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

Check available RoundingMode and DecimalFormat.

Difference between Divide and Conquer Algo and Dynamic Programming

I assume you have already read Wikipedia and other academic resources on this, so I won't recycle any of that information. I must also caveat that I am not a computer science expert by any means, but I'll share my two cents on my understanding of these topics...

Dynamic Programming

Breaks the problem down into discrete subproblems. The recursive algorithm for the Fibonacci sequence is an example of Dynamic Programming, because it solves for fib(n) by first solving for fib(n-1). In order to solve the original problem, it solves a different problem.

Divide and Conquer

These algorithms typically solve similar pieces of the problem, and then put them together at the end. Mergesort is a classic example of divide and conquer. The main difference between this example and the Fibonacci example is that in a mergesort, the division can (theoretically) be arbitrary, and no matter how you slice it up, you are still merging and sorting. The same amount of work has to be done to mergesort the array, no matter how you divide it up. Solving for fib(52) requires more steps than solving for fib(2).

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

How to sum digits of an integer in java?

without mapping ? the quicker lambda solution

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );

…or same with the slower % operator

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );


…or Unicode compliant

Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );

How to check if activity is in foreground or in visible background?

UPD: updated to state Lifecycle.State.RESUMED. Thanks to @htafoya for that.

In 2019 with help of new support library 28+ or AndroidX you can simply use:

val isActivityInForeground = activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)

You can read more in the documenation to understand what happened under the hood.

How To Check If A Key in **kwargs Exists?

You want

if 'errormessage' in kwargs:
    print("found it")

To get the value of errormessage

if 'errormessage' in kwargs:
    print("errormessage equals " + kwargs.get("errormessage"))

In this way, kwargs is just another dict. Your first example, if kwargs['errormessage'], means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError.

Your second example, if errormessage in kwargs:, means "if kwargs contains the element named by "errormessage", and unless "errormessage" is the name of a variable, you'll get a NameError.

I should mention that dictionaries also have a method .get() which accepts a default parameter (itself defaulting to None), so that kwargs.get("errormessage") returns the value if that key exists and None otherwise (similarly kwargs.get("errormessage", 17) does what you might think it does). When you don't care about the difference between the key existing and having None as a value or the key not existing, this can be handy.

Load data from txt with pandas

You can use:

data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]

Add sep=" " in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.

How can I remount my Android/system as read-write in a bash script using adb?

Otherwise... if

getenforce

returns

Enforcing

Then maybe you should call

setenforce 0 
mount -o rw,remount /system 
setenforce 1

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

How to exclude records with certain values in sql select

SELECT  DISTINCT a.StoreID
FROM    tableName a
        LEFT JOIN tableName b 
          ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE   b.StoreID IS NULL

OUTPUT

+---------+
¦ STOREID ¦
¦---------¦
¦       3 ¦
+---------+

C# Generics and Type Checking

You can use typeof(T).

private static string BuildClause<T>(IList<T> clause)
{
     Type itemType = typeof(T);
     if(itemType == typeof(int) || itemType == typeof(decimal))
    ...
}

Address already in use: JVM_Bind

as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How to select <td> of the <table> with javascript?

There are also the rows and cells members;

var t = document.getElementById("tbl");
for (var r = 0; r < t.rows.length; r++) {
    for (var c = 0; c < t.rows[r].cells.length; c++) {
        alert(t.rows[r].cells[c].innerHTML)
    }
}

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

Here's a linearization option on simple data that uses tools from scikit learn.

Given

import numpy as np

import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer


np.random.seed(123)

# General Functions
def func_exp(x, a, b, c):
    """Return values from a general exponential function."""
    return a * np.exp(b * x) + c


def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Helper
def generate_data(func, *args, jitter=0):
    """Return a tuple of arrays with random data along a general function."""
    xs = np.linspace(1, 5, 50)
    ys = func(xs, *args)
    noise = jitter * np.random.normal(size=len(xs)) + jitter
    xs = xs.reshape(-1, 1)                                  # xs[:, np.newaxis]
    ys = (ys + noise).reshape(-1, 1)
    return xs, ys
transformer = FunctionTransformer(np.log, validate=True)

Code

Fit exponential data

# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp)             # 1

# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans)                # 2
model = results.predict
y_fit = model(x_samp)

# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit")     # 3
plt.title("Exponential Fit")

enter image description here

Fit log data

# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp)             # 1

# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp)                # 2
model = results.predict
y_fit = model(x_trans)

# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit")             # 3
plt.title("Logarithmic Fit")

enter image description here


Details

General Steps

  1. Apply a log operation to data values (x, y or both)
  2. Regress the data to a linearized model
  3. Plot by "reversing" any log operations (with np.exp()) and fit to original data

Assuming our data follows an exponential trend, a general equation+ may be:

enter image description here

We can linearize the latter equation (e.g. y = intercept + slope * x) by taking the log:

enter image description here

Given a linearized equation++ and the regression parameters, we could calculate:

  • A via intercept (ln(A))
  • B via slope (B)

Summary of Linearization Techniques

Relationship |  Example   |     General Eqn.     |  Altered Var.  |        Linearized Eqn.  
-------------|------------|----------------------|----------------|------------------------------------------
Linear       | x          | y =     B * x    + C | -              |        y =   C    + B * x
Logarithmic  | log(x)     | y = A * log(B*x) + C | log(x)         |        y =   C    + A * (log(B) + log(x))
Exponential  | 2**x, e**x | y = A * exp(B*x) + C | log(y)         | log(y-C) = log(A) + B * x
Power        | x**2       | y =     B * x**N + C | log(x), log(y) | log(y-C) = log(B) + N * log(x)

+Note: linearizing exponential functions works best when the noise is small and C=0. Use with caution.

++Note: while altering x data helps linearize exponential data, altering y data helps linearize log data.

Start index for iterating Python list

If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):

dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
            'Friday', 'Saturday',  ]

startDayName = 'Monday'

startIndex = dayNames.index( startDayName )
print ( startIndex )

rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]

for x in rotatedDayNames:
    print ( x )

Using generic std::function objects with member functions in one class

If you need to store a member function without the class instance, you can do something like this:

class MyClass
{
public:
    void MemberFunc(int value)
    {
      //do something
    }
};

// Store member function binding
auto callable = std::mem_fn(&MyClass::MemberFunc);

// Call with late supplied 'this'
MyClass myInst;
callable(&myInst, 123);

What would the storage type look like without auto? Something like this:

std::_Mem_fn_wrap<void,void (__cdecl TestA::*)(int),TestA,int> callable

You can also pass this function storage to a standard function binding

std::function<void(int)> binding = std::bind(callable, &testA, std::placeholders::_1);
binding(123); // Call

Past and future notes: An older interface std::mem_func existed, but has since been deprecated. A proposal exists, post C++17, to make pointer to member functions callable. This would be most welcome.

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

Convert all data frame character columns to factors

Roland's answer is great for this specific problem, but I thought I would share a more generalized approach.

DF <- data.frame(x = letters[1:5], y = 1:5, z = LETTERS[1:5], 
                 stringsAsFactors=FALSE)
str(DF)
# 'data.frame':  5 obs. of  3 variables:
#  $ x: chr  "a" "b" "c" "d" ...
#  $ y: int  1 2 3 4 5
#  $ z: chr  "A" "B" "C" "D" ...

## The conversion
DF[sapply(DF, is.character)] <- lapply(DF[sapply(DF, is.character)], 
                                       as.factor)
str(DF)
# 'data.frame':  5 obs. of  3 variables:
#  $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  $ y: int  1 2 3 4 5
#  $ z: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5

For the conversion, the left hand side of the assign (DF[sapply(DF, is.character)]) subsets the columns that are character. In the right hand side, for that subset, you use lapply to perform whatever conversion you need to do. R is smart enough to replace the original columns with the results.

The handy thing about this is if you wanted to go the other way or do other conversions, it's as simple as changing what you're looking for on the left and specifying what you want to change it to on the right.

Imply bit with constant 1 or 0 in SQL Server

You might add the second snippet as a field definition for ICourseBased in a view.

DECLARE VIEW MyView
AS
  SELECT
  case 
  when FC.CourseId is not null then cast(1 as bit)
  else cast(0 as bit)
  end
  as IsCoursedBased
  ...

SELECT ICourseBased FROM MyView

Syntax behind sorted(key=lambda: ...)

One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]

print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))

Results:

[('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

From the GNU UPC website:

Compiler build fails with fatal error: gnu/stubs-32.h: No such file or directory

This error message shows up on the 64 bit systems where GCC/UPC multilib feature is enabled, and it indicates that 32 bit version of libc is not installed. There are two ways to correct this problem:

  • Install 32 bit version of glibc (e.g. glibc-devel.i686 on Fedora, CentOS, ..)
  • Disable 'multilib' build by supplying "--disable-multilib" switch on the compiler configuration command

How do I keep Python print from adding newlines or spaces?

Greg is right-- you can use sys.stdout.write

Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then

lst = ['h', 'm']
print  "".join(lst)

Where can I find the API KEY for Firebase Cloud Messaging?

You can find API KEY from the google-services.json file

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

Adding a background image to a <div> element

<div id="image">Example to have Background Image</div>

We need to Add the below content in Style tag:

.image {
  background-image: url('C:\Users\ajai\Desktop\10.jpg');
}

What is an AssertionError? In which case should I throw it from my own code?

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

  1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
  2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

For example:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

Python 3.4.0 with MySQL database

I solved it this way: download the zipped package from here and follow this set of instructions:

unzip  /path/to/downloads/folder/mysql-connector-python-VER.zip  

In case u got a .gz u can use ->

tar xzf mysql-connector-python-VER.tar.gz 

And then:

cd mysql-connector-python-VER  # move into the directory

sudo python3 setup.py install # NOTICE I USED PYTHON3 INSTEAD OF PYTHON

You can read about it here

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!