Programs & Examples On #Bcpl

BCPL (Basic Combined Programming Language) is a procedural, imperative, and structured computer programming language designed by Martin Richards of the University of Cambridge in 1966.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

Create Excel files from C# without office

Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.

C#: Assign same value to multiple variables in single statement

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;

    Console.ReadLine();
}

public class AccessorTest
{
    public AccessorTest(int value = default(int))
    {
        _Value = value;
    }

    private int _Value;

    public int Value
    {
        get
        {
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
        }
        set
        {
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;
        }
    }
}

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

Get height and width of a layout programmatically

try something like this code from this link

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
 viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
  viewWidth = view.getWidth();
  viewHeight = view.getHeight();
}
 });
}

hope this helps.

How to change default Anaconda python environment

The correct answer (as of Dec 2018) is... you can't. Upgrading conda install python=3.6 may work, but it might not if you have packages that are necessary, but cannot be uninstalled.

Anaconda uses a default environment named base and you cannot create a new (e.g. python 3.6) environment with the same name. This is intentional. If you want your base Anaconda to be python 3.6, the right way to do this is to install Anaconda for python 3.6. As a package manager, the goal of Anaconda is to make different environments encapsulated, hence why you must source activate into them and why you can't just quietly switch the base package at will as this could lead to many issues on production systems.

Align text in JLabel to the right

This can be done in two ways.

JLabel Horizontal Alignment

You can use the JLabel constructor:

JLabel(String text, int horizontalAlignment) 

To align to the right:

JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);

JLabel also has setHorizontalAlignment:

label.setHorizontalAlignment(SwingConstants.RIGHT);

This assumes the component takes up the whole width in the container.

Using Layout

A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:

    Box box = Box.createVerticalBox();
    JLabel label1 = new JLabel("test1, the beginning");
    label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label1);

    JLabel label2 = new JLabel("test2, some more");
    label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label2);

    JLabel label3 = new JLabel("test3");
    label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label3);


    add(box);

Disable all dialog boxes in Excel while running VB script?

In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:

DoCmd.SetWarnings False

After running all the updates, the last step in my VBA script is:

DoCmd.SetWarnings True

Hope this helps.

Where does Chrome store extensions?

For older versions of windows (2k, 2k3, xp)

"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions" 

How to convert strings into integers in Python?

See this function

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

Then

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

You can also check

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Sometimes type setting:

max_allowed_packet = 16M

in my.ini is not working.

Try to determine the my.ini as follows:

set-variable = max_allowed_packet = 32M

or

set-variable = max_allowed_packet = 1000000000

Then restart the server:

/etc/init.d/mysql restart

How do I create an abstract base class in JavaScript?

JavaScript Classes and Inheritance (ES6)

According to ES6, you can use JavaScript classes and inheritance to accomplish what you need.

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

First of all, we define our abstract class. This class can't be instantiated, but can be extended. We can also define functions that must be implemented in all classes that extends this one.

/**
 * Abstract Class Animal.
 *
 * @class Animal
 */
class Animal {

  constructor() {
    if (this.constructor == Animal) {
      throw new Error("Abstract classes can't be instantiated.");
    }
  }

  say() {
    throw new Error("Method 'say()' must be implemented.");
  }

  eat() {
    console.log("eating");
  }
}

After that, we can create our concrete Classes. These classes will inherit all functions and behaviour from abstract class.

/**
 * Dog.
 *
 * @class Dog
 * @extends {Animal}
 */
class Dog extends Animal {
  say() {
    console.log("bark");
  }
}

/**
 * Cat.
 *
 * @class Cat
 * @extends {Animal}
 */
class Cat extends Animal {
  say() {
    console.log("meow");
  }
}

/**
 * Horse.
 *
 * @class Horse
 * @extends {Animal}
 */
class Horse extends Animal {}

And the results...

// RESULTS

new Dog().eat(); // eating
new Cat().eat(); // eating
new Horse().eat(); // eating

new Dog().say(); // bark
new Cat().say(); // meow
new Horse().say(); // Error: Method say() must be implemented.

new Animal(); // Error: Abstract classes can't be instantiated.

Set value for particular cell in pandas DataFrame using index

set_value() is deprecated.

Starting from the release 0.23.4, Pandas "announces the future"...

>>> df
                   Cars  Prices (U$)
0               Audi TT        120.0
1 Lamborghini Aventador        245.0
2      Chevrolet Malibu        190.0
>>> df.set_value(2, 'Prices (U$)', 240.0)
__main__:1: FutureWarning: set_value is deprecated and will be removed in a future release.
Please use .at[] or .iat[] accessors instead

                   Cars  Prices (U$)
0               Audi TT        120.0
1 Lamborghini Aventador        245.0
2      Chevrolet Malibu        240.0

Considering this advice, here's a demonstration of how to use them:

  • by row/column integer positions

>>> df.iat[1, 1] = 260.0
>>> df
                   Cars  Prices (U$)
0               Audi TT        120.0
1 Lamborghini Aventador        260.0
2      Chevrolet Malibu        240.0
  • by row/column labels

>>> df.at[2, "Cars"] = "Chevrolet Corvette"
>>> df
                  Cars  Prices (U$)
0               Audi TT        120.0
1 Lamborghini Aventador        260.0
2    Chevrolet Corvette        240.0

References:

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to install Java SDK on CentOS?

If you want the Oracle JDK and are willing not to use yum/rpm, see this answer here:

Downloading Java JDK on Linux via wget is shown license page instead

As per that post, you can automate the download of the tarball using curl and specifying a cookie header.

Then you can put the tarball contents in the right place and add java to your PATH, for example:

curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz > jdk.tar.gz

tar xzvf jdk.tar.gz
sudo mkdir /usr/local/java
sudo mv jdk1.8.0_45 /usr/local/java/
sudo ln -s /usr/local/java/jdk1.8.0_45 /usr/local/java/jdk

sudo vi /etc/profile.d/java.sh
export PATH="$PATH:/usr/local/java/jdk/bin"
export JAVA_HOME=/usr/local/java/jdk

source /etc/profile.d/java.sh

How do I call ::CreateProcess in c++ to launch a Windows executable?

Something like this:

STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

Different ways of adding to Dictionary

Dictionary.Add(key, value) and Dictionary[key] = value have different purposes:

  • Use the Add method to add new key/value pair, existing keys will not be replaced (an ArgumentException is thrown).
  • Use the indexer if you don't care whether the key already exists in the dictionary, in other words: add the key/value pair if the the key is not in the dictionary or replace the value for the specified key if the key is already in the dictionary.

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

Why does modulus division (%) only work with integers?

The % operator does not work in C++, when you are trying to find the remainder of two numbers which are both of the type Float or Double.

Hence you could try using the fmod function from math.h / cmath.h or you could use these lines of code to avoid using that header file:

float sin(float x) {
 float temp;
 temp = (x + M_PI) / ((2 *M_PI) - M_PI);
 return limited_sin((x + M_PI) - ((2 *M_PI) - M_PI) * temp ));

}

An invalid form control with name='' is not focusable

None of the previous answers worked for me, and I don't have any hidden fields with the required attribute.

In my case, the problem was caused by having a <form> and then a <fieldset> as its first child, which holds the <input> with the required attribute. Removing the <fieldset> solved the problem. Or you can wrap your form with it; it is allowed by HTML5.

I'm on Windows 7 x64, Chrome version 43.0.2357.130 m.

Close Bootstrap Modal

this worked for me:

<span class="button" data-dismiss="modal" aria-label="Close">cancel</span>

use this link modal close

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Parse time of format hh:mm:ss

A bit verbose, but it's the standard way of parsing and formatting dates in Java:

DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
  Date dt = formatter.parse("08:19:12");
  Calendar cal = Calendar.getInstance();
  cal.setTime(dt);
  int hour = cal.get(Calendar.HOUR);
  int minute = cal.get(Calendar.MINUTE);
  int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
  // This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
  // Here, you should log the error and decide what to do next
  e.printStackTrace();
}

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

How to order events bound with jQuery

The order the bound callbacks are called in is managed by each jQuery object's event data. There aren't any functions (that I know of) that allow you to view and manipulate that data directly, you can only use bind() and unbind() (or any of the equivalent helper functions).

Dowski's method is best, you should modify the various bound callbacks to bind to an ordered sequence of custom events, with the "first" callback bound to the "real" event. That way, no matter in what order they are bound, the sequence will execute in the right way.

The only alternative I can see is something you really, really don't want to contemplate: if you know the binding syntax of the functions may have been bound before you, attempt to un-bind all of those functions and then re-bind them in the proper order yourself. That's just asking for trouble, because now you have duplicated code.

It would be cool if jQuery allowed you to simply change the order of the bound events in an object's event data, but without writing some code to hook into the jQuery core that doesn't seem possible. And there are probably implications of allowing this that I haven't thought of, so maybe it's an intentional omission.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

How do I convert ticks to minutes?

there are 600 million ticks per minute. ticksperminute

Can't start Eclipse - Java was started but returned exit code=13

I found I had installed 32-bit Eclipse by mistake, and was trying to use it with a 64-bit JRE, which is why I got this error. To see whether you have 32 or 64 bit Eclipse installed, see this answer: https://stackoverflow.com/a/9578565/191761

How to avoid reverse engineering of an APK file?

Agreed with @Muhammad Saqib here: https://stackoverflow.com/a/46183706/2496464

