Programs & Examples On #Wss4j

The Apache WSS4J™ is a Java implementation of the primary security standards for Web Services, namely the OASIS Web Services Security (WS-Security) specifications from the OASIS Web Services Security TC.

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

How to display Toast in Android?

 Toast toast=Toast.makeText(getApplicationContext(),"Hello", Toast.LENGTH_SHORT);
 toast.setGravity(Gravity.CENTER, 0, 0); // last two args are X and Y are used for setting position
 toast.setDuration(10000);//you can even use milliseconds to display toast
 toast.show();**//showing the toast is important**

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Just delete /etc/ImageMagick/policy.xml file. E.g.

rm /etc/<ImageMagick_PATH>/policy.xml

For ImageMagick 6, it's:

sudo rm /etc/ImageMagick-6/policy.xml

std::cin input with spaces?

You want to use the .getline function in cin.

#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

  cout << "Enter your name: ";
  cin.getline (name,256);

  cout << "Enter your favourite movie: ";
  cin.getline (title,256);

  cout << name << "'s favourite movie is " << title;

  return 0;
}

Took the example from here. Check it out for more info and examples.

Using Docker-Compose, how to execute multiple commands

If you need to run more than one daemon process, there's a suggestion in the Docker documentation to use Supervisord in an un-detached mode so all the sub-daemons will output to the stdout.

From another SO question, I discovered you can redirect the child processes output to the stdout. That way you can see all the output!

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)

See:


Here's a working example:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

in folder src/main/webapp/WEB-INF

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet><servlet-name>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

json-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

in folder src/main/resources:

mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

In folder src/main/java/test/json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Request.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Result.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:

{"addition":20,"subtraction":6,"multiplication":91}

Go to beginning of line without opening new line in VI

0 Takes you to the beginning of the line

Shift 0 Takes you to the end of the line

RegEx for Javascript to allow only alphanumeric

Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Using pip behind a proxy with CNTLM

In Ubuntu 14.04 LTS

   sudo pip --proxy http://PROXYDOM:PROXYPORT install package

Cheers

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

How to use the addr2line command in Linux?

You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.

Given the VA 0x4005BDC by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps file while your program is running. The line of interest is the text segment of your process, which is identifiable by the permissions r-xp and the name of your program or library.

Let's say that the base VA is 0x0x4005000. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc. Then, supply that to add2line:

addr2line -e a.out -j .text 0xbdc

And see if that gets you your line number.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

You are trying to set the timezone for date_time which already has a timezone. Use replace and astimezone functions.

local_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)

Intel's HAXM equivalent for AMD on Windows OS

Buying a new processor is one solution, but for some of us that means buying other components as well. Alternatively you could just buy an Android phone that supports your lowest target API level and run your apps off the phone. You can find some of those phones on Amazon, Ebay, craigslist for pennies (sometimes). Plus this grants you the benefit of actually running on the minimum hardware you intend to support. While this may be a bit slower than installing your app on an emulated system, it will probably save you money.

Android, device testing/debugging link: http://developer.android.com/tools/device.html

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

With Spring Boot, I'm not entirely sure why this was necessary (I got the /error fallback even though @ResponseBody was defined on an @ExceptionHandler), but the following in itself did not work:

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

It still threw an exception, apparently because no producible media types were defined as a request attribute:

// AbstractMessageConverterMethodProcessor
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType,
        ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
        throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

    Class<?> valueType = getReturnValueType(value, returnType);
    Type declaredType = getGenericType(returnType);
    HttpServletRequest request = inputMessage.getServletRequest();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
if (value != null && producibleMediaTypes.isEmpty()) {
        throw new IllegalArgumentException("No converter found for return value of type: " + valueType);   // <-- throws
    }

// ....

@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, Type declaredType) {
    Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (!CollectionUtils.isEmpty(mediaTypes)) {
        return new ArrayList<MediaType>(mediaTypes);

So I added them.

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    Set<MediaType> mediaTypes = new HashSet<>();
    mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    httpServletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

And this got me through to have a "supported compatible media type", but then it still didn't work, because my ErrorMessage was faulty:

public class ErrorMessage {
    int code;

    String message;
}

JacksonMapper did not handle it as "convertable", so I had to add getters/setters, and I also added @JsonProperty annotation

public class ErrorMessage {
    @JsonProperty("code")
    private int code;

    @JsonProperty("message")
    private String message;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Then I received my message as intended

{"code":400,"message":"An \"url\" parameter must be defined."}

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

Pass array to MySQL stored routine

I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar:

  declare pos int;           -- Keeping track of the next item's position
  declare item varchar(100); -- A single item of the input
  declare breaker int;       -- Safeguard for while loop 

  -- The string must end with the delimiter
  if right(inputString, 1) <> '|' then
     set inputString = concat(inputString, '|');
  end if;

  DROP TABLE IF EXISTS MyTemporaryTable;
  CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
  set breaker = 0;

  while (breaker < 2000) && (length(inputString) > 1) do
     -- Iterate looking for the delimiter, add rows to temporary table.
     set breaker = breaker + 1;
     set pos = INSTR(inputString, '|');
     set item = LEFT(inputString, pos - 1);
     set inputString = substring(inputString, pos + 1);
     insert into MyTemporaryTable values(item);
  end while;

For example, input for this code could be the string Apple|Banana|Orange. MyTemporaryTable will be populated with three rows containing the strings Apple, Banana, and Orange respectively.

I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).

Hope this helps somebody.

Force IE compatibility mode off using tags

There is the "edge" mode.

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>My Web Page</title>
   </head>
   <body>
      <p>Content goes here.</p>
   </body>
</html>

From the linked MSDN page:

Edge mode tells Windows Internet Explorer to display content in the highest mode available, which actually breaks the “lock-in” paradigm. With Internet Explorer 8, this is equivalent to IE8 mode. If a (hypothetical) future release of Internet Explorer supported a higher compatibility mode, pages set to Edge mode would appear in the highest mode supported by that version; however, those same pages would still appear in IE8 mode when viewed with Internet Explorer 8.

However, "edge" mode is not encouraged in production use:

It is recommended that Web developers restrict their use of Edge mode to test pages and other non-production uses because of the possible unexpected results of rendering page content in future versions of Windows Internet Explorer.

I honestly don't entirely understand why. But according to this, the best way to go at the moment is using IE=8.

How to list all the files in android phone by using adb shell?

Open cmd type adb shell then press enter. Type ls to view files list.

Android widget: How to change the text of a button

I had a button in my layout.xml that was defined as a View as in:

final View myButton = findViewById(R.id.button1);

I was not able to change the text on it until I also defined it as a button:

final View vButton = findViewById(R.id.button1);
final Button bButton = (Button) findViewById(R.id.button1);

When I needed to change the text, I used the bButton.setText("Some Text"); and when I wanted to alter the view, I used the vButton.

Worked great!

CodeIgniter removing index.php from url

Step 1 :

Add this in htaccess file

<IfModule mod_rewrite.c>
  RewriteEngine On
  #RewriteBase /

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [QSA,L]
</IfModule>

Step 2 :

Remove index.php in codeigniter config

$config['base_url'] = ''; 
$config['index_page'] = '';

Step 3 :

Allow overriding htaccess in Apache Configuration (Command)

sudo nano /etc/apache2/apache2.conf

and edit the file & change to

AllowOverride All

for www folder

Step 4 :

Enabled apache mod rewrite (Command)

sudo a2enmod rewrite

Step 5 :

Restart Apache (Command)

sudo /etc/init.d/apache2 restart

Http 415 Unsupported Media type error with JSON

The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers

Changing navigation title programmatically

I prefer using self.navigationItem.title = "Your Title Here" over self.title = "Your Title Here" to provide title in the navigation bar since tab bar also uses self.title to alter its title. You should try the following code once.

Note: calling the super view lifecycle is necessary before you do any stuffs.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
    }
}