And @Mumair give a good starting steps: https://stackoverflow.com/a/35411378/474330

It is always safe to assume that everything you distribute to your user's device, belong to the user. Plain and simple. You may be able to use the latest tools and procedure to encrypt your intellectual properties but there is no way to prevent a determined person from 'studying' your system. And even if the current technology may make it difficult for them to gain unwanted access, there might be some easy way tomorrow, or even just the next hour!

Thus, here comes the equation:

When it comes to money, we always assume that client is untrusted.

Even in as simple as an in-game economy. (Especially in games! There are more 'sophisticated' users there and loopholes spread in seconds!)

How do we stay safe?

Most, if not all, of our key processing systems (and database of course) located on the server side. And between the client and server, lies encrypted communications, validations, etc. That is the idea of thin client.

String Concatenation in EL

Mc Dowell's answer is right. I just want to add an improvement if in case you may need to return the variable's value as:

${ empty variable ? '<variable is empty>' : variable }

Why do I always get the same sequence of random numbers with rand()?

If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:

"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".

Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.

Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.

Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.

Catch Ctrl-C in C

With a signal handler.

Here is a simple example flipping a bool used in main():

#include <signal.h>

static volatile int keepRunning = 1;

void intHandler(int dummy) {
    keepRunning = 0;
}

// ...

int main(void) {

   signal(SIGINT, intHandler);

   while (keepRunning) { 
      // ...

Edit in June 2017: To whom it may concern, particularly those with an insatiable urge to edit this answer. Look, I wrote this answer seven years ago. Yes, language standards change. If you really must better the world, please add your new answer but leave mine as is. As the answer has my name on it, I'd prefer it to contain my words too. Thank you.

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

convert string into array of integers

A quick one for modern browsers:

'14 2'.split(' ').map(Number);

// [14, 2]`

Converting an object to a string

add on ---

JSON.stringify(obj) is nice, but it will convert to json string object. sometimes we will need the string of it, like when posting it in body for WCF http post and recieving as a string.

in order of this we should reuse the stringify() as following:

let obj = {id:1, name:'cherry'};
let jsonObj = JSON.stringify(doc); //json object string
let strObj = JSON.stringify(jsonObj); //json object string wrapped with string

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

How do I delete a Git branch locally and remotely?

Since January 2013, GitHub included a Delete branch button next to each branch in your "Branches" page.

Relevant blog post: Create and delete branches

How to install Android SDK Build Tools on the command line?

I just had this problem, so I finally wrote a 1 line bash dirty solution by reading and parsing the list of aviable tools :

 tools/android update sdk -u -t $(android list sdk | grep 'Android SDK Build-tools' | sed 's/ *\([0-9]\+\)\-.*/\1/')

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Restart container within pod

kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1

Assuming the container is run as root which is not recommended.

In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.

check android application is in foreground or not?

Below is updated solution for the latest Android SDK.

String PackageName = context.getPackageName();
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ComponentName componentInfo;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            List<ActivityManager.AppTask> tasks = manager.getAppTasks();
            componentInfo = tasks.get(0).getTaskInfo().topActivity;
        }
        else
        {
            List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(1);
            componentInfo = tasks.get(0).topActivity;
        }

        if (componentInfo.getPackageName().equals(PackageName))
            return true;
        return false;

Hope this helps, thanks.

How to turn off the Eclipse code formatter for certain sections of Java code?

If you put the plus sign on the beginning of the line, it formats differently:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";

Maven error "Failure to transfer..."

In my case. The issues is same reason. I see the problem is on proxy and firewall.

Here my solution
Fisrt ways:
1. install Proxy for Maven and Eclipse
2. Go to Locate the {user}/.m2/repository and Remove all the *.lastupdated files
3. Go back into Eclipse, Right-click on the project and select Maven > Update Project. > Select "Force Update of Snapshots/Releases".

If the project is still exist error. example: here is my issues after all above step

Failure to transfer org.apache.maven:maven-archiver:pom:2.5 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven:maven-archiver:pom:2.5 from/to central (https://repo.maven.apache.org/maven2): Connect timed out

I use this solution useful for me:
1. Find repository in https://mvnrepository.com/
2. Copy dependency to my *.poml of project
example

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-archiver</artifactId>
    <version>2.5</version>
</dependency>


3. Build project. the dependency missing will be downloaded to local repository.
4. Go back into Eclipse, Right-click on the project and select Maven > Update Project. > Select "Force Update of Snapshots/Releases".
=>> Error is resolved
5. I remove dependencies at step 2 after finished and resolved. Done

Progress Bar with HTML and CSS

Using setInterval.

_x000D_
_x000D_
var totalelem = document.getElementById("total");_x000D_
var progresselem = document.getElementById("progress");_x000D_
var interval = setInterval(function(){_x000D_
    if(progresselem.clientWidth>=totalelem.clientWidth)_x000D_
    {_x000D_
        clearInterval(interval);_x000D_
        return;_x000D_
    }_x000D_
    progresselem.style.width = progresselem.offsetWidth+1+"px";_x000D_
},10)
_x000D_
.outer_x000D_
{_x000D_
    width: 200px;_x000D_
    height: 15px;_x000D_
    background: red;_x000D_
}_x000D_
.inner_x000D_
{_x000D_
    width: 0px;_x000D_
    height: 15px;_x000D_
    background: green;_x000D_
}
_x000D_
<div id="total" class="outer">_x000D_
    <div id="progress" class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using CSS Transtitions.

_x000D_
_x000D_
function loading()_x000D_
{_x000D_
    document.getElementById("progress").style.width="200px";_x000D_
}
_x000D_
.outer_x000D_
{_x000D_
    width: 200px;_x000D_
    height: 15px;_x000D_
    background: red;_x000D_
}_x000D_
.inner_x000D_
{_x000D_
    width: 0px;_x000D_
    height: 15px;_x000D_
    background: green;_x000D_
    -webkit-transition:width 3s linear;_x000D_
    transition: width 3s linear;_x000D_
}
_x000D_
<div id="total" class="outer">_x000D_
    <div id="progress" class="inner"></div>_x000D_
</div>_x000D_
<button id="load" onclick="loading()">Load</button>
_x000D_
_x000D_
_x000D_

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

CSS for grabbing cursors (drag & drop)

You can create your own cursors and set them as the cursor using cursor: url('path-to-your-cursor');, or find Firefox's and copy them (bonus: a nice consistent look in every browser).

Java: unparseable date exception

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.

This from the accepted answer helped me solve this problem:

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern

The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema

I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

Class is inaccessible due to its protection level

The code you posted does not produce the error messages you quoted. You should provide a (small) example that actually exhibits the problem.

Simplest/cleanest way to implement a singleton in JavaScript

The following works in Node.js version 6:

class Foo {
  constructor(msg) {

    if (Foo.singleton) {
      return Foo.singleton;
    }

    this.msg = msg;
    Foo.singleton = this;
    return Foo.singleton;
  }
}

We test:

const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }

IIS - can't access page by ip address instead of localhost

In IIS Manager, I added a binding to the site specifying the IP address. Previously, all my bindings were host names.

firefox proxy settings via command line

Just wanted to post the code in a cleaner format... originally posted by sam3344920

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "148.233.229.235 ");>>"%ffile%\prefs.js"
echo user_pref("network.proxy.http_port", 3128);>>"%ffile%\prefs.js"
echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js"
set ffile=
cd %windir%

If someone wants to remove the proxy settings, here is some code that will do that for you.

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
type "%ffile%\prefs.js" | findstr /v "user_pref("network.proxy.type", 1);" >"%ffile%\prefs_.js"
rename "%ffile%\prefs.js" "prefs__.js"
rename "%ffile%\prefs_.js" "prefs.js"
del "%ffile%\prefs__.js"
set ffile=
cd %windir%

Explanation: The code goes and finds the perfs.js file. Then looks within it to find the line "user_pref("network.proxy.type", 1);". If it finds it, it deletes the file with the /v parameter. The reason I added the rename and delete lines is because I couldn't find a way to overwrite the file once I had removed the proxy line. I'm sure there is a more efficient/safer way of doing this...

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

Are there benefits of passing by pointer over passing by reference in C++?

Clarifications to the preceding posts:


References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)

While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)

bool test( int & a)
{
  return (&a) == (int *) NULL;
}

int
main()
{
  int * i = (int *)NULL;
  cout << ( test(*i) ) << endl;
};

The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().

Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)

Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...


More practically:

  • References hide that you are changing data stored someplace else.
  • It's easy to confuse a Reference with a Copied object.
  • Pointers make it obvious!

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For higher version of phpunit such as 6.4 You must use the namespace PHPUnit\Framework\TestCase

use TestCase instead PHPUnit_Framework_TestCase

// use the following namespace
use PHPUnit\Framework\TestCase;

// extend using TestCase instead PHPUnit_Framework_TestCase
class SampleTest extends TestCase {

}

Get public/external IP address?

string pubIp =  new System.Net.WebClient().DownloadString("https://api.ipify.org");

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

SQL Plus change current directory

Years later i had the same problem. My solution is the creation of a temporary batchfile and another instance of sqlplus:

In first SQL-Script:

:
set echo off
spool sqlsub_tmp.bat
prompt cd /D D:\some\dir
prompt sqlplus user/passwd@tnsname @second_script.sql
spool off
host sqlsub_tmp.bat
host del sqlsub_tmp.bat
:

Note that "second_script.sql" needs an "exit" statement at end if you want to return to the first one..

How to delete a column from a table in MySQL

To delete column use this,

ALTER TABLE `tbl_Country` DROP `your_col`

In Android EditText, how to force writing uppercase?

Android actually has a built-in InputFilter just for this!

edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});

Be careful, setFilters will reset all other attributes which were set via XML (i.e. maxLines, inputType,imeOptinos...). To prevent this, add you Filter(s) to the already existing ones.

InputFilter[] editFilters = <EditText>.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = <YOUR_FILTER>;  
<EditText>.setFilters(newFilters);

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

OSX - How to auto Close Terminal window after the "exit" command executed.

osascript -e "tell application \"System Events\" to keystroke \"w\" using command down"

This simulates a CMD + w keypress.

If you want Terminal to quit completely you can use: osascript -e "tell application \"System Events\" to keystroke \"q\" using command down"

This doesn't give any errors and makes the Terminal stop cleanly.

Line Break in XML formatting?

Take note: I have seen other posts that say &#xA; will give you a paragraph break, which oddly enough works in the Android xml String.xml file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the \n shows up on both.

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

on ubuntu /etc/phpmyadmin/config-db.php

make sure the password matches your config.inc.php for the control user

also for the blowfish too short error

edit /var/lib/phpmyadmin/blowfish_secret.inc.php and make the key longer

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

make *** no targets specified and no makefile found. stop

Delete your source tree that was gunzipped or gzipped and extracted to folder and reextract again. Supply your options again

./configure --with-option=/path/etc ...

Then if all libs are present, your make should succeed.

Get Today's date in Java at midnight time

    Calendar c = new GregorianCalendar();
    c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    Date d1 = c.getTime(); //the midnight, that's the first second of the day.

should be Fri Mar 09 00:00:00 IST 2012

var functionName = function() {} vs function functionName() {}

A function declaration and a function expression assigned to a variable behave the same once the binding is established.

There is a difference however at how and when the function object is actually associated with its variable. This difference is due to the mechanism called variable hoisting in JavaScript.

Basically, all function declarations and variable declarations are hoisted to the top of the function in which the declaration occurs (this is why we say that JavaScript has function scope).

  • When a function declaration is hoisted, the function body "follows" so when the function body is evaluated, the variable will immediately be bound to a function object.

  • When a variable declaration is hoisted, the initialization does not follow, but is "left behind". The variable is initialized to undefined at the start of the function body, and will be assigned a value at its original location in the code. (Actually, it will be assigned a value at every location where a declaration of a variable with the same name occurs.)

The order of hoisting is also important: function declarations take precedence over variable declarations with the same name, and the last function declaration takes precedence over previous function declarations with the same name.

Some examples...

var foo = 1;
function bar() {
  if (!foo) {
    var foo = 10 }
  return foo; }
bar() // 10

Variable foo is hoisted to the top of the function, initialized to undefined, so that !foo is true, so foo is assigned 10. The foo outside of bar's scope plays no role and is untouched.

function f() {
  return a; 
  function a() {return 1}; 
  var a = 4;
  function a() {return 2}}
f()() // 2

function f() {
  return a;
  var a = 4;
  function a() {return 1};
  function a() {return 2}}
f()() // 2

Function declarations take precedence over variable declarations, and the last function declaration "sticks".

function f() {
  var a = 4;
  function a() {return 1}; 
  function a() {return 2}; 
  return a; }
f() // 4

In this example a is initialized with the function object resulting from evaluating the second function declaration, and then is assigned 4.

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}}
b();
a // 1

Here the function declaration is hoisted first, declaring and initializing variable a. Next, this variable is assigned 10. In other words: the assignment does not assign to outer variable a.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Error "The connection to adb is down, and a severe error has occurred."

This problem has been plaguing me for days until I finally figured out what was causing it. It got so bad I couldn't even update my apps even after trying all the above suggestions.

HTC Sync also runs a process called adb.exe. HTC Sync is an optional program available when installing the HTC USB driver. I had recently updated my installation of the HTC bundle and apparently hadn't installed HTC Sync before. Checking properties on adb.exe in the Task Manager showed it to belong to HTC Sync, not Android.

As soon as I uninstalled HTC Sync from the control panel the problem disappeared! (It's listed separately from the USB driver so that can stay.) I never saw more than one instance of adb.exe running. I'm curious to know if people having to kill the process from Task Manager, check to see if it's actually the Android process you are killing?

Please read user comments (I too have a HTC Thunderbolt): http://www.file.net/process/adb.exe.html

How do I serialize a C# anonymous type to a JSON string?

Please note this is from 2008. Today I would argue that the serializer should be built in and that you can probably use swagger + attributes to inform consumers about your endpoint and return data.


Iwould argue that you shouldn't be serializing an anonymous type. I know the temptation here; you want to quickly generate some throw-away types that are just going to be used in a loosely type environment aka Javascript in the browser. Still, I would create an actual type and decorate it as Serializable. Then you can strongly type your web methods. While this doesn't matter one iota for Javascript, it does add some self-documentation to the method. Any reasonably experienced programmer will be able to look at the function signature and say, "Oh, this is type Foo! I know how that should look in JSON."

Having said that, you might try JSON.Net to do the serialization. I have no idea if it will work

How do I find a stored procedure containing <text>?

In case you needed schema as well:

SELECT   DISTINCT SCHEMA_NAME(o.schema_id),o.name,[text]
FROM     syscomments AS c
         INNER JOIN sys.objects AS o ON c.id = o.[object_id]
         INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
WHERE    text LIKE '%foo%'
ORDER BY  SCHEMA_NAME(o.schema_id),o.name 

AWS EFS vs EBS vs S3 (differences & when to use?)

One word answer: MONEY :D

1 GB to store in US-East-1: (Updated at 2016.dec.20)

  • Glacier: $0.004/Month (Note: Major price cut in 2016)
  • S3: $0.023/Month
  • S3-IA (announced in 2015.09): $0.0125/Month (+$0.01/gig retrieval charge)
  • EBS: $0.045-0.1/Month (depends on speed - SSD or not) + IOPS costs
  • EFS: $0.3/Month

Further storage options, which may be used for temporary storing data while/before processing it:

  • SNS
  • SQS
  • Kinesis stream
  • DynamoDB, SimpleDB

The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.

There are a lot more differences between these services:

EFS is:

  • Generally Available (out of preview), but may not yet be available in your region
  • Network filesystem (that means it may have bigger latency but it can be shared across several instances; even between regions)
  • It is expensive compared to EBS (~10x more) but it gives extra features.
  • It's a highly available service.
  • It's a managed service
  • You can attach the EFS storage to an EC2 Instance
  • Can be accessed by multiple EC2 instances simultaneously
  • Since 2016.dec.20 it's possible to attach your EFS storage directly to on-premise servers via Direct Connect. ()

EBS is:

  • A block storage (so you need to format it). This means you are able to choose which type of file system you want.
  • As it's a block storage, you can use Raid 1 (or 0 or 10) with multiple block storages
  • It is really fast
  • It is relatively cheap
  • With the new announcements from Amazon, you can store up to 16TB data per storage on SSD-s.
  • You can snapshot an EBS (while it's still running) for backup reasons
  • But it only exists in a particular region. Although you can migrate it to another region, you cannot just access it across regions (only if you share it via the EC2; but that means you have a file server)
  • You need an EC2 instance to attach it to
  • New feature (2017.Feb.15): You can now increase volume size, adjust performance, or change the volume type while the volume is in use. You can continue to use your application while the change takes effect.

S3 is:

  • An object store (not a file system).
  • You can store files and "folders" but can't have locks, permissions etc like you would with a traditional file system
  • This means, by default you can't just mount S3 and use it as your webserver
  • But it's perfect for storing your images and videos for your website
  • Great for short term archiving (e.g. a few weeks). It's good for long term archiving too, but Glacier is more cost efficient.
  • Great for storing logs
  • You can access the data from every region (extra costs may apply)
  • Highly Available, Redundant. Basically data loss is not possible (99.999999999% durability, 99.9 uptime SLA)
  • Much cheaper than EBS.
  • You can serve the content directly to the internet, you can even have a full (static) website working direct from S3, without an EC2 instance

Glacier is:

  • Long term archive storage
  • Extremely cheap to store
  • Potentially very expensive to retrieve
  • Takes up to 4 hours to "read back" your data (so only store items you know you won't need to retrieve for a long time)

As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)

Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

For Java programmers using Spring, I've avoided this problem using an AOP aspect that automatically retries transactions that run into transient deadlocks.

See @RetryTransaction Javadoc for more info.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There isn't a direct equivalent. Just store it numerically, e.g. number of seconds or something appropriate to your required accuracy.

How to remove "href" with Jquery?

If you want your anchor to still appear to be clickable:

$("a").removeAttr("href").css("cursor","pointer");

And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in asp.net)

$("a[href='#']").removeAttr("href").css("cursor","pointer");

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

How do I use Spring Boot to serve static content located in Dropbox folder?

There's a property spring.resources.staticLocations that can be set in the application.properties. Note that this will override the default locations. See org.springframework.boot.autoconfigure.web.ResourceProperties.

Unable to verify leaf signature

Another approach to solving this securely is to use the following module.

node_extra_ca_certs_mozilla_bundle

This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

To generate the PEM file to use with the above environment variable. You can install the module using:

npm install --save node_extra_ca_certs_mozilla_bundle

and then launch your node script with an environment variable.

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

Other ways to use the generated PEM file are available at:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

NOTE: I am the author of the above module.

Column name or number of supplied values does not match table definition

This is an older post but I want to also mention that if you have something like

insert into blah
       select * from blah2

and blah and blah2 are identical keep in mind that a computed column will throw this same error...

I just realized that when the above failed and I tried

insert into blah (cola, colb, colc)
       select cola, colb, colc from blah2

In my example it was fullname field (computed from first and last, etc)

Cannot kill Python script with Ctrl-C

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

How can I exclude multiple folders using Get-ChildItem -exclude?

You can exclude like this, the regex 'or' symbol, assuming a file you want doesn't have the same name as a folder you're excluding.

$exclude = 'dir1|dir2|dir3'
ls -r | where { $_.fullname -notmatch $exclude }

ls -r -dir | where fullname -notmatch 'dir1|dir2|dir3'

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

How to set a session variable when clicking a <a> link

In HTML:

<a href="index.php?link=home" name="home">home</a>

Then in PHP:

if(isset($_GET['link'])){$_SESSION['link'] = $_GET['link'];}

Cleanest way to reset forms

For just to reset the form use reset() method. It resets the form but you could get issue such as validation errors - ex: Name is required

To solve this use resetForm() method. It resets the form and also resets the submit status solving your issue.

The resetForm() method is actually calling reset() method and additionally it is resetting the submit status.

Does Enter key trigger a click event?

Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.

<button type="button" ...></button>

Big thanks to DeborahK!

Angular2 - Enter Key executes first (click) function present on the form

Angular/RxJs When should I unsubscribe from `Subscription`

The SubSink package, an easy and consistent solution for unsubscribing

As nobody else has mentioned it, I want to recommend the Subsink package created by Ward Bell: https://github.com/wardbell/subsink#readme.

I have been using it on a project were we are several developers all using it. It helps a lot to have a consistent way that works in every situation.

How do I compute the intersection point of two lines?

I didn't find an intuitive explanation on the web, so now that I worked it out, here's my solution. This is for infinite lines (what I needed), not segments.

Some terms you might remember:

A line is defined as y = mx + b OR y = slope * x + y-intercept

Slope = rise over run = dy / dx = height / distance

Y-intercept is where the line crosses the Y axis, where X = 0

Given those definitions, here are some functions:

def slope(P1, P2):
    # dy/dx
    # (y2 - y1) / (x2 - x1)
    return(P2[1] - P1[1]) / (P2[0] - P1[0])

def y_intercept(P1, slope):
    # y = mx + b
    # b = y - mx
    # b = P1[1] - slope * P1[0]
    return P1[1] - slope * P1[0]

def line_intersect(m1, b1, m2, b2):
    if m1 == m2:
        print ("These lines are parallel!!!")
        return None
    # y = mx + b
    # Set both lines equal to find the intersection point in the x direction
    # m1 * x + b1 = m2 * x + b2
    # m1 * x - m2 * x = b2 - b1
    # x * (m1 - m2) = b2 - b1
    # x = (b2 - b1) / (m1 - m2)
    x = (b2 - b1) / (m1 - m2)
    # Now solve for y -- use either line, because they are equal here
    # y = mx + b
    y = m1 * x + b1
    return x,y

Here's a simple test between two (infinite) lines:

A1 = [1,1]
A2 = [3,3]
B1 = [1,3]
B2 = [3,1]
slope_A = slope(A1, A2)
slope_B = slope(B1, B2)
y_int_A = y_intercept(A1, slope_A)
y_int_B = y_intercept(B1, slope_B)
print(line_intersect(slope_A, y_int_A, slope_B, y_int_B))

Output:

(2.0, 2.0)

How to get $(this) selected option in jQuery?

Best and shortest way in my opinion for onchange events on the dropdown to get the selected option:

$('option:selected',this);

to get the value attribute:

$('option:selected',this).attr('value');

to get the shown part between the tags:

$('option:selected',this).text();

In your sample:

$("#select-id").change(function(){
  var cur_value = $('option:selected',this).text();
});

How can I make a thumbnail <img> show a full size image when clicked?

The

<a href="image2.gif" ><img src="image1.gif"/></a>

technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.

Returning Arrays in Java

You need to do something with the return value...

import java.util.Arrays;

public class trial1{

    public static void main(String[] args){
        int[] B = numbers();
        System.out.println(Arrays.toString(B));
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

AngularJS not detecting Access-Control-Allow-Origin header?

It's a bug in chrome for local dev. Try other browser. Then it'll work.

Read/write files within a Linux kernel module

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);

# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
            loff_t *pos);

Also, filp_open no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs).