private func setupNavBar() {
    self.navigationItem.title = "Your Title Here"
}

How to make primary key as autoincrement for Room Persistence lib

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true)

Reference for PrimaryKey.

In a URL, should spaces be encoded using %20 or +?

You can use either - which means most people opt for "+" as it's more human readable.

How to get the top position of an element?

$("#myTable").offset().top;

This will give you the computed offset (relative to document) of any object.

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

Change Toolbar color in Appcompat 21

This is what is known as a DarkActionBar which means you should use the following theme to obtain your desired style:

<android.support.v7.widget.Toolbar  
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="@dimen/triple_height_toolbar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

How do I check OS with a preprocessor directive?

There is no standard macro that is set according to C standard. Some C compilers will set one on some platforms (e.g. Apple's patched GCC sets a macro to indicate that it is compiling on an Apple system and for the Darwin platform). Your platform and/or your C compiler might set something as well, but there is no general way.

Like hayalci said, it's best to have these macros set in your build process somehow. It is easy to define a macro with most compilers without modifying the code. You can simply pass -D MACRO to GCC, i.e.

gcc -D Windows
gcc -D UNIX

And in your code:

#if defined(Windows)
// do some cool Windows stuff
#elif defined(UNIX)
// do some cool Unix stuff
#else
#    error Unsupported operating system
#endif

How to sort a HashMap in Java

Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.

How to declare a local variable in Razor?

You can also use:

@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}

No need for a variable in the code

Cannot implicitly convert type 'int?' to 'int'.

Check the declaration of your variable. It must be like that

public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }

I hope it is useful for you

Code for Greatest Common Divisor in Python

The algorithms with m-n can runs awfully long.

This one performs much better:

def gcd(x, y):
    while y != 0:
        (x, y) = (y, x % y)
    return x

How to enumerate a range of numbers starting at 1

Simplest way to do in Python 2.5 exactly what you ask about:

import itertools as it

... it.izip(it.count(1), xrange(2000, 2005)) ...

If you want a list, as you appear to, use zip in lieu of it.izip.

(BTW, as a general rule, the best way to make a list out of a generator or any other iterable X is not [x for x in X], but rather list(X)).

Creating files in C++

Do this with a file stream. When a std::ofstream is closed, the file is created. I personally like the following code, because the OP only asks to create a file, not to write in it:

#include <fstream>

int main()
{
    std::ofstream file { "Hello.txt" };
    // Hello.txt has been created here
}

The temporary variable file is destroyed right after its creation, so the stream is closed and thus the file is created.

How to prevent colliders from passing through each other?

  • Edit ---> Project Settings ---> Time ... decrease "Fixed Timestep" value .. This will solve the problem but it can affect performance negatively.

  • Another solution is could be calculate the coordinates (for example, you have a ball and wall. Ball will hit to wall. So calculate coordinates of wall and set hitting process according these cordinates )

Stopping an Android app from console

The clean way of stopping the app is:

adb shell am force-stop com.my.app.package

This way you don't have to figure out the process ID.

When 1 px border is added to div, Div size increases, Don't want to do that

You can create the element with border with the same color of your background, then when you want the border to show, just change its color.

List of Stored Procedures/Functions Mysql Command Line

My preference is for something that:

  1. Lists both functions and procedures,
  2. Lets me know which are which,
  3. Gives the procedures' names and types and nothing else,
  4. Filters results by the current database, not the current definer
  5. Sorts the result

Stitching together from other answers in this thread, I end up with

select 
  name, type 
from 
  mysql.proc 
where 
  db = database() 
order by 
  type, name;

... which ends you up with results that look like this:

mysql> select name, type from mysql.proc where db = database() order by type, name;
+------------------------------+-----------+
| name                         | type      |
+------------------------------+-----------+
| get_oldest_to_scan           | FUNCTION  |
| get_language_prevalence      | PROCEDURE |
| get_top_repos_by_user        | PROCEDURE |
| get_user_language_prevalence | PROCEDURE |
+------------------------------+-----------+
4 rows in set (0.30 sec)

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

Convert Promise to Observable

If you are using RxJS 6.0.0:

import { from } from 'rxjs';
const observable = from(promise);

What is the best way to trigger onchange event in react js

At least on text inputs, it appears that onChange is listening for input events:

var event = new Event('input', { bubbles: true });
element.dispatchEvent(event);

How do I create and access the global variables in Groovy?

def iamnotglobal=100 // This will not be accessible inside the function

iamglobal=200 // this is global and will be even available inside the 

def func()
{
    log.info "My value is 200. Here you see " + iamglobal
    iamglobal=400
    //log.info "if you uncomment me you will get error. Since iamnotglobal cant be printed here " + iamnotglobal
}
def func2()
{
   log.info "My value was changed inside func to 400 . Here it is = " + iamglobal
}
func()
func2()

here iamglobal variable is a global variable used by func and then again available to func2

if you declare variable with def it will be local, if you don't use def its global

How to add headers to OkHttp request interceptor?

Kotlin version:

fun okHttpClientFactory(): OkHttpClient {
    return OkHttpClient().newBuilder()
        .addInterceptor { chain ->
            chain.request().newBuilder()
                .addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .build()
                .let(chain::proceed)
        }
        .build()
}

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

To make sure it does not fail for string, date and timestamp columns:

import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
    """
    Counts number of nulls and nans in each column
    """
    df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()

    if len(df) == 0:
        print("There are no any missing values!")
        return None

    if sort:
        return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)

    return df

If you want to see the columns sorted based on the number of nans and nulls in descending:

count_missings(spark_df)

# | Col_A | 10 |
# | Col_C | 2  |
# | Col_B | 1  | 

If you don't want ordering and see them as a single row:

count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# |  10   |   1   |   2   |

Run bash command on jenkins pipeline

If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:

Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)

Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

Is it possible to set the stacking order of pseudo-elements below their parent element?

I know this is an old thread, but I feel the need to post the proper answer. The actual answer to this question is that you need to create a new stacking context on the parent of the element with the pseudo element (and you actually have to give it a z-index, not just a position).

Like this:

#parent {
    position: relative;
    z-index: 1;
}
#pseudo-parent {
    position: absolute;
    /* no z-index allowed */
}
#pseudo-parent:after {
    position: absolute;
    top:0;
    z-index: -1;
}

It has nothing to do with using :before or :after pseudo elements.

_x000D_
_x000D_
#parent { position: relative; z-index: 1; }_x000D_
#pseudo-parent { position: absolute; } /* no z-index required */_x000D_
#pseudo-parent:after { position: absolute; z-index: -1; }_x000D_
_x000D_
/* Example styling to illustrate */_x000D_
#pseudo-parent { background: #d1d1d1; }_x000D_
#pseudo-parent:after { margin-left: -3px; content: "M" }
_x000D_
<div id="parent">_x000D_
 <div id="pseudo-parent">_x000D_
   &nbsp;_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting input values from text box

Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.

How do I count the number of rows and columns in a file using bash?

Columns: awk '{print NF}' file | sort -nu | tail -n 1

Use head -n 1 for lowest column count, tail -n 1 for highest column count.

Rows: cat file | wc -l or wc -l < file for the UUOC crowd.

TypeScript: Interfaces vs Types


When to use type?


Generic Transformations

Use the type when you are transforming multiple types into a single generic type.

Example:

type Nullable<T> = T | null | undefined
type NonNull<T> = T extends (null | undefined) ? never : T

Type Aliasing

We can use the type for creating the aliases for long or complicated types that are hard to read as well as inconvenient to type again and again.

Example:

type Primitive = number | string | boolean | null | undefined

Creating an alias like this makes the code more concise and readable.


Type Capturing

Use the type to capture the type of an object when the type is unknown.

Example:

const orange = { color: "Orange", vitamin: "C"}
type Fruit = typeof orange
let apple: Fruit

Here, we get the unknown type of orange, call it a Fruit and then use the Fruit to create a new type-safe object apple.


When to use interface?


Polymorphism

An interface is a contract to implement a shape of the data. Use the interface to make it clear that it is intended to be implemented and used as a contract about how the object will be used.

Example:

interface Bird {
    size: number
    fly(): void
    sleep(): void
}

class Hummingbird implements Bird { ... }
class Bellbird implements Bird { ... }

Though you can use the type to achieve this, the Typescript is seen more as an object oriented language and the interface has a special place in object oriented languages. It's easier to read the code with interface when you are working in a team environment or contributing to the open source community. It's easy on the new programmers coming from the other object oriented languages too.

The official Typescript documentation also says:

... we recommend using an interface over a type alias when possible.

This also suggests that the type is more intended for creating type aliases than creating the types themselves.


Declaration Merging

You can use the declaration merging feature of the interface for adding new properties and methods to an already declared interface. This is useful for the ambient type declarations of third party libraries. When some declarations are missing for a third party library, you can declare the interface again with the same name and add new properties and methods.

Example:

We can extend the above Bird interface to include new declarations.

interface Bird {
    color: string
    eat(): void
}

That's it! It's easier to remember when to use what than getting lost in subtle differences between the two.

How to calculate the number of occurrence of a given character in each row of a column of strings?

You could just use string division

require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'

Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.

Why does PEP-8 specify a maximum line length of 79 characters?

Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

Node.js Logging

Winston is a pretty good logging library. You can write logs out to a file using it.

Code would look something like:

var winston = require('winston');

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
  ],
  exceptionHandlers: [
    new (winston.transports.Console)({ json: false, timestamp: true }),
    new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
  ],
  exitOnError: false
});

module.exports = logger;

You can then use this like:

var logger = require('./log');

logger.info('log to file');

Get fragment (value after hash '#') from a URL in php

Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.

A. setup your strings with a div id, so the name anchor goes where its supposed to and the javascript can change the text colors

<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>

B. Use Javascript to do the heavy work, on the server side, inserted in your PHP page, or wherever..

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

C. I am launching the java function automatically when the page is loaded.

<script>
$( document ).ready(function() {

D. get the anchor (#tesla) from the url received by the server

var myhash1 = $(location).attr('hash'); //myhash1 == #tesla

E. trim the hash sign off of it

myhash1 = myhash1.substr(1)  //myhash1 == tesla

F. I need to highlight the term and the description so i create a new var

var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1

G. Now I can manipulate the text color for the term and description

var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>

H. This works. client clicks link on client side (xyz.com#tesla) and goes right to the term. the term and the description are highlighted in blue by javascript for quick reading .. all other entries left in black..

How to import an existing project from GitHub into Android Studio

Steps:

  1. Download the Zip from the website or clone from Github Desktop. Don't use VCS in android studio.
  2. (Optional)Copy the folder extracted into your AndroidStudioProjects folder which must contain the hidden .git folder.
  3. Open Android Studio-> File-> Open-> Select android directory.
  4. If it's a Eclipse project then convert it to gradle(Provided by Android Studio). Otherwise, it's done.

Execute a command line binary with Node.js

@hexacyanide's answer is almost a complete one. On Windows command prince could be prince.exe, prince.cmd, prince.bat or just prince (I'm no aware of how gems are bundled, but npm bins come with a sh script and a batch script - npm and npm.cmd). If you want to write a portable script that would run on Unix and Windows, you have to spawn the right executable.

Here is a simple yet portable spawn function:

function spawn(cmd, args, opt) {
    var isWindows = /win/.test(process.platform);

    if ( isWindows ) {
        if ( !args ) args = [];
        args.unshift(cmd);
        args.unshift('/c');
        cmd = process.env.comspec;
    }

    return child_process.spawn(cmd, args, opt);
}

var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])

// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;

How to call a RESTful web service from Android?

Here is my Library That I have created for simple Webservice Calling,

You can use this by adding a one line gradle dependency -

compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'

Here is the demonstration of using.

https://github.com/vishalchhodwani1992/httpLibrary

Font is not available to the JVM with Jasper Reports

I solved this by choosing 'SansSerif' or 'Serif' only and not 'Arial' or 'Times New Roman'.

How can I fetch all items from a DynamoDB table without specifying the primary key?

This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet

        string tablename = "AnyTableName"; //table whose data you want to fetch

        var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(  

            new DynamoDBOperationConfig
            {
                OverrideTableName = tablename; 
            });

        foreach(string Id in IdList) // in case you are taking string from input
        {
            Guid objGuid = Guid.Parse(Id); //parsing string to guid
            BatchRead.AddKey(objGuid);
        }

        await BatchRead.ExecuteAsync();
        var result = BatchRead.Results;

// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch

How to find file accessed/created just few minutes ago

Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:

find . -cmin +<time>
find . -cmin -<time>
find . -cmin  <time>

In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:

find . -cmin -5

Powershell get ipv4 address into a variable

$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""

Also check which index of ipconfig has the IPv4 Address

How to display pandas DataFrame of floats using a format string for columns?

As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

which displays

enter image description here

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

constants.name = ['pie','eek']
C

enter image description here

However it appears to have some limitations:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

enter image description here

which looks ok but:

C

enter image description here

  • Formatting works only for values, not index entries:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    

enter image description here

How could others, on a local network, access my NodeJS app while it's running on my machine?

If you are using a router then:

  1. Replace server.listen(yourport, 'localhost'); with server.listen(yourport, 'your ipv4 address');

    in my machine it is

     server.listen(3000, '192.168.0.3');
    
  2. Make sure your port is forwarded to your ipv4 address.

  3. On Windows Firewall, tick all on Node.js:Server-side JavaScript.

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

How to know user has clicked "X" or the "Close" button?

It determines when to close the application if a form is closed (if your application is not attached to a specific form).

    private void MyForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (Application.OpenForms.Count == 0) Application.Exit();
    }