trigger click event from angularjs directive

This is more the Angular way to do it: http://plnkr.co/edit/xYNX47EsYvl4aRuGZmvo?p=preview

  1. I added $scope.selectedItem that gets you past your first problem (defaulting the image)
  2. I added $scope.setSelectedItem and called it in ng-click. Your final requirements may be different, but using a directive to bind click and change src was overkill, since most of it can be handled with template
  3. Notice use of ngSrc to avoid errant server calls on initial load
  4. You'll need to adjust some styles to get the image positioned right in the div. If you really need to use background-image, then you'll need a directive like ngSrc that defers setting the background-image style until after real data has loaded.

How can I install packages using pip according to the requirements.txt file from a local directory?

Installing requirements.txt file inside virtual env with Python 3:

I had the same issue. I was trying to install the requirements.txt file inside a virtual environment. I found the solution.

Initially, I created my virtualenv in this way:

virtualenv -p python3 myenv

Activate the environment using:

source myenv/bin/activate

Now I installed the requirements.txt file using:

pip3 install -r requirements.txt

Installation was successful and I was able to import the modules.

Is it possible in Java to catch two exceptions in the same catch block?

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

"python" not recognized as a command

Make sure you click on Add python.exe to path during install, and select:

"Will be installed on local hard drive"

It fixed my problem, hope it helps...

jQuery find element by data attribute value

You can also use .filter()

$('.slide-link').filter('[data-slide="0"]').addClass('active');

docker mounting volumes on host

If you came here because you were looking for a simple way to browse any VOLUME:

  1. Find out the name of the volume with docker volume list
  2. Shut down all running containers to which this volume is attached to
  3. Run docker run -it --rm --mount source=[NAME OF VOLUME],target=/volume busybox
  4. A shell will open. cd /volume to enter the volume.

How to get system time in Java without creating a new Date

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

How do I set the value property in AngularJS' ng-options?

If you want to change the value of your option elements because the form will eventually be submitted to the server, instead of doing this,

<select name="text" ng-model="text" ng-options="select p.text for p in resultOptions"></select>

You can do this:

<select ng-model="text" ng-options="select p.text for p in resultOptions"></select>
<input type="hidden" name="text" value="{{ text }}" />

The expected value will then be sent through the form under the correct name.

How to check that an element is in a std::set?

In C++20 we'll finally get std::set::contains method.

#include <iostream>
#include <string>
#include <set>

int main()
{
    std::set<std::string> example = {"Do", "not", "panic", "!!!"};

    if(example.contains("panic")) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

Javascript files are often cached by the browser for a lot longer than you might expect.

This can often result in unexpected behaviour when you release a new version of your JS file.

Therefore, it is common practice to add a QueryString parameter to the URL for the javascript file. That way, the browser caches the Javascript file with v=1. When you release a new version of your javascript file you change the url's to v=2 and the browser will be forced to download a new copy.

How to force Eclipse to ask for default workspace?

Editing the config.ini file with

osgi.instance.area.default=\D:\\Projects\\Eclipse Workspace\\

worked for me.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to rename a class and its corresponding file in Eclipse?

To rename file using refactoring (which also updates all occurrences of name in other scripts):

  1. Save changes to file before using refactoring/renaming
  2. In Project Explorer view, right-click file to be renamed and select Refactor | Rename -or- select it and go to Refactor | Rename from the Menu Bar. A Rename File dialog will appear.
  3. Enter the file's new name.
  4. Check the "Update references" box and click Preview.
  5. You can scroll through changes using the Select Next / Previous Change scrolling arrows.
  6. Press OK to rename file and update all occurrences of the script name in other scripts.

See "PHP Developer User Guide > Tasks > Using Refactoring > Renaming Files".

Error in installation a R package

I had the same problem with e1071 package. Just close any other R sessions running parallelly and you will be good to go.

How to change button text in Swift Xcode 6?

swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

How to find index of list item in Swift?

You can filter an array with a closure:

var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 }  // <= returns [3]

And you can count an array:

filtered.count // <= returns 1

So you can determine if an array includes your element by combining these:

myList.filter { $0 == 3 }.count > 0  // <= returns true if the array includes 3

If you want to find the position, I don't see fancy way, but you can certainly do it like this:

var found: Int?  // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
    if x[i] == 3 {
        found = i
    }
}

EDIT

While we're at it, for a fun exercise let's extend Array to have a find method:

extension Array {
    func find(includedElement: T -> Bool) -> Int? {
        for (idx, element) in enumerate(self) {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }
}

Now we can do this:

myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

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

If you want control over interpolation modes see this post.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Why are you doing this? If you want something that looks like a navigation bar, use UINavigationBar.

Toolbars have specific visual style associated with them. The Human Interface Guidelines for the iPhone state:

A toolbar appears at the bottom edge of the screen and contains buttons that perform actions related to objects in the current view.

It then gives several visual examples of roughly square icons with no text. I would urge you to follow the HIG on this.

how to convert java string to Date object

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".

So, try to change the code to:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

Output:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

What exactly is Spring Framework for?

In the past I thought about Spring framework from purely technical standpoint.

Given some experience of team work and developing enterprise Webapps - I would say that Spring is for faster development of applications (web applications) by decoupling its individual elements (beans). Faster development makes it so popular. Spring allows shifting responsibility of building (wiring up) the application onto the Spring framework. The Spring framework's dependency injection is responsible for connecting/ wiring up individual beans into a working application.

This way developers can be focused more on development of individual components (beans) as soon as interfaces between beans are defined.

Testing of such application is easy - the primary focus is given to individual beans. They can be easily decoupled and mocked, so unit-testing is fast and efficient.

Spring framework defines multiple specialized beans such as @Controller (@Restcontroller), @Repository, @Component to serve web purposes. Spring together with Maven provide a structure that is intuitive to developers. Team work is easy and fast as there is individual elements are kept apart and can be reused.

How can I escape square brackets in a LIKE clause?

The ESCAPE keyword is used if you need to search for special characters like % and _, which are normally wild cards. If you specify ESCAPE, SQL will search literally for the characters % and _.

Here's a good article with some more examples

SELECT columns FROM table WHERE 
    column LIKE '%[[]SQL Server Driver]%' 

-- or 

SELECT columns FROM table WHERE 
    column LIKE '%\[SQL Server Driver]%' ESCAPE '\'

ActiveRecord OR query

Use ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

The resulting SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))

Unable to call the built in mb_internal_encoding method?

If someone is having trouble with installing php-mbstring package in ubuntu do following sudo apt-get install libapache2-mod-php5

Calling multiple JavaScript functions on a button click

I think that since return validateView(); will return a value (to the click event?), your second call ShowDiv1(); will not get called.

You can always wrap multiple function calls in another function, i.e.

<asp:LinkButton OnClientClick="return display();">

function display() {
   if(validateView() && ShowDiv1()) return true;
}

You also might try:

<asp:LinkButton OnClientClick="return (validateView() && ShowDiv1());">

Though I have no idea if that would throw an exception.

Error in Process.Start() -- The system cannot find the file specified

You can use the folowing to get the full path to your program like this:

Environment.CurrentDirectory

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()

Setting default value for TypeScript object passed as argument

Typescript supports default parameters now:

https://www.typescriptlang.org/docs/handbook/functions.html

Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:

function sayName(firstName: string, lastName = "Smith") {
  const name = firstName + ' ' + lastName;
  alert(name);
}

sayName('Bob');

Remove property for all objects in array

ES6:

const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))

What's the difference between using CGFloat and float?

As @weichsel stated, CGFloat is just a typedef for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat. Same goes for integer values.

I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.

Iterating over a numpy array

If you only need the indices, you could try numpy.ndindex:

>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

jQuery send HTML data through POST

I don't see why you shouldn't be able to send html content via a post.

if you encounter any issues, you could perhaps use some kind of encoding / decoding - but I don't see that you will.

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/

What is a deadlock?

To define deadlock, first I would define process.

Process : As we know process is nothing but a program in execution.

Resource : To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.

Deadlock : Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.

Deadlock condition or situation

enter image description here

In the above diagram there are two process P1 and p2 and there are two resources R1 and R2.

Resource R1 is allocated to process P1 and resource R2 is allocated to process p2. To complete execution of process P1 needs resource R2, so P1 request for R2, but R2 is already allocated to P2.

In the same way Process P2 to complete its execution needs R1, but R1 is already allocated to P1.

both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a DEADLOCK Condition.

In order for deadlock to occur, four conditions must be true.

  1. Mutual exclusion - Each resource is either currently allocated to exactly one process or it is available. (Two processes cannot simultaneously control the same resource or be in their critical section).
  2. Hold and Wait - processes currently holding resources can request new resources.
  3. No preemption - Once a process holds a resource, it cannot be taken away by another process or the kernel.
  4. Circular wait - Each process is waiting to obtain a resource which is held by another process.

and all these condition are satisfied in above diagram.

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

Invalidating JSON Web Tokens

I just save token to users table, when user login I will update new token, and when auth equal to the user current jwt.

I think this is not the best solution but that work for me.

Clang vs GCC - which produces faster binaries?

The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.

Regex number between 1 and 100

I use for this angular 6

try this.

^([0-9]\.[0-9]{1}|[0-9]\.[0-9]{2}|\.[0-9]{2}|[1-9][0-9]\.[0-9]{1}|[1-9][0-9]\.[0-9]{2}|[0-9][0-9]|[1-9][0-9]\.[0-9]{2})$|^([0-9]|[0-9][0-9]|[0-99])$|^100$

it's validate 0.00 - 100. with two decimal places.

hope this will help

<input matInput [(ngModel)]="commission" type="number" max="100" min="0" name="rateInput" pattern="^(\.[0-9]{2}|[0-9]\.[0-9]{2}|[0-9][0-9]|[1-9][0-9]\.[0-9]{2})$|^([0-9]|[0-9][0-9]|[0-99])$|^100$" required #rateInput2="ngModel"><span>%</span><br>

Number should be between 0 and 100

Inject service in app.config

I don't think you're supposed to be able to do this, but I have successfully injected a service into a config block. (AngularJS v1.0.7)

angular.module('dogmaService', [])
    .factory('dogmaCacheBuster', [
        function() {
            return function(path) {
                return path + '?_=' + Date.now();
            };
        }
    ]);

angular.module('touch', [
        'dogmaForm',
        'dogmaValidate',
        'dogmaPresentation',
        'dogmaController',
        'dogmaService',
    ])
    .config([
        '$routeProvider',
        'dogmaCacheBusterProvider',
        function($routeProvider, cacheBuster) {
            var bust = cacheBuster.$get[0]();

            $routeProvider
                .when('/', {
                    templateUrl: bust('touch/customer'),
                    controller: 'CustomerCtrl'
                })
                .when('/screen2', {
                    templateUrl: bust('touch/screen2'),
                    controller: 'Screen2Ctrl'
                })
                .otherwise({
                    redirectTo: bust('/')
                });
        }
    ]);

angular.module('dogmaController', [])
    .controller('CustomerCtrl', [
        '$scope',
        '$http',
        '$location',
        'dogmaCacheBuster',
        function($scope, $http, $location, cacheBuster) {

            $scope.submit = function() {
                $.ajax({
                    url: cacheBuster('/customers'),  //server script to process data
                    type: 'POST',
                    //Ajax events
                    // Form data
                    data: formData,
                    //Options to tell JQuery not to process data or worry about content-type
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function() {
                        $location
                            .path('/screen2');

                        $scope.$$phase || $scope.$apply();
                    }
                });
            };
        }
    ]);

SQL Server 2000: How to exit a stored procedure?

This seems like a lot of code but the best way i've found to do it.

    ALTER PROCEDURE Procedure
    AS

    BEGIN TRY
        EXEC AnotherProcedure
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;

        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
        RETURN --this forces it out
    END CATCH

--Stuff here that you do not want to execute if the above failed.    

    END --end procedure

javascript: detect scroll end

I found an alternative that works.

None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.

Implemented solution:

function IsScrollbarAtBottom() {
    var documentHeight = $(document).height();
    var scrollDifference = $(window).height() + $(window).scrollTop();
    return (documentHeight == scrollDifference);
}

Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html

Regards

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

How to prevent column break within an element?

Firefox now supports this:

page-break-inside: avoid;

This solves the problem of elements breaking across columns.

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

Uninstall / remove a Homebrew package including all its dependencies

You can just use a UNIX pipe for this

brew deps [FORMULA] | xargs brew rm

How to set the color of "placeholder" text?