How to change the name of an iOS app?

For changing application name only (that will display along with app icon) in xcode 4 or later:

Click on your project file icon from Groups & Files panel, choose Target -> Build Settings -> Packaging -> Product Name. Click on the row, a pop-up will come, type your new app name here.

For changing Project name only (that will display along with project icon) in xcode 4 or later:

Click on your project file icon from Groups & Files panel, choose Project(above targets) from right pane, just see at the far right pane(it will be visible only if you have enabled "Hide or show utilities").Look for project name.Edit it to new name you want to give your project.

Delete your app from simulator/device, clean and run.Changes should reflect.

That's it

What is the meaning of @_ in Perl?

You can also use shift for individual variables in most cases:

$var1 = shift;

This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.

convert string array to string

string[] test = new string[2];

test[0] = "Hello ";
test[1] = "World!";

string.Join("", test);

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

numpy.dot(a, b, out=None)

Dot product of two arrays.

For N dimensions it is a sum product over the last axis of a and the second-to-last of b.

Documentation: numpy.dot.

Fastest way to extract frames using ffmpeg?

Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:

time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp

1m36.029s

This takes long because ffmpeg parses the entire video file to get the desired frames.

time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4   -frames:v 1 period_down_$i.bmp ; done

0m4.689s

This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek is the default , and make sure you add -ss before the input video -i option.

Note that it's better to use -filter:v -fps=fps=... instead of -r as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.

CSS I want a div to be on top of everything

Yes, in order for the z-index to work, you'll need to give the element a position: absolute or a position: relative property.

But... pay attention to parents!

You have to go up the nodes of the elements to check if at the level of the common parent the first descendants have a defined z-index.

All other descendants can never be in the foreground if at the base there is a lower definite z-index.

In this snippet example, div1-2-1 has a z-index of 1000 but is nevertheless under the div1-1-1 which has a z-index of 3.

This is because div1-1 has a z-index greater than div1-2.

enter image description here

_x000D_
_x000D_
.div {
  
}

#div1 {
  z-index: 1;
  position: absolute;
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

#div1-1 {
  z-index: 2;
  position: absolute;
  left: 230px;
  width: 200px;
  height: 200px;
  top: 31px;
  background-color: indianred;
}

#div1-1-1 {
  z-index: 3;
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: burlywood;
}

#div1-2 {
  z-index: 1;
  position: absolute;
  width: 200px;
  height: 200px;
  left: 80px;
  top: 5px;
  background-color: red;
}

#div1-2-1 {
  z-index: 1000;
  position: absolute;
  left: 70px;
  width: 120px;
  height: 100px;
  top: 10px;
  color: red;
  background-color: lightyellow;
}

.blink {
  animation: blinker 1s linear infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}

.rotate {
  writing-mode: vertical-rl;
  padding-left: 50px;
  font-weight: bold;
  font-size: 20px;
}
_x000D_
<div class="div" id="div1">div1</br>z-index: 1
  <div class="div" id="div1-1">div1-1</br>z-index: 2
    <div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
  </div>
  
  <div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
    <div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br>   parent)</span></div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to set UITextField height?

In Swift 3 use:

yourTextField.frame.size.height = 30

AngularJS UI Router - change url without reloading state

i did this but long ago in version: v0.2.10 of UI-router like something like this::

$stateProvider
  .state(
    'home', {
      url: '/home',
      views: {
        '': {
          templateUrl: Url.resolveTemplateUrl('shared/partial/main.html'),
          controller: 'mainCtrl'
        },
      }
    })
  .state('home.login', {
    url: '/login',
    templateUrl: Url.resolveTemplateUrl('authentication/partial/login.html'),
    controller: 'authenticationCtrl'
  })
  .state('home.logout', {
    url: '/logout/:state',
    controller: 'authenticationCtrl'
  })
  .state('home.reservationChart', {
    url: '/reservations/?vw',
    views: {
      '': {
        templateUrl: Url.resolveTemplateUrl('reservationChart/partial/reservationChartContainer.html'),
        controller: 'reservationChartCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/viewVoucherContainer.html'),
        controller: 'viewVoucherCtrl',
        reloadOnSearch: false
      },
      '[email protected]': {
        templateUrl: Url.resolveTemplateUrl('voucher/partial/voucherContainer.html'),
        controller: 'voucherCtrl',
        reloadOnSearch: false
      }
    },
    reloadOnSearch: false
  })

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

How to set JAVA_HOME for multiple Tomcat instances?

Also, note that there shouldn't be any space after =:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27

grunt: command not found when running from terminal

I have been hunting around trying to solve this one for a while and none of the suggested updates to bash seemed to be working. What I discovered was that some point my npm root was modified such that it was pointing to a Users/USER_NAME/.node/node_modules while the actual installation of npm was living at /usr/local/lib/node_modules. You can check this by running npm root and npm root -g (for the global installation). To correct the path you can call npm config set prefix /usr/local.

How to get a jqGrid cell value when editing

Hi, I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.

My solution like this:

var userIDContent = $("#grid").getCell(id,"userID");  // Use getCell to get the content
//alert("userID:" +userID);  // you can see the content here.

//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val();  // var userID = $(userIDContent).attr('attrName');

Iterate over the lines of a string

I suppose you could roll your own:

def parse(string):
    retval = ''
    for char in string:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

I'm not sure how efficient this implementation is, but that will only iterate over your string once.

Mmm, generators.

Edit:

Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.

How to convert date to timestamp in PHP?

If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:

function UTCToTimestamp($utc_datetime_str)
{
    preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
    $datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];

    return strtotime($datetime_str);
}

$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);

Eclipse - Failed to create the java virtual machine

It works for me after removing -XX:+UseParallelOldGC option from file.

Cannot install signed apk to device manually, got error "App not installed"

I am using Android 10 in MiA2. The mistake I was making is that I tried to install the app via ES Explorer. I tried Settings -> Apps & Notifications -> Advanced -> Special App Access -> Install Unknown Apps -> ES File Manage -> Allow from this source. Even then the app won't install.

Then I tired to install the app using the default File Manager and it installed easily.

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

JavaScript: set dropdown selected item based on option text

This works in latest Chrome, FireFox and Edge, but not IE11:

document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';

And if you want to ignore spaces around the title:

document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'

Skip a submodule during a Maven build

It's possible to decide which reactor projects to build by specifying the -pl command line argument:

$ mvn --help
[...]
 -pl,--projects <arg>                   Build specified reactor projects
                                        instead of all projects
[...]

It accepts a comma separated list of parameters in one of the following forms:

  • relative path of the folder containing the POM
  • [groupId]:artifactId

Thus, given the following structure:

project-root [com.mycorp:parent]
  |
  + --- server [com.mycorp:server]
  |       |
  |       + --- orm [com.mycorp.server:orm]
  |
  + --- client [com.mycorp:client]

You can specify the following command line:

mvn -pl .,server,:client,com.mycorp.server:orm clean install

to build everything. Remove elements in the list to build only the modules you please.


EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el flag that excludes projects from the reactor, similarly to what -pl does:

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

CSS3 Continuous Rotate Animation (Just like a loading sundial)

You also might notice a little lag because 0deg and 360deg are the same spot, so it is going from spot 1 in a circle back to spot 1. It is really insignificant, but to fix it, all you have to do is change 360deg to 359deg

my jsfiddle illustrates your animation:

#myImg {
    -webkit-animation: rotation 2s infinite linear;
}

@-webkit-keyframes rotation {
    from {-webkit-transform: rotate(0deg);}
    to   {-webkit-transform: rotate(359deg);}
}

Also what might be more resemblant of the apple loading icon would be an animation that transitions the opacity/color of the stripes of gray instead of rotating the icon.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Python: Remove division decimal

You could probably do like below

# p and q are the numbers to be divided
if p//q==p/q:
    print(p//q)
else:
    print(p/q)

JavaScript property access: dot notation vs. brackets?

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["?"] (more examples).

Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

Fixed footer in Bootstrap

Add this:

<div class="footer fixed-bottom">

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

How to test if JSON object is empty in Java

if you want to check for the json empty case, we can directly use below code

String jsonString = {};
JSONObject jsonObject = new JSONObject(jsonString);
if(jsonObject.isEmpty()){
 System.out.println("json is empty");
} else{
 System.out.println("json is not empty");
}

this may help you.

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

SQL Server 2012 can't start because of a login failure

This happened to me. A policy on the domain was taking away the SQL Server user account's "Log on as a service" rights. You can work around this using JLo's solution, but does not address the group policy problem specifically and it will return next time the group policies are refreshed on the machine.

The specific policy causing the issue for me was: Under, Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignments: Log on as a service

You can see which policies are being applied to your machine by running the command "rsop" from the command line. Follow the path to the policy listed above and you will see its current value as well as which GPO set the value.

Can't get Gulp to run: cannot find module 'gulp-util'

Any answer didn't help in my case. What eventually helped was removing bower and gulp (I use both of them in my project):

npm remove -g bower
npm remove -g gulp

After that I installed them again:

npm install -g bower
npm install -g gulp

Now it works just fine.

How can I make a checkbox readonly? not disabled?

There is no property to make the checkbox readonly. But you can try this trick.

<input type="checkbox" onclick="return false" />

DEMO

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

How to disable an Android button?

In Java, once you have the reference of the button:

Button button = (Button) findviewById(R.id.button);

To enable/disable the button, you can use either:

button.setEnabled(false);
button.setEnabled(true);

Or:

button.setClickable(false);
button.setClickable(true);

Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method. Otherwise, from XML, you can directly use:

android:clickable = "false"

So:

<Button
        android:id="@+id/button"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/button_text"
        android:clickable = "false" />

Disable scrolling in webview?

Here is my code for disabling all scrolling in webview:

  // disable scroll on touch
  webview.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return (event.getAction() == MotionEvent.ACTION_MOVE);
    }
  });

To only hide the scrollbars, but not disable scrolling:

WebView.setVerticalScrollBarEnabled(false);
WebView.setHorizontalScrollBarEnabled(false);

or you can try using single column layout but this only works with simple pages and it disables horizontal scrolling:

   //Only disabled the horizontal scrolling:
   webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

You can also try to wrap your webview with vertically scrolling scrollview and disable all scrolling on the webview:

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"    >
  <WebView
    android:id="@+id/mywebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none" />
</ScrollView>

And set

webview.setScrollContainer(false);

Don't forget to add the webview.setOnTouchListener(...) code above to disable all scrolling in the webview. The vertical ScrollView will allow for scrolling of the WebView's content.

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

Warning: implode() [function.implode]: Invalid arguments passed

You are getting the error because $ret is not an array.

To get rid of the error, at the start of your function, define it with this line: $ret = array();

It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

switch case statement error: case expressions must be constant expression

In a regular Android project, constants in the resource R class are declared like this:

public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:

public static int main=0x7f030004;

In other words, the constants are not final in a library project. Therefore your code would no longer compile.

The solution for this is simple: Convert the switch statement into an if-else statement.

public void onClick(View src)
{
    int id = src.getId();
    if (id == R.id.playbtn){
        checkwificonnection();
    } else if (id == R.id.stopbtn){
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
    } else if (id == R.id.btnmenu){
        openOptionsMenu();
    }
}

http://tools.android.com/tips/non-constant-fields

You can quickly convert a switch statement to an if-else statement using the following:

In Eclipse
Move your cursor to the switch keyword and press Ctrl + 1 then select

Convert 'switch' to 'if-else'.

In Android Studio
Move your cursor to the switch keyword and press Alt + Enter then select

Replace 'switch' with 'if'.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

jQuery delete confirmation box

I used this:

<a href="url/to/delete.asp" onclick="return confirm(' you want to delete?');">Delete</a>

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Yes, on Arrays.asList, returning a fixed-size list.

Other than using a linked list, simply use addAll method list.

Example:

String idList = "123,222,333,444";

List<String> parentRecepeIdList = new ArrayList<String>();

parentRecepeIdList.addAll(Arrays.asList(idList.split(","))); 

parentRecepeIdList.add("555");

How to increment a number by 2 in a PHP For Loop

Another simple solution with +=:

$y = 1;

for ($x = $y; $x <= 15; $y++) {
  printf("The number of first paragraph is: $y <br>");
  printf("The number of second paragraph is: $x+=2 <br>");
} 

Find row where values for column is maximal in a pandas DataFrame

df.iloc[df['columnX'].argmax()]