For Firefox use:

 input:-moz-placeholder { color: #aaa; }
 textarea:-moz-placeholder { color: #aaa;}

For all other browsers (Chrome, IE, Safari), just use:

 .placeholder { color: #aaa; }

Invert "if" statement to reduce nesting

Guard clauses or pre-conditions (as you can probably see) check to see if a certain condition is met and then breaks the flow of the program. They're great for places where you're really only interested in one outcome of an if statement. So rather than say:

if (something) {
    // a lot of indented code
}

You reverse the condition and break if that reversed condition is fulfilled

if (!something) return false; // or another value to show your other code the function did not execute

// all the code from before, save a lot of tabs

return is nowhere near as dirty as goto. It allows you to pass a value to show the rest of your code that the function couldn't run.

You'll see the best examples of where this can be applied in nested conditions:

if (something) {
    do-something();
    if (something-else) {
        do-another-thing();
    } else {
        do-something-else();
    }
}

vs:

if (!something) return;
do-something();

if (!something-else) return do-something-else();
do-another-thing();

You'll find few people arguing the first is cleaner but of course, it's completely subjective. Some programmers like to know what conditions something is operating under by indentation, while I'd much rather keep method flow linear.

I won't suggest for one moment that precons will change your life or get you laid but you might find your code just that little bit easier to read.

Setting up connection string in ASP.NET to SQL SERVER

You can put this in your web.config file connectionStrings:

<add name="myConnectionString" connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

Java - What does "\n" mean?

\n is add a new line.

Please note java has method System.out.println("Write text here");

Notice the difference:

Code:

System.out.println("Text 1");
System.out.println("Text 2");

Output:

Text 1
Text 2

Code:

System.out.print("Text 1");
System.out.print("Text 2");

Output:

Text 1Text 2

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

You are missing vendor folder, probably its new cloned repository or new project

the vendor folder is populated by composer binary which reads composer.json file or system requirements and installs packaged under vendor folder and create an autoload script that has all classed

composer update

How does the compilation/linking process work?

On the standard front:

  • a translation unit is the combination of a source files, included headers and source files less any source lines skipped by conditional inclusion preprocessor directive.

  • the standard defines 9 phases in the translation. The first four correspond to preprocessing, the next three are the compilation, the next one is the instantiation of templates (producing instantiation units) and the last one is the linking.

In practice the eighth phase (the instantiation of templates) is often done during the compilation process but some compilers delay it to the linking phase and some spread it in the two.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

If you want to run inside a background service and take the data in foreground use the below one, it is tested and verified.

public class MyService extends Service 
        implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, 
        GoogleApiClient.OnConnectionFailedListener, 
        com.google.android.gms.location.LocationListener {


    private static final int ASHIS = 1234;
    Intent intentForPendingIntent;
    HandlerThread handlerThread;
    Looper looper;
    GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRrequest;
    private static final int UPDATE_INTERVAL = 1000;
    private static final int FASTEST_INTERVAL = 100;
    private static final int DSIPLACEMENT_UPDATES = 1;
    ;
    private Handler handler1;
    private Runnable runable1;
    private Location mLastLocation;
    private float waitingTime;
    private int waiting2min;
    private Location locationOld;
    private double distance;
    private float totalWaiting;
    private float speed;
    private long timeGpsUpdate;
    private long timeOld;
    private NotificationManager mNotificationManager;
    Notification notification;
    PendingIntent resultPendingIntent;
    NotificationCompat.Builder mBuilder;


    // Sets an ID for the notification
    int mNotificationId = 001;
    private static final String TAG = "BroadcastService";
    public static final String BROADCAST_ACTION = "speedExceeded";
    private final Handler handler = new Handler();
    Intent intentforBroadcast;
    int counter = 0;
    private Runnable sendUpdatesToUI;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(MyService.this, "binder", Toast.LENGTH_SHORT).show();

        return null;
    }


    @Override
    public void onCreate() {
        showNotification();
        intentforBroadcast  = new Intent(BROADCAST_ACTION);

        Toast.makeText(MyService.this, "created", Toast.LENGTH_SHORT).show();

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        createLocationRequest();
        mGoogleApiClient.connect();


    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void showNotification() {

        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_media_play)
                        .setContentTitle("Total Waiting Time")
                        .setContentText(totalWaiting+"");


        Intent resultIntent = new Intent(this, trackingFusion.class);

        // Because clicking the notification opens a new ("special") activity, there's
        // no need to create an artificial back stack.
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Builds the notification and issues it.

        mNotifyMgr.notify(mNotificationId, mBuilder.build());


        startForeground(001, mBuilder.getNotification());
    }


    @Override
    public void onLocationChanged(Location location) {

        //handler.removeCallbacks(runable);

        Toast.makeText(MyService.this, "speed" + speed, Toast.LENGTH_SHORT).show();
        timeGpsUpdate = location.getTime();
        float delta = (timeGpsUpdate - timeOld) / 1000;
        if (location.getAccuracy() < 100) {
            speed = location.getSpeed();
            distance += mLastLocation.distanceTo(location);
            Log.e("distance", "onLocationChanged: " + distance);
            //mLastLocation = location;
            //newLocation = mLastLocation;

            Log.e("location:", location + "");


            //speed = (long) (distance / delta);


            locationOld = location;
            mLastLocation = location;

            diaplayViews();
        }

        diaplayViews();
     /*if (map != null) {
         map.addMarker(new MarkerOptions()
                 .position(new LatLng(location.getLatitude(), location.getLongitude()))
                 .title("Hello world"));


     }*/
    }


    private void createLocationRequest() {

        mLocationRrequest = new LocationRequest();

        mLocationRrequest.setInterval(UPDATE_INTERVAL);
        mLocationRrequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRrequest.setSmallestDisplacement(DSIPLACEMENT_UPDATES);

    }


    private void methodToCalculateWaitingTime() {


        if (handler1 != null) {
            handler1.removeCallbacks(runable1);

        }


        Log.e("Here", "here1");
        handler1 = new Handler(Looper.getMainLooper());
        runable1 = new Runnable() {
            public void run() {

                Log.e("Here", "here2:" + mLastLocation.getSpeed());


                if (mLastLocation != null) {
                    diaplayViews();
                    if ((mLastLocation.getSpeed() == 0.0)) {

                        increaseTime();

                    } else {
                        if (waitingTime <= 120) {
                            waiting2min = 0;

                        }
                    }
                    handler1.postDelayed(this, 10000);
                } else {
                    if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mLastLocation = locationOld;

                }
            }
        };

        handler1.postDelayed(runable1, 10000);


    }

    private void diaplayViews() {
        float price = (float) (14 + distance * 0.5);

        //textDistance.setText(waitingTime);a
    }


    private void increaseTime() {
        waiting2min = waiting2min + 10;
        if (waiting2min >= 120)

        {
            if (waiting2min == 120) {
                waitingTime = waitingTime + 2 * 60;


            } else {
                waitingTime = waitingTime + 10;
            }


            totalWaiting = waitingTime / 60;
            showNotification();
            Log.e("waiting Time", "increaseTime: " + totalWaiting);
        }


    }

    @Override
    public void onDestroy() {
        Toast.makeText(MyService.this, "distroyed", Toast.LENGTH_SHORT).show();
        if (mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();
        }
        mGoogleApiClient.disconnect();

    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.e("Connection_fusion", "connected");

        startLocationUpdates();


    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    private void startLocationUpdates() {
        Location location = plotTheInitialMarkerAndGetInitialGps();
        if (location == null) {
            plotTheInitialMarkerAndGetInitialGps();


        } else {

            mLastLocation = location;
            methodToCalculateWaitingTime();
        }
    }

    private Location plotTheInitialMarkerAndGetInitialGps() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRrequest, this);
        locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if ((locationOld != null)) {
            mLastLocation = locationOld;

            timeOld = locationOld.getTime();
        } else {
            startLocationUpdates();
        }

        return mLastLocation;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        Toast.makeText(MyService.this, "start command", Toast.LENGTH_SHORT).show();

        sendUpdatesToUI = new Runnable() {
            public void run() {
                DisplayLoggingInfo();
                handler.postDelayed(this, 10000); // 5 seconds
            }
        };
        handler.postDelayed(sendUpdatesToUI, 10000); // 1 second
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_NOT_STICKY;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        sendUpdatesToUI = new Runnable() {
            public void run() {
                Log.e("sent", "sent");
                DisplayLoggingInfo();
                handler.postDelayed(this, 5000); // 5 seconds
            }
        };
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        super.onStart(intent, startId);
    }

    private void DisplayLoggingInfo() {
        Log.d(TAG, "entered DisplayLoggingInfo");
        intentforBroadcast.putExtra("distance", distance);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentforBroadcast);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

    }
}

Git: How to squash all commits on branch

Although this answer is a bit verbose it does allow you to create a single commit branch by doing a single merge with another branch. (No rebasing/squashing/merging individual commits).

Since we don't care about the in-between commits we can use a simple solution:

# Merge and resolve conflicts
git merge origin/master

# Soft reset and create a HEAD with the version you want
git reset --soft origin/master
git commit -m "Commit message"
git push origin your-branch -f

... then to remove the history...

# Get the most up-to-date master
git checkout master
git reset --hard

# Create a temporary branch
git checkout -b temp-branch

# Retrieve the diff between master and your-branch and commit with a single commit
git checkout origin/your-branch
git commit -m "Feature commit"

# Force push to the feature branch
git push origin temp-branch:your-branch -f

# Clean up
git checkout your-branch
git branch -D temp-branch

This can all be put into a bash function with 3 params like so squashall --their master --mine your-branch --msg "Feature commit" and it will work as long as you have the correct version of files locally.

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Laravel 5 Carbon format datetime

Declare in model:

class ModelName extends Model
{      