argmax() would provide the index corresponding to the max value for the columnX. iloc can be used to get the row of the DataFrame df for this index.

How to tell Jackson to ignore a field during serialization if its value is null?

In Jackson 2.x, use:

@JsonInclude(JsonInclude.Include.NON_NULL)

How do you print in a Go test using the "testing" package?

For testing sometimes I do

fmt.Fprintln(os.Stdout, "hello")

Also, you can print to:

fmt.Fprintln(os.Stderr, "hello)

List all devices, partitions and volumes in Powershell

To get all of the file system drives, you can use the following command:

gdr -PSProvider 'FileSystem'

gdr is an alias for Get-PSDrive, which includes all of the "virtual drives" for the registry, etc.

Equivalent of Math.Min & Math.Max for Dates?

public static class DateTool
{
    public static DateTime Min(DateTime x, DateTime y)
    {
        return (x.ToUniversalTime() < y.ToUniversalTime()) ? x : y;
    }
    public static DateTime Max(DateTime x, DateTime y)
    {
        return (x.ToUniversalTime() > y.ToUniversalTime()) ? x : y;
    }
}

This allows the dates to have different 'kinds' and returns the instance that was passed in (not returning a new DateTime constructed from Ticks or Milliseconds).

[TestMethod()]
    public void MinTest2()
    {
        DateTime x = new DateTime(2001, 1, 1, 1, 1, 2, DateTimeKind.Utc);
        DateTime y = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local);

        //Presumes Local TimeZone adjustment to UTC > 0
        DateTime actual = DateTool.Min(x, y);
        Assert.AreEqual(x, actual);
    }

Note that this test would fail East of Greenwich...

How to get Python requests to trust a self signed SSL certificate?

With the verify parameter you can provide a custom certificate authority bundle

requests.get(url, verify=path_to_bundle_file)

From the docs:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

disable horizontal scroll on mobile web

For me, the viewport meta tag actually caused a horizontal scroll issue on the Blackberry.

I removed content="initial-scale=1.0; maximum-scale=1.0; from the viewport tag and it fixed the issue. Below is my current viewport tag:

<meta name="viewport" content="user-scalable=0;"/>

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

Jenkins could not run git

Also you can set Git location in Jenkins server/node configuration:

goto Configure, under section Node Properties mark checkbox Tools Location and set yours path to Git.

enter image description here

using awk with column value conditions

please try this

echo $VAR | grep ClNonZ | awk '{print $3}';

or

echo cat filename | grep ClNonZ | awk '{print $3}';

Use of String.Format in JavaScript?

//Add "format" method to the string class
//supports:  "Welcome {0}. You are the first person named {0}".format("David");
//       and "First Name:{} Last name:{}".format("David","Wazy");
//       and "Value:{} size:{0} shape:{1} weight:{}".format(value, size, shape, weight)
String.prototype.format = function () {
    var content = this;
    for (var i = 0; i < arguments.length; i++) {
        var target = '{' + i + '}';
        content=content.split(target).join(String(arguments[i]))
        content = content.replace("{}", String(arguments[i]));
    }
    return content;
}
alert("I {} this is what {2} want and {} works for {2}!".format("hope","it","you"))

You can mix and match using positional and "named" replacement locations using this function.

Can an Android NFC phone act as an NFC tag?

Yes, take a look at NDEF Push in NFCManager - with Android 4 you can now even create the NDEFMessage to push to the active device at the time the interaction takes place.

How to resize Image in Android?

//photo is bitmap image

Bitmap btm00 = Utils.getResizedBitmap(photo, 200, 200);

 setimage.setImageBitmap(btm00);

  And in Utils class :

public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);
    // RECREATE THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
            matrix, false);
    return resizedBitmap;
}

Font scaling based on width of container

You may be you looking for something like this:

http://jsfiddle.net/sijav/dGsC9/4/
http://fiddle.jshell.net/sijav/dGsC9/4/show/

I have used flowtype, and it's working great (however it's JavaScript and not a pure CSS solution):

$('body').flowtype({
    minFont: 10,
    maxFont: 40,
    minimum: 500,
    maximum: 1200,
    fontRatio: 70
});

Formatting floats without trailing zeros

You can use max() like this:

print(max(int(x), x))

How to hide action bar before activity is created, and then show it again?

Using this simple code in your .class file to hide action bar

getSupportActionBar().hide();

Can you do greater than comparison on a date in a Rails 3 search?

Note.
  where(:user_id => current_user.id, :notetype => p[:note_type]).
  where("date > ?", p[:date]).
  order('date ASC, created_at ASC')

or you can also convert everything into the SQL notation

Note.
  where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
  order('date ASC, created_at ASC')

"insufficient memory for the Java Runtime Environment " message in eclipse

If you are using Virtual Machine (VM), allocate more RAM to your VM and your problem will be solved.

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Use modern document.execCommand("copy") and jQuery. See this stackoverflow answer

var ClipboardHelper = { // as Object

copyElement: function ($element)
{
   this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
    var $tempInput =  $("<textarea>");
    $("body").append($tempInput);
    $tempInput.val(text).select();
    document.execCommand("copy");
    $tempInput.remove();
}};

How to Call:

 ClipboardHelper.copyText('Hello\nWorld');
 ClipboardHelper.copyElement($('body h1').first());

_x000D_
_x000D_
// JQUERY DOCUMENT_x000D_
;(function ( $, window, document, undefined ) {_x000D_
  _x000D_
  var ClipboardHelper = {_x000D_
_x000D_
    copyElement: function ($element)_x000D_
    {_x000D_
       this.copyText($element.text())_x000D_
    },_x000D_
    copyText:function(text) // Linebreaks with \n_x000D_
    {_x000D_
        var $tempInput =  $("<textarea>");_x000D_
        $("body").append($tempInput);_x000D_
      _x000D_
        //todo prepare Text: remove double whitespaces, trim_x000D_
        _x000D_
        $tempInput.val(text).select();_x000D_
        document.execCommand("copy");_x000D_
        $tempInput.remove();_x000D_
    }_x000D_
};_x000D_
_x000D_
    $(document).ready(function()_x000D_
    {_x000D_
         var $body=$('body');_x000D_
         _x000D_
        $body.on('click', '*[data-copy-text-to-clipboard]', function(event) _x000D_
        {_x000D_
            var $btn=$(this);_x000D_
            var text=$btn.attr('data-copy-text-to-clipboard');_x000D_
            ClipboardHelper.copyText(text);_x000D_
        });_x000D_
      _x000D_
        $body.on('click', '.js-copy-element-to-clipboard', function(event) _x000D_
        {_x000D_
            ClipboardHelper.copyElement($(this));_x000D_
        });_x000D_
_x000D_
    });_x000D_
_x000D_
_x000D_
})( jQuery, window, document );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<span data-copy-text-to-clipboard=_x000D_
"Hello_x000D_
 World">_x000D_
  Copy Text_x000D_
</span>_x000D_
<br><br>_x000D_
<span class="js-copy-element-to-clipboard">_x000D_
Hello_x000D_
World _x000D_
Element_x000D_
</span>
_x000D_
_x000D_
_x000D_

Python: Generate random number between x and y which is a multiple of 5

Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.

import random
for x in range(20):
  print random.randint(1,11)*5,
print

produces e.g.

5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

Creating a script for a Telnet session?

Write the telnet session inside a BAT Dos file and execute.

?: ?? Operators Instead Of IF|ELSE

For [1], you can't: these operators are made to return a value, not perform operations.

The expression

a ? b : c

evaluates to b if a is true and evaluates to c if a is false.

The expression

b ?? c

evaluates to b if b is not null and evaluates to c if b is null.

If you write

return a ? b : c;

or

return b ?? c;

they will always return something.

For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

AngularJS 1.2 $injector:modulerr

Besides below answer, if you have this error in console ([$injector:nomod], MINERR_ASSET:22), but everything seems to work fine, make sure that you don't have duplicate includes in your index.html.

Because this error can also be raised if you have duplicate includes of the files, that use this module, and are included before the file with actual module declaration.

Create MSI or setup project with Visual Studio 2012

There is some progress for Visual studio 2013 developers :-D woot woot! See blog post Visual Studio Installer Projects Extension.

Link and information were retrieved from Brian Harry's blog post Creating installers with Visual Studio.

How to connect to a docker container from outside the host (same network) [Windows]

This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;

Server is already running in Rails

You can get rid of the process by killing it:

kill -9 $(lsof -i tcp:3000 -t)

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

iterrows pandas get next rows value

There is a pairwise() function example in the itertools document:

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])

for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
    print i1, i2, row1["value"], row2["value"]

Here is the output:

0 1 AA BB
1 2 BB CC

But, I think iter rows in a DataFrame is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.

Age from birthdate in python

from datetime import date

days_in_year = 365.2425    
age = int((date.today() - birth_date).days / days_in_year)

In Python 3, you could perform division on datetime.timedelta:

from datetime import date, timedelta

age = (date.today() - birth_date) // timedelta(days=365.2425)

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Spring Could not Resolve placeholder

enter image description hereI know It is an old message , but i want to add my case.

If you use more than one profile(dev,test,prod...), check your execute profile.

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

Change background color of selected item on a ListView

nameofList.getChildAt(position).setBackgroundColor(RED);

worked for me

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I had the same issue with WebSphere 6.1. As Ceki pointed out, there were tons of jars that WebSphere was using and one of them was pointing to an older version of slf4j.

The No-Op fallback happens only with slf4j -1.6+ so anything older than that will throw an exception and halts your deployment.

There is a documentation in SLf4J site which resolves this. I followed that and added slf4j-simple-1.6.1.jar to my application along with slf4j-api-1.6.1.jar which I already had.

If you use Maven, add the following dependencies, with ${slf4j.version} being the latest version of slf4j

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>${slf4j.version}</version>
</dependency>

This solved my issue. Hope it helps others who have this issue.

How to specify the actual x axis values to plot as x axis ticks in R

Hope this coding will helps you :)

plot(x,y,xaxt = 'n')

axis(side=1,at=c(1,20,30,50),labels=c("1975","1980","1985","1990"))

Reflection: How to Invoke Method with parameters

You have a bug right there

result = methodInfo.Invoke(methodInfo, parametersArray);

it should be

result = methodInfo.Invoke(classInstance, parametersArray);

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.

Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.

HTML5 Dynamically create Canvas

It happens because you call it before DOM has loaded. Firstly, create the element and add atrributes to it, then after DOM has loaded call it. In your case it should look like that:

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
window.onload = function() {
    document.getElementById("CursorLayer");
}

How to deal with SQL column names that look like SQL keywords?

Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.

All these answers work in the various databases but apparently a lot don't support the ANSI solution.

Visual Studio: ContextSwitchDeadlock

I was getting this error and switched the queries to async (await (...).ToListAsync()). All good now.

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

Access to Image from origin 'null' has been blocked by CORS policy

For local development you could serve the files with a simple web server.

With Python installed, go into the folder where your project is served, like cd my-project/. And then use python -m SimpleHTTPServer which would make index.html and it's JavaScript files available at localhost:8000.

What is the difference between an int and an Integer in Java and C#?

int is used to declare primitive variable

e.g. int i=10;

Integer is used to create reference variable of class Integer

Integer a = new Integer();

JavaScript isset() equivalent

window.isset = function(v_var) {
    if(typeof(v_var) == 'number'){ if(isNaN(v_var)){ return false; }}
    if(typeof(v_var) == 'undefined' || v_var === null){ return false;   } else { return true; }
};

plus Tests:

https://gist.github.com/daylik/24acc318b6abdcdd63b46607513ae073

how to get all markers on google-maps-v3

Google Maps API v3:

I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".

var map = new GMaps({
    div: '#map',
    lat: 40.730610,
    lng: -73.935242,
});

var myMarkers = map.markers;

You can loop over it and access all Marker methods listed at Google Maps Reference.

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

How to import a module given its name as string?

For example, my module names are like jan_module/feb_module/mar_module.

month = 'feb'
exec 'from %s_module import *'%(month)

ConfigurationManager.AppSettings - How to modify and save?

as the base question is about win forms here is the solution : ( I just changed the code by user1032413 to rflect windowsForms settings ) if it's a new key :

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

if the key already exists :

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);

How to change UINavigationBar background color from the AppDelegate

To change the background color and not the tint the following piece of code will work:

[self.navigationController.navigationBar setBarTintColor:[UIColor greenColor]];
[self.navigationController.navigationBar setTranslucent:NO];

Wait until flag=true

I tried to used @Kiran approach like follow:

checkFlag: function() {
  var currentObject = this; 
  if(flag == false) {
      setTimeout(currentObject.checkFlag, 100); 
   } else {
     /* do something*/
   }
}

(framework that I am using force me to define functions this way). But without success because when execution come inside checkFlag function second time, this is not my object it is Window. So, I finished with code below

checkFlag: function() {
    var worker = setInterval (function(){
         if(flag == true){             
             /* do something*/
              clearInterval (worker);
         } 
    },100);
 }

How do we update URL or query strings using javascript/jQuery without reloading the page?

Prefix URL changes with a hashtag to avoid a redirect.

This redirects

location.href += '&test='true';

This doesn't redirect

location.href += '#&test='true';

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I had same problem regarding that i.e A network-related or instance-specific error occurred while establishing a connection to SQL Server.