 protected $casts = [
    'created_at' => 'datetime:d/m/Y', // Change your format
    'updated_at' => 'datetime:d/m/Y',
];

Ascending and Descending Number Order in java

You can sort the array first, and then loop through it twice, once in both directions:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

req.body empty on posts

In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.

Also to get rid of error message replace:

app.use(bodyParser.urlencoded())

With:

app.use(bodyParser.urlencoded({
  extended: true
}));

See https://github.com/expressjs/body-parser

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart

As @SujeetAgrahari mentioned, body-parser is now inbuilt with express.js.

Use app.use(express.json()); to implement it in recent versions for JSON bodies. For URL encoded bodies (the kind produced by HTTP form POSTs) use app.use(express.urlencoded());

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

How to run Java program in command prompt

A very general command prompt how to for java is

javac mainjava.java
java mainjava

You'll very often see people doing

javac *.java
java mainjava

As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

Count distinct values

SELECT CUSTOMER, COUNT(*) as PETS 
FROM table_name 
GROUP BY CUSTOMER;

Which characters make a URL invalid?

Several of Unicode character ranges are valid HTML5, although it might still not be a good idea to use them.

E.g., href docs say http://www.w3.org/TR/html5/links.html#attr-hyperlink-href:

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

Then the definition of "valid URL" points to http://url.spec.whatwg.org/, which says it aims to:

Align RFC 3986 and RFC 3987 with contemporary implementations and obsolete them in the process.

That document defines URL code points as:

ASCII alphanumeric, "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", and code points in the ranges U+00A0 to U+D7FF, U+E000 to U+FDCF, U+FDF0 to U+FFFD, U+10000 to U+1FFFD, U+20000 to U+2FFFD, U+30000 to U+3FFFD, U+40000 to U+4FFFD, U+50000 to U+5FFFD, U+60000 to U+6FFFD, U+70000 to U+7FFFD, U+80000 to U+8FFFD, U+90000 to U+9FFFD, U+A0000 to U+AFFFD, U+B0000 to U+BFFFD, U+C0000 to U+CFFFD, U+D0000 to U+DFFFD, U+E1000 to U+EFFFD, U+F0000 to U+FFFFD, U+100000 to U+10FFFD.

The term "URL code points" is then used in the statement:

If c is not a URL code point and not "%", parse error.

in a several parts of the parsing algorithm, including the schema, authority, relative path, query and fragment states: so basically the entire URL.

Also, the validator http://validator.w3.org/ passes for URLs like "??", and does not pass for URLs with characters like spaces "a b"

Of course, as mentioned by Stephen C, it is not just about characters but also about context: you have to understand the entire algorithm. But since class "URL code points" is used on key points of the algorithm, it that gives a good idea of what you can use or not.

See also: Unicode characters in URLs

Is Spring annotation @Controller same as @Service?

No you can't they are different. When the app was deployed your controller mappings would be borked for example.

Why do you want to anyway, a controller is not a service, and vice versa.

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I also had this problem. In my case it was because of no grants were assigned to MySQL user. Assigning grants to MySQL user which my app uses resolved the issue:

grant select, insert, delete, update on my_db.* to 'my_user'@'%';

Declare a dictionary inside a static class

The problem with your initial example was primarily due to the use of const rather than static; you can't create a non-null const reference in C#.

I believe this would also have worked:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic
        = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
}

Also, as Y Low points out, adding readonly is a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.

Laravel password validation rule

Sounds like a good job for regular expressions.

Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :

This might help too:

http://www.regular-expressions.info/unicode.html

Using --add-host or extra_hosts with docker-compose

https://docs.docker.com/compose/compose-file/#extra_hosts

extra_hosts - Add hostname mappings. Uses the same values as the docker client --add-host parameter.

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

An entry with the ip address and hostname will be created in /etc/hosts > inside containers for this service, e.g:

162.242.195.82  somehost
50.31.209.229   otherhost

The real difference between "int" and "unsigned int"

There is no difference between the two in how they are stored in memory and registers, there is no signed and unsigned version of int registers there is no signed info stored with the int, the difference only becomes relevant when you perform maths operations, there are signed and unsigned version of the maths ops built into the CPU and the signedness tell the compiler which version to use.

Storing an object in state of a React component?

In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper

import update from 'immutability-helper';

var abc = update(this.state.abc, {
   xyz: {$set: 'foo'}
});

this.setState({abc: abc});

This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.

If you do this, you can have the following to make up for the performance of

shouldComponentUpdate: function(nextProps, nextState){
   return this.state.abc !== nextState.abc; 
   // and compare any props that might cause an update
}

Remove the last chars of the Java String variable

I think you want to remove the last five characters ('.', 'n', 'u', 'l', 'l'):

path = path.substring(0, path.length() - 5);

Note how you need to use the return value - strings are immutable, so substring (and other methods) don't change the existing string - they return a reference to a new string with the appropriate data.

Or to be a bit safer:

if (path.endsWith(".null")) {
  path = path.substring(0, path.length() - 5);
}

However, I would try to tackle the problem higher up. My guess is that you've only got the ".null" because some other code is doing something like this:

path = name + "." + extension;

where extension is null. I would conditionalise that instead, so you never get the bad data in the first place.

(As noted in a question comment, you really should look through the String API. It's one of the most commonly-used classes in Java, so there's no excuse for not being familiar with it.)

Spring Data JPA find by embedded object property

According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  

or

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

However, it also depends on the naming convention of fields that you have in your @Embeddable class,

e.g. the following field might not work in any of the styles that mentioned above

private String cRcdDel;

I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 

or

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);

When I renamed column to

private String rcdDel;

my following solutions work fine without any issue:

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 

OR

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);

Removing trailing newline character from fgets() input

For single '\n' trimming,

void remove_new_line(char* string)
{
    size_t length = strlen(string);
    if((length > 0) && (string[length-1] == '\n'))
    {
        string[length-1] ='\0';
    }
}

for multiple '\n' trimming,

void remove_multi_new_line(char* string)
{
  size_t length = strlen(string);
  while((length>0) && (string[length-1] == '\n'))
  {
      --length;
      string[length] ='\0';
  }
}

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

How do I set the background color of my main screen in Flutter?

you should return Scaffold widget and add your widget inside Scaffold

suck as this code :

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          backgroundColor: Colors.white,
          body: Center(child: new Text("Hello, World!"));
    );
  }
}

How to convert Seconds to HH:MM:SS using T-SQL

You can try this

set @duration= 112000
SELECT 
   "Time" = cast (@duration/3600 as varchar(3)) +'H'
         + Case 
       when ((@duration%3600 )/60)<10 then
                 '0'+ cast ((@duration%3600 )/60)as varchar(3))
       else 
               cast ((@duration/60) as varchar(3))
       End

What is a handle in C++?

HANDLE hnd; is the same as void * ptr;

HANDLE is a typedef defined in the winnt.h file in Visual Studio (Windows):

typedef void *HANDLE;

Read more about HANDLE

PHP exec() vs system() vs passthru()

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

How do I get a class instance of generic type T?

Imagine you have an abstract superclass that is generic:

public abstract class Foo<? extends T> {}

And then you have a second class that extends Foo with a generic Bar that extends T:

public class Second extends Foo<Bar> {}

You can get the class Bar.class in the Foo class by selecting the Type (from bert bruynooghe answer) and infering it using Class instance:

Type mySuperclass = myFoo.getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
//Parse it as String
String className = tType.toString().split(" ")[1];
Class clazz = Class.forName(className);

You have to note this operation is not ideal, so it is a good idea to cache the computed value to avoid multiple calculations on this. One of the typical uses is in generic DAO implementation.

The final implementation:

public abstract class Foo<T> {

    private Class<T> inferedClass;

    public Class<T> getGenericClass(){
        if(inferedClass == null){
            Type mySuperclass = getClass().getGenericSuperclass();
            Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
            String className = tType.toString().split(" ")[1];
            inferedClass = Class.forName(className);
        }
        return inferedClass;
    }
}

The value returned is Bar.class when invoked from Foo class in other function or from Bar class.

Content is not allowed in Prolog SAXParserException

to simply remove it, paste your xml file into notepad, you'll see the extra character before the first tag. Remove it & paste back into your file - bof

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

My Thought,

Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.

Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.

Copy a file from one folder to another using vbscripting

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is not read-only.  Safe to replace the file.
            fso.CopyFile SourceFile, "C:\destfolder\", True
        Else 
            'The file exists and is read-only.
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            'Replace the file
            fso.CopyFile SourceFile, "C:\destfolder\", True
            'Reapply the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
        End If
    Else
        'The file does not exist in the destination folder.  Safe to copy file to this folder.
        fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

This problem bugs me for a long time since none of the work-around worked for me :(

But good news is, the following method works fine for my application.

The basic idea is to register a EventManager in App.xmal.cs to sniff PreviewMouseLeftButtonDownEvent for all ComboBoxItem, then trigger the SelectionChangedEvent if the selecting item is the same as the selected item, i.e. the selection is performed without changing index.

In App.xmal.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        // raise selection change event even when there's no change in index
        EventManager.RegisterClassHandler(typeof(ComboBoxItem), UIElement.PreviewMouseLeftButtonDownEvent,
                                          new MouseButtonEventHandler(ComboBoxSelfSelection), true);

        base.OnStartup(e);
    }

    private static void ComboBoxSelfSelection(object sender, MouseButtonEventArgs e)
    {
        var item = sender as ComboBoxItem;

        if (item == null) return;

        // find the combobox where the item resides
        var comboBox = ItemsControl.ItemsControlFromItemContainer(item) as ComboBox;

        if (comboBox == null) return;

        // fire SelectionChangedEvent if two value are the same
        if ((string)comboBox.SelectedValue == (string)item.Content)
        {
            comboBox.IsDropDownOpen = false;
            comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItem(), new ListItem()));
        }
    }
}

Then, for all combo boxes, register SelectionChangedEvent in a normal way:

<ComboBox ItemsSource="{Binding BindList}"
          SelectionChanged="YourSelectionChangedEventHandler"/>

Now, if two indices are different, nothing special but the ordinary event handling process; if two indices are the same, the Mouse Event on the item will first be handled, and thus trigger the SelectionChangedEvent. In this way, both situations will trigger SelectionChangedEvent :)

Automatically capture output of last command into a variable using Bash?

Bash is kind of an ugly language. Yes, you can assign the output to variable

MY_VAR="$(find -name foo.txt)"
echo "$MY_VAR"

But better hope your hardest that find only returned one result and that that result didn't have any "odd" characters in it, like carriage returns or line feeds, as they will be silently modified when assigned to a Bash variable.

But better be careful to quote your variable correctly when using it!

It's better to act on the file directly, e.g. with find's -execdir (consult the manual).

find -name foo.txt -execdir vim '{}' ';'

or

find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'

What is a 'workspace' in Visual Studio Code?

The main utility of a workspace (and maybe the only one) is to allow to add multiple independent folders that compounds a project. For example:

- WorkspaceProjectX  
-- ApiFolder   (maybe /usr/share/www/api)  
-- DocsFolder  (maybe /home/user/projx/html/docs)  
-- WebFolder   (maybe /usr/share/www/web)

So you can group those in a work space for a specific project instead of have to open multiple folders windows.

You can learn more here.

How to make sure that a certain Port is not occupied by any other process

netstat -ano|find ":port_no" will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .

example : netstat -ano | find ":1900" This gives you the result like this.

UDP    107.109.121.196:1900   *:*                                    1324  
UDP    127.0.0.1:1900         *:*                                    1324  
UDP    [::1]:1900             *:*                                    1324  
UDP    [fe80::8db8:d9cc:12a8:2262%13]:1900  *:*                      1324

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Clearing coverage highlighting in Eclipse

I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: enter image description here

Check if registry key exists using VBScript

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if

Converting a string to a date in JavaScript

_x000D_
_x000D_
var a = "13:15"_x000D_
var b = toDate(a, "h:m")_x000D_
//alert(b);_x000D_
document.write(b);_x000D_
_x000D_
function toDate(dStr, format) {_x000D_
  var now = new Date();_x000D_
  if (format == "h:m") {_x000D_
    now.setHours(dStr.substr(0, dStr.indexOf(":")));_x000D_
    now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));_x000D_
    now.setSeconds(0);_x000D_
    return now;_x000D_
  } else_x000D_
    return "Invalid Format";_x000D_
}
_x000D_
_x000D_
_x000D_

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Splash screen sizes for Android

and at the same time for Cordova (a.k.a Phonegap), React-Native and all other development platforms

Format : 9-Patch PNG (recommended)

Dimensions

 - LDPI:
    - Portrait: 200x320px
    - Landscape: 320x200px
 - MDPI:
    - Portrait: 320x480px
    - Landscape: 480x320px
 - HDPI:
    - Portrait: 480x800px
    - Landscape: 800x480px
 - XHDPI:
    - Portrait: 720px1280px
    - Landscape: 1280x720px
 - XXHDPI
    - Portrait: 960x1600px
    - Landscape: 1600x960px
 - XXXHDPI 
    - Portrait: 1280x1920px
    - Landscape: 1920x1280px

Note: Preparing XXXHDPI is not needed and also maybe XXHDPI size too because of the repeating areas of 9-patch images. On the other hand, if only Portrait sizes are used the App size could be more less. More pictures mean more space is need.

Pay attention

I think there is no an exact size for the all devices. I use Xperia Z 5". If you develop a crossplatform-webview app you should consider a lot of things (whether screen has softkey navigation buttons or not, etc). Therefore, I think there is only one suitable solution. The solution is to prepare a 9-patch splash screen (find How to design a new splash screen heading below).

  1. Create splash screens for the above screen sizes as 9-patch. Give names your files with .9.png suffixes
  2. Add the lines below into your config.xml file
  3. Add the splash screen plugin if it's needed.
  4. Run your project.

That's it!

Cordova specific code
To be added lines into the config.xml for 9-patch splash screens

<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="6000" />
<platform name="android">
    <splash src="res/screen/android/ldpi.9.png" density="ldpi"/>
    <splash src="res/screen/android/mdpi.9.png" density="mdpi"/>
    <splash src="res/screen/android/hdpi.9.png" density="hdpi"/>
    <splash src="res/screen/android/xhdpi.9.png" density="xhdpi"/> 
</platform>

To be added lines into the config.xml when using non-9-patch splash screens

<platform name="android">
    <splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
    <splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
    <splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
    <splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>

    <splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
    <splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
    <splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
    <splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>

How to design a new splash screen

I would describe a simple way to create proper splash screen using this way. Assume we're designing a 1280dp x 720dp - xhdpi (x-large) screen. I've written for the sake of example the below;

  • In Photoshop: File -> New in new dialog window set your screens

    Width: 720 Pixels Height: 1280 Pixels

    I guess the above sizes mean Resolution is 320 Pixels/Inch. But to ensure you can change resolution value to 320 in your dialog window. In this case Pixels/Inch = DPI

    Congratulations... You have a 720dp x 1280dp splash screen template.

How to generate a 9-patch splash screen

After you designed your splash screen, if you want to design 9-Patch splash screen, you should insert 1 pixel gap for every side. For this reason you should increase +2 pixel your canvas size's width and height ( now your image sizes are 722 x 1282 ).

I've left the blank 1 pixel gap at every side as directed the below.
Changing the canvas size by using Photoshop:
- Open a splash screen png file in Photoshop
- Click onto the lock icon next to the 'Background' name in the Layers field (to leave blank instead of another color like white) if there is like the below:
enter image description here
- Change the canvas size from Image menu ( Width: 720 pixels to 722 pixels and Height: 1280 pixels to 1282 pixels). Now, should see 1 pixel gap at every side of the splash screen image.

Then you can use C:\Program Files (x86)\Android\android-studio\sdk\tools\draw9patch.bat to convert a 9-patch file. For that open your splash screen on draw9patch app. You should define your logo and expandable areas. Notice the black line the following example splash screen. The black line's thickness is just 1 px ;) Left and Top sides black lines define your splash screen's must display area. Exactly as your designed. Right and Bottom lines define the addable and removable area (automatically repeating areas).

Just do that: Zoom your image's top edge on draw9patch application. Click and drag your mouse to draw line. And press shift + click and drag your mouse to erase line.

Sample 9-patch design

If you develop a cross-platform app (like Cordova/PhoneGap) you can find the following address almost all mabile OS splash screen sizes. Click for Windows Phone, WebOS, BlackBerry, Bada-WAC and Bada splash screen sizes.

https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes

And if you need IOS, Android etc. app icon sizes you can visit here.

IOS

Format : PNG (recommended)

Dimensions

 - Tablet (iPad)
   - Non-Retina (1x)
     - Portrait: 768x1024px
     - Landscape: 1024x768px
   - Retina (2x)
     - Portrait: 1536x2048px
     - Landscape: 2048x1536px
 - Handheld (iPhone, iPod)
   - Non-Retina (1x)
     - Portrait: 320x480px
     - Landscape: 480x320px
   - Retina (2x)
     - Portrait: 640x960px
     - Landscape: 960x640px
 - iPhone 5 Retina (2x)
   - Portrait: 640x1136px
   - Landscape: 1136x640px
 - iPhone 6 (2x)
   - Portrait: 750x1334px
   - Landscape: 1334x750px
 - iPhone 6 Plus (3x)
   - Portrait: 1242x2208px
   - Landscape: 2208x1242px

python selenium click on button

The following debugging process helped me solve a similar issue.

with open("output_init.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))


xpath1 = "the xpath of the link you want to click on"
destination_page_link = driver.find_element_by_xpath(xpath1)
destination_page_link.click()


with open("output_dest.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))

You should then have two textfiles with the initial page you were on ('output_init.txt') and the page you were forwarded to after clicking the button ('output_dest.txt'). If they're the same, then yup, your code did not work. If they aren't, then your code worked, but you have another issue. The issue for me seemed to be that the necessary javascript that transformed the content to produce my hook was not yet executed.

Your options as I see it:

  1. Have the driver execute the javascript and then call your find element code. Look for more detailed answers on this on stackoverflow, as I didn't follow this approach.
  2. Just find a comparable hook on the 'output_dest.txt' that will produce the same result, which is what I did.
  3. Try waiting a bit before clicking anything:

xpath2 = "your xpath that you are going to click on"

WebDriverWait(driver, timeout=5).until(lambda x: x.find_element_by_xpath(xpath2))

The xpath approach isn't necessarily better, I just prefer it, you can also use your selector approach.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

For people who like the .Net convention of "try" functions that return a boolean and handle a byref param containing the result. If you don't need the out parameter you can omit it and just use the return value.

StringTests.js

  var obj1 = {};
  var bool1 = '{"h":"happy"}'.tryParse(obj1); // false
  var obj2 = {};
  var bool2 = '2114509 GOODLUCKBUDDY 315852'.tryParse(obj2);  // false

  var obj3 = {};
  if('{"house_number":"1","road":"Mauchly","city":"Irvine","county":"Orange County","state":"California","postcode":"92618","country":"United States of America","country_code":"us"}'.tryParse(obj3))
    console.log(obj3);

StringUtils.js

String.prototype.tryParse = function(jsonObject) {
  jsonObject = jsonObject || {};
  try {
    if(!/^[\[{]/.test(this) || !/[}\]]$/.test(this)) // begin / end with [] or {}
      return false; // avoid error handling for strings that obviously aren't json
    var json = JSON.parse(this);
    if(typeof json === 'object'){
      jsonObject.merge(json);
      return true;
    }
  } catch (e) {
    return false;
  }
}

ObjectUtils.js

Object.defineProperty(Object.prototype, 'merge', {
  value: function(mergeObj){
    for (var propertyName in mergeObj) {
      if (mergeObj.hasOwnProperty(propertyName)) {
        this[propertyName] = mergeObj[propertyName];
      }      
    }
    return this;
  },
  enumerable: false, // this is actually the default
});