I was using SQL Server 2005 (.\sqlexpress)` and worked fine but suddenly services stopped and gave me error.

I solved it like this,

Start -> Search Box - > Sql Configuration Manager -> SQL Server 2005 Services >and just Change Your SQL Server (SQLEXPRESS) State to Running by right clicking that service Sate.

document.body.appendChild(i)

In 2019 you can use querySelector for that.

It's supported by most browsers (https://caniuse.com/#search=querySelector)

document.querySelector('body').appendChild(i);

Python Serial: How to use the read or readline function to read more than 1 character at a time

I see a couple of issues.

First:

ser.read() is only going to return 1 byte at a time.

If you specify a count

ser.read(5)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

That will continue to read characters until an EOL is received.

Second:

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

Get rid of the

for line in ser.read():

and just say:

line = ser.readline()

jQuery loop over JSON result from AJAX Success?

$each will work.. Another option is jQuery Ajax Callback for array result

function displayResultForLog(result) {
  if (result.hasOwnProperty("d")) {
    result = result.d
  }

  if (result !== undefined && result != null) {
    if (result.hasOwnProperty('length')) {
      if (result.length >= 1) {
        for (i = 0; i < result.length; i++) {
          var sentDate = result[i];
        }
      } else {
        $(requiredTable).append('Length is 0');
      }
    } else {
      $(requiredTable).append('Length is not available.');
    }

  } else {
    $(requiredTable).append('Result is null.');
  }
}

Add content to a new open window

When You want to open new tab/window (depends on Your browser configuration defaults):

output = 'Hello, World!';
window.open().document.write(output);

When output is an Object and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)

output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));

Update

Google Chrome (60.0.3112.90) block this code:

Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9

When You want to append some data to existing page

output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;

output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;

Speed up rsync with Simultaneous/Concurrent File Transfers?

Updated answer (Jan 2020)

xargs is now the recommended tool to achieve parallel execution. It's pre-installed almost everywhere. For running multiple rsync tasks the command would be:

ls /srv/mail | xargs -n1 -P4 -I% rsync -Pa % myserver.com:/srv/mail/

This will list all folders in /srv/mail, pipe them to xargs, which will read them one-by-one and and run 4 rsync processes at a time. The % char replaces the input argument for each command call.

Original answer using parallel:

ls /srv/mail | parallel -v -j8 rsync -raz --progress {} myserver.com:/srv/mail/{}

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

How to use placeholder as default value in select2 framework

I tried all this and in the end, simply using a title="text here" worked for my system. Note there is no blank option

<select name="Restrictions" class="selectpicker show-tick form-control" 
        data-live-search="true" multiple="multiple" title="Choose Multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

Pass in an enum as a method parameter

If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

How do I "un-revert" a reverted Git commit?

Or you could git checkout -b <new-branch> and git cherry-pick <commit> the before to the and git rebase to drop revert commit. send pull request like before.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Better way to revert to a previous SVN revision of a file?

svn merge -r 854:853 l3toks.dtx

or

svn merge -c -854 l3toks.dtx

The two commands are equivalent.

onKeyPress Vs. onKeyUp and onKeyDown

Most of the answers here are focused more on theory than practical matters and there's some big differences between keyup and keypress as it pertains to input field values, at least in Firefox (tested in 43).

If the user types 1 into an empty input element:

  1. The value of the input element will be an empty string (old value) inside the keypress handler

  2. The value of the input element will be 1 (new value) inside the keyup handler.

This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.

Scenario:

  1. The user types 12345 into an input element.
  2. The user selects the text 12345.
  3. The user types the letter A.

When the keypress event fires after entering the letter A, the text box now contains only the letter A.

But:

  1. Field.val() is 12345.
  2. $Field.val().length is 5
  3. The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).

So it seems that the browser (Firefox 43) erases the user's selection, then fires the keypress event, then updates the fields contents, then fires keyup.

How to pass boolean values to a PowerShell script from a command prompt

It appears that powershell.exe does not fully evaluate script arguments when the -File parameter is used. In particular, the $false argument is being treated as a string value, in a similar way to the example below:

PS> function f( [bool]$b ) { $b }; f -b '$false'
f : Cannot process argument transformation on parameter 'b'. Cannot convert value 
"System.String" to type "System.Boolean", parameters of this type only accept 
booleans or numbers, use $true, $false, 1 or 0 instead.
At line:1 char:36
+ function f( [bool]$b ) { $b }; f -b <<<<  '$false'
    + CategoryInfo          : InvalidData: (:) [f], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,f

Instead of using -File you could try -Command, which will evaluate the call as script:

CMD> powershell.exe -NoProfile -Command .\RunScript.ps1 -Turn 1 -Unify $false
Turn: 1
Unify: False

As David suggests, using a switch argument would also be more idiomatic, simplifying the call by removing the need to pass a boolean value explicitly:

CMD> powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify
Turn: 1
Unify: True

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

C++ template constructor

Some points:

  • If you declare any constructor(including a templated one), the compiler will refrain from declaring a default constructor.
  • Unless you declare a copy-constructor (for class X one that takes X or X& or X const &) the compiler will generate the default copy-constructor.
  • If you provide a template constructor for class X which takes T const & or T or T& then the compiler will nevertheless generate a default non-templated copy-constructor, even though you may think that it shouldn't because when T = X the declaration matches the copy-constructor declaration.
  • In the latter case you may want to provide a non-templated copy-constructor along with the templated one. They will not conflict. When X is passed the nontemplated will be called. Otherwise the templated

HTH

How to create an empty R vector to add new items

To create an empty vector use:

vec <- c();

Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.

Once the vector has been created you can add elements to it as follows:

For example, to add the numeric value 1:

vec <- c(vec, 1);

or, to add a string value "a"

vec <- c(vec, "a");

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

What is a good practice to check if an environmental variable exists or not?

In case you want to check if multiple env variables are not set, you can do the following:

import os

MANDATORY_ENV_VARS = ["FOO", "BAR"]

for var in MANDATORY_ENV_VARS:
    if var not in os.environ:
        raise EnvironmentError("Failed because {} is not set.".format(var))

Is there a simple way to convert C++ enum to string?

What I tend to do is create a C array with the names in the same order and position as the enum values.

eg.

enum colours { red, green, blue };
const char *colour_names[] = { "red", "green", "blue" };

then you can use the array in places where you want a human-readable value, eg

colours mycolour = red;
cout << "the colour is" << colour_names[mycolour];

You could experiment a little with the stringizing operator (see # in your preprocessor reference) that will do what you want, in some circumstances- eg:

#define printword(XX) cout << #XX;
printword(red);

will print "red" to stdout. Unfortunately it won't work for a variable (as you'll get the variable name printed out)

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

Can I use Class.newInstance() with constructor arguments?

Assuming you have the following constructor

class MyClass {
    public MyClass(Long l, String s, int i) {

    }
}

You will need to show you intend to use this constructor like so:

Class classToLoad = MyClass.class;

Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int

Long l = new Long(88);
String s = "text";
int i = 5;

classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))