text:
**ATTENTION:** If you want to fix a bug in the currently released gem please use the 0.1.x-support branch. The master is the current development branch and is not ready for prime-time just yet.

# Viewpoint for Exchange Web Services 1.0
http://github.com/zenchild/Viewpoint/wiki

Viewpoint for EWS provides a thin Ruby layer on top of Microsoft Exchange
Web Services(EWS). It also includes a bunch of model classes that add an
additional layer of abstraction on top of EWS for use in implementing
programs with Viewpoint.

BLOG:  http://distributed-frostbite.blogspot.com/

Add me in LinkedIn:  http://www.linkedin.com/in/danwanek

Find me on irc.freenode.net in #ruby-lang (zenChild)

## Features

### New in 1.0

* SOAP backend is now only dependant on Nokogiri. Before version 1.0 Viewpoint
went through a number of iterations in backends including SOAP4r and Handsoap.
Each of these approaches had major issues so in the end I decided it was
easiest to just build the SOAP messages with Nokogiri since I was using it as
the parser for response messages already.

* Viewpoint is no longer built on a Singleton pattern. The reason it was
previously is because of the Handsoap backend. Handsoap itself uses a
Singleton pattern for connection to the SOAP endpoint so with authentication
I was forced to implement Viewpoint as a Singleton as well. Now with Handsoap
out of the picture this is no longer required. Go crazy ;)

### Enhanced in 1.0

* *Delegate access is supported*
  One thing that was often asked for, but missing from the previous version
  was delegate access to mailboxes and calendars.  This is now supported via
  the 'act_as' parameter to the GenericFolder::get_folder method. For example:
  ofolder = Folder.get_folder(:inbox,'otheruser@test.com')
  If your user has delegate access to the Inbox for otheruser@test.com this
  operation will retrieve their inbox and allow you to manipulate it as you
  would with your own Inbox.

* There is also some support for manipulation of delegate access itself via
  the methods MailboxUser#add_delegate!, MailboxUser#update_delegate!, and
  MailboxUser#get_delegate_info.

--------------------------------------------------------------------------
TO USE:

```ruby
require 'rubygems'
require 'viewpoint'
include Viewpoint::EWS

endpoint = 'https://example.com/ews/Exchange.asmx'
user = 'username'
pass = 'password'

cli = Viewpoint::EWSClient.new endpoint, user, pass

# Get all folders
folders = cli.find_folders

# Get a specific folder
inbox = cli.get_folder :inbox

# Get available EWS methods on an object
inbox.ews_methods

# Get items from an object (messages in this case)
msgs = inbox.items
```

--------------------------------------------------------------------------
DESIGN GOALS/GUIDELINES:

  1. The SOAP back-end should not know about the Model.
    I went around and around on this one for awhile.  There are some
    simplicity advantages to creating Model objects within the SOAP
    responses, but I ultimately decided against it so that one could use
    the SOAP back-end without the Model.  Essentially the SOAP classes
    pass back a Hash that the Model uses to create its own objects.

  2. The use of Hashes is not a crime.
    While some people decidedly do not like Hashes and believe complex
    hashing should be in the form of objects, there are some instances
    where hashing is just plain simpler and flexible.  To that end, I use
    hashes pretty extensively in Viewpoint, both for objects being passed
    to the SOAP back-end and returned from it.

  3. Follow EWS naming conventions where it makes sense.
    I try and follow the naming conventions of the Exchange Web Service
    operations as much as it makes sense.  There are some things howerver
    where they do not and I have deviated somewhat.  For example,
    an instance method named delete_folder doesn't make much sense, but
    an instance method named delete! is pretty clear what it deletes.
--------------------------------------------------------------------------
!!!SHOUTS OUT!!!
--------------------------------------------------------------------------
* Thanks to Harold Lee (https://github.com/haroldl) for working on the
  get_user_availability code.
--------------------------------------------------------------------------
DISCLAIMER:  If you see something that could be done better or would like
to help out in the development of this code please feel free to clone the
'git' repository and send me patches:
git clone git://github.com/zenchild/Viewpoint.git
or add an issue on GitHub:
http://github.com/zenchild/Viewpoint/issues

Cheers!
--------------------------------------------------------------------------


text:
Authentication and security
===========================

.. testsetup::

   import tornado.auth
   import tornado.web

Cookies and secure cookies
~~~~~~~~~~~~~~~~~~~~~~~~~~

You can set cookies in the user's browser with the ``set_cookie``
method:

.. testcode::

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            if not self.get_cookie("mycookie"):
                self.set_cookie("mycookie", "myvalue")
                self.write("Your cookie was not set yet!")
            else:
                self.write("Your cookie was set!")

.. testoutput::
   :hide:

Cookies are not secure and can easily be modified by clients.  If you
need to set cookies to, e.g., identify the currently logged in user,
you need to sign your cookies to prevent forgery. Tornado supports
signed cookies with the `~.RequestHandler.set_secure_cookie` and
`~.RequestHandler.get_secure_cookie` methods. To use these methods,
you need to specify a secret key named ``cookie_secret`` when you
create your application. You can pass in application settings as
keyword arguments to your application:

.. testcode::

    application = tornado.web.Application([
        (r"/", MainHandler),
    ], cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__")

.. testoutput::
   :hide:

Signed cookies contain the encoded value of the cookie in addition to a
timestamp and an `HMAC <http://en.wikipedia.org/wiki/HMAC>`_ signature.
If the cookie is old or if the signature doesn't match,
``get_secure_cookie`` will return ``None`` just as if the cookie isn't
set. The secure version of the example above:

.. testcode::

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            if not self.get_secure_cookie("mycookie"):
                self.set_secure_cookie("mycookie", "myvalue")
                self.write("Your cookie was not set yet!")
            else:
                self.write("Your cookie was set!")

.. testoutput::
   :hide:

Tornado's secure cookies guarantee integrity but not confidentiality.
That is, the cookie cannot be modified but its contents can be seen by the
user.  The ``cookie_secret`` is a symmetric key and must be kept secret --
anyone who obtains the value of this key could produce their own signed
cookies.

By default, Tornado's secure cookies expire after 30 days.  To change this,
use the ``expires_days`` keyword argument to ``set_secure_cookie`` *and* the
``max_age_days`` argument to ``get_secure_cookie``.  These two values are
passed separately so that you may e.g. have a cookie that is valid for 30 days
for most purposes, but for certain sensitive actions (such as changing billing
information) you use a smaller ``max_age_days`` when reading the cookie.

Tornado also supports multiple signing keys to enable signing key
rotation. ``cookie_secret`` then must be a dict with integer key versions
as keys and the corresponding secrets as values. The currently used
signing key must then be set as ``key_version`` application setting
but all other keys in the dict are allowed for cookie signature validation,
if the correct key version is set in the cookie.
To implement cookie updates, the current signing key version can be
queried via `~.RequestHandler.get_secure_cookie_key_version`.

.. _user-authentication:

User authentication
~~~~~~~~~~~~~~~~~~~

The currently authenticated user is available in every request handler
as `self.current_user <.RequestHandler.current_user>`, and in every
template as ``current_user``. By default, ``current_user`` is
``None``.

To implement user authentication in your application, you need to
override the ``get_current_user()`` method in your request handlers to
determine the current user based on, e.g., the value of a cookie. Here
is an example that lets users log into the application simply by
specifying a nickname, which is then saved in a cookie:

.. testcode::

    class BaseHandler(tornado.web.RequestHandler):
        def get_current_user(self):
            return self.get_secure_cookie("user")

    class MainHandler(BaseHandler):
        def get(self):
            if not self.current_user:
                self.redirect("/login")
                return
            name = tornado.escape.xhtml_escape(self.current_user)
            self.write("Hello, " + name)

    class LoginHandler(BaseHandler):
        def get(self):
            self.write('<form action="/login" method="post">'
                       'Name: <input type="text" name="name">'
                       '<input type="submit" value="Sign in">'
                       '</form>')

        def post(self):
            self.set_secure_cookie("user", self.get_argument("name"))
            self.redirect("/")

    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/login", LoginHandler),
    ], cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__")

.. testoutput::
   :hide:

You can require that the user be logged in using the `Python
decorator <http://www.python.org/dev/peps/pep-0318/>`_
`tornado.web.authenticated`. If a request goes to a method with this
decorator, and the user is not logged in, they will be redirected to
``login_url`` (another application setting). The example above could be
rewritten:

.. testcode::

    class MainHandler(BaseHandler):
        @tornado.web.authenticated
        def get(self):
            name = tornado.escape.xhtml_escape(self.current_user)
            self.write("Hello, " + name)

    settings = {
        "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        "login_url": "/login",
    }
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/login", LoginHandler),
    ], **settings)

.. testoutput::
   :hide:

If you decorate ``post()`` methods with the ``authenticated``
decorator, and the user is not logged in, the server will send a
``403`` response.  The ``@authenticated`` decorator is simply
shorthand for ``if not self.current_user: self.redirect()`` and may
not be appropriate for non-browser-based login schemes.

Check out the `Tornado Blog example application
<https://github.com/tornadoweb/tornado/tree/stable/demos/blog>`_ for a
complete example that uses authentication (and stores user data in a
MySQL database).

Third party authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~

The `tornado.auth` module implements the authentication and
authorization protocols for a number of the most popular sites on the
web, including Google/Gmail, Facebook, Twitter, and FriendFeed.
The module includes methods to log users in via these sites and, where
applicable, methods to authorize access to the service so you can, e.g.,
download a user's address book or publish a Twitter message on their
behalf.

Here is an example handler that uses Google for authentication, saving
the Google credentials in a cookie for later access:

.. testcode::

    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                                   tornado.auth.GoogleOAuth2Mixin):
        @tornado.gen.coroutine
        def get(self):
            if self.get_argument('code', False):
                user = yield self.get_authenticated_user(
                    redirect_uri='http://your.site.com/auth/google',
                    code=self.get_argument('code'))
                # Save the user with e.g. set_secure_cookie
            else:
                yield self.authorize_redirect(
                    redirect_uri='http://your.site.com/auth/google',
                    client_id=self.settings['google_oauth']['key'],
                    scope=['profile', 'email'],
                    response_type='code',
                    extra_params={'approval_prompt': 'auto'})

.. testoutput::
   :hide:

See the `tornado.auth` module documentation for more details.

.. _xsrf:

Cross-site request forgery protection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

`Cross-site request
forgery <http://en.wikipedia.org/wiki/Cross-site_request_forgery>`_, or
XSRF, is a common problem for personalized web applications. See the
`Wikipedia
article <http://en.wikipedia.org/wiki/Cross-site_request_forgery>`_ for
more information on how XSRF works.

The generally accepted solution to prevent XSRF is to cookie every user
with an unpredictable value and include that value as an additional
argument with every form submission on your site. If the cookie and the
value in the form submission do not match, then the request is likely
forged.

Tornado comes with built-in XSRF protection. To include it in your site,
include the application setting ``xsrf_cookies``:

.. testcode::

    settings = {
        "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        "login_url": "/login",
        "xsrf_cookies": True,
    }
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/login", LoginHandler),
    ], **settings)

.. testoutput::
   :hide:

If ``xsrf_cookies`` is set, the Tornado web application will set the
``_xsrf`` cookie for all users and reject all ``POST``, ``PUT``, and
``DELETE`` requests that do not contain a correct ``_xsrf`` value. If
you turn this setting on, you need to instrument all forms that submit
via ``POST`` to contain this field. You can do this with the special
`.UIModule` ``xsrf_form_html()``, available in all templates::

    <form action="/new_message" method="post">
      {% module xsrf_form_html() %}
      <input type="text" name="message"/>
      <input type="submit" value="Post"/>
    </form>

If you submit AJAX ``POST`` requests, you will also need to instrument
your JavaScript to include the ``_xsrf`` value with each request. This
is the `jQuery <http://jquery.com/>`_ function we use at FriendFeed for
AJAX ``POST`` requests that automatically adds the ``_xsrf`` value to
all requests::

    function getCookie(name) {
        var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
        return r ? r[1] : undefined;
    }

    jQuery.postJSON = function(url, args, callback) {
        args._xsrf = getCookie("_xsrf");
        $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST",
            success: function(response) {
            callback(eval("(" + response + ")"));
        }});
    };

For ``PUT`` and ``DELETE`` requests (as well as ``POST`` requests that
do not use form-encoded arguments), the XSRF token may also be passed
via an HTTP header named ``X-XSRFToken``.  The XSRF cookie is normally
set when ``xsrf_form_html`` is used, but in a pure-Javascript application
that does not use any regular forms you may need to access
``self.xsrf_token`` manually (just reading the property is enough to
set the cookie as a side effect).

If you need to customize XSRF behavior on a per-handler basis, you can
override `.RequestHandler.check_xsrf_cookie()`. For example, if you
have an API whose authentication does not use cookies, you may want to
disable XSRF protection by making ``check_xsrf_cookie()`` do nothing.
However, if you support both cookie and non-cookie-based authentication,
it is important that XSRF protection be used whenever the current
request is authenticated with a cookie.

redpajama_set_name: RedPajamaGithub


text:
package com.hypertino.binders.json.bench

import scala.collection.mutable
import scala.scalajs.js.JSApp
import scala.util.control.NonFatal

case class MeasureResult(name: String, totalRuns: Long, time: Long, opsPerSec: Double)

object BenchTest extends JSApp {
  val TEST_TIME = 7000 // ms

  def main(): Unit = {
    val iterations = 3
    1 to iterations foreach { iteration ⇒
      run(iteration.toString)
    }
    println("------------------------------------------------------")
    printMeasures(measures)
  }

  def run(iteration: String): Unit = {
    val cls = new JsonBindersBenchmark
    import cls._
    println(s"Iteration: $iteration")
    measure("Binders_serializeCaseClass", Binders_serializeCaseClass)
    measure("Binders_deserializeCaseClass", Binders_deserializeCaseClass)
    measure("Binders_serializeAndDeserializeCaseClass", Binders_serializeAndDeserializeCaseClass)
    measure("Binders_serializeCaseClass2", Binders_serializeCaseClass2)
    measure("Binders_deserializeCaseClass2", Binders_deserializeCaseClass2)
    measure("Binders_serializeAndDeserializeCaseClass2", Binders_serializeAndDeserializeCaseClass2)
    measure("Binders_serializeAndDeserializeCaseClass2NoOption", Binders_serializeAndDeserializeCaseClass2NoOption)

    measure("Upickle_serializeCaseClass", Upickle_serializeCaseClass)
    measure("Upickle_deserializeCaseClass", Upickle_deserializeCaseClass)
    measure("Upickle_serializeAndDeserializeCaseClass", Upickle_serializeAndDeserializeCaseClass)
    measure("Upickle_serializeCaseClass2", Upickle_serializeCaseClass2)
    measure("Upickle_deserializeCaseClass2", Upickle_deserializeCaseClass2)
    measure("Upickle_serializeAndDeserializeCaseClass2", Upickle_serializeAndDeserializeCaseClass2)
    measure("Upickle_serializeAndDeserializeCaseClass2NoOption", Upickle_serializeAndDeserializeCaseClass2NoOption)
  }

  def alignRight(d: Double) = {
    val s = f"$d%8.4f"
    val spaces = Math.max(0, 16 - s.length)
    Seq.fill(spaces)(" ").mkString + s
  }

  val measures = mutable.ArrayBuffer[MeasureResult]()
  def measure(name: String, code: () ⇒ Unit) = {
    println(s"---------------------------------")
    println(s"Measuring: $name...")
    try {
      val before = System.currentTimeMillis()
      code()
      code()
      code()
      code()
      code()
      code()
      code()
      code()
      code()
      code()
      var after = System.currentTimeMillis()
      var totalRuns: Long = 10

      if (after - before < TEST_TIME) {
        val maxBatchSize = 1000
        val batch = if (after == before)
          maxBatchSize
        else
          Math.max(Math.min(maxBatchSize, TEST_TIME / (after - before + 1) ), 1)

        val endTime = System.currentTimeMillis() + TEST_TIME
        println(s"batch: $batch, endtime: $endTime")
        while (endTime > System.currentTimeMillis()) {
          var cnt = batch
          while (cnt > 0) {
            code()
            cnt -= 1
          }
          totalRuns += batch
        }
        after = System.currentTimeMillis()
      }
      val opsPerSec = 1.0 * totalRuns / ((after - before) / 1000.0)
      val measureResult = MeasureResult(name, totalRuns, after-before, opsPerSec)
      measures += measureResult
      println(s"Total ${measureResult.totalRuns} runs of '${measureResult.name}': for ${measureResult.time} ms. ${measureResult.opsPerSec} ops/sec")
    }
    catch {
      case NonFatal(e) ⇒
        println(e)
    }
  }

  private def printMeasures(measures: Iterable[MeasureResult]): Unit = {
    val alignLen = measures.map(_.name.length).max
    measures.foreach { m ⇒
      println(s"${m.name}${Seq.fill(alignLen - m.name.length)(" ").mkString} ${alignRight(m.opsPerSec)} ops/sec. ${m.totalRuns} cnt for ${m.time} ms")
    }
  }
}


text:
Article 810
----
Dès sa désignation, le curateur prend possession des valeurs et autres biens
détenus par des tiers et poursuit le recouvrement des sommes dues à la
succession.

Il peut poursuivre l'exploitation de l'entreprise individuelle dépendant de la
succession, qu'elle soit commerciale, industrielle, agricole ou artisanale.

Après prélèvement des frais d'administration, de gestion et de vente, il
consigne les sommes composant l'actif de la succession ainsi que les revenus des
biens et les produits de leur réalisation. En cas de poursuite de l'activité de
l'entreprise, seules les recettes qui excèdent le fonds de roulement nécessaire
au fonctionnement de celle-ci sont consignées.

Les sommes provenant à un titre quelconque d'une succession vacante ne peuvent,
en aucun cas, être consignées autrement que par l'intermédiaire du curateur.


text:
title: 'Parallelism'
---

## Normal flow

The diagram shows the normal Azure DevOps and Aggregator interaction.

{{< mermaid class="text-center">}}
sequenceDiagram
  User ->>+ AzDO : New Work Item
  AzDO -->>- User : Work Item(id=42, ver=1)

  activate Aggregator
  AzDO ->>+ Aggregator : event(workitem.created, id=42)
  Aggregator ->>+ AzDO : readWorkItem(id=42)
  AzDO -->>- Aggregator : ver=1
  Aggregator ->> DataModel : new(WorkItem, id=42, ver=1)
  Aggregator ->>+ ruleA : triggers
  ruleA ->> DataModel : get(WorkItem, id=42)

  ruleA ->> DataModel : update(WorkItem, id=42)
  ruleA -->>- Aggregator : returns
  Aggregator ->> AzDO : updateWorkItem(id=42, ver=1)
  AzDO --> Aggregator : ver=2
  deactivate Aggregator

  opt Cycle until exahustion
  activate Aggregator
  AzDO ->>+ Aggregator : event(workitem.updated, id=42, ver=2)
  Aggregator ->> DataModel : new(WorkItem, id=42, ver=2)
  Aggregator ->>+ ruleA : triggers
  ruleA ->> DataModel : get(WorkItem, id=42)
  ruleA ->> DataModel : update(WorkItem, id=42)
  ruleA -->>- Aggregator : returns
  Aggregator ->> AzDO : updateWorkItem(id=42, ver=2)
  AzDO --> Aggregator : ver=3
  deactivate Aggregator
  end
{{< /mermaid >}}

## Parallel changes

Sequence diagram showing a failing Azure DevOps and Aggregator interaction.

{{< mermaid class="text-center">}}
sequenceDiagram
  User ->>+ AzDO : New Work Item
  AzDO -->>- User : Work Item(id=42, ver=1)

  activate Aggregator
  AzDO ->>+ Aggregator : event(workitem.created, id=42)
  Aggregator ->>+ AzDO : readWorkItem(id=42)
  AzDO -->>- Aggregator : ver=1
  Aggregator ->> DataModel : new(WorkItem, id=42, ver=1)
  Aggregator ->>+ rule : triggers
  rule ->> DataModel : get(WorkItem, id=42)

  Note right of User: Same or another user
  User ->>+ AzDO : Update Work Item
  AzDO -->>- User : Work Item(id=42, ver=2)

  rule ->> DataModel : update(WorkItem, id=42)
  rule -->>- Aggregator : returns
  rect rgb(240, 120, 120)
    Aggregator -X AzDO : updateWorkItem(id=42, ver=1)
  end
  deactivate Aggregator

  activate Aggregator
    AzDO ->>+ Aggregator : event(workitem.updated, id=42, ver=2)
  deactivate Aggregator
{{< /mermaid >}}

> VS403351: Test Operation for path /rev failed

The VS403351 error happens because Aggregator adds a specific check to the JSON Patch document for the Work Item revision.

```c#
  Operation = Operation.Test,
  Path = "/rev",
  Value = item.Rev
```

It can be disabled on a _per rule_ base using the [check revision directive](../rules/directives#check-revision-directive).


text:
import { OpenApiBuilder, Server, ServerVariable } from '.';

describe('Top barrel', () => {
    it('OpenApiBuilder is exported', () => {
        const sut = OpenApiBuilder.create();
        expect(sut).not.null;
    });
    it('Server is exported', () => {
        const sut = new Server('a', 'b');
        expect(sut).not.null;
    });
    it('ServerVariable is exported', () => {
        const sut = new ServerVariable('a', ['b'], 'c');
        expect(sut).not.null;
    });
});


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!-- $Revision: 590482 $ $Date: 2007-10-31 08:51:54 +1100 (Wed, 31 Oct 2007) $ -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.geronimo.plugins</groupId>
        <artifactId>openejb</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </parent>

    <groupId>org.apache.geronimo.modules</groupId>
    <artifactId>geronimo-openejb-clustering-wadi</artifactId>
    <packaging>bundle</packaging>
    <name>Geronimo Plugins, OpenEJB :: Clustering over WADI</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.geronimo.modules</groupId>
            <artifactId>geronimo-clustering</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.modules</groupId>
            <artifactId>geronimo-clustering-wadi</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.modules</groupId>
            <artifactId>geronimo-openejb</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


text:
package models.services

import java.util.UUID

import models._
import play.api.libs.json.{ JsValue, Json }

import scala.util.Random

/**
 * Created by dylangrald on 11/13/16.
 */
object SomeRandom {

  val random = new Random()

  def double(): Double = {
    random.nextDouble()
  }

  def string(): String = {
    random.alphanumeric.take(10).mkString("")
  }

  def pointLocation(): PointLocation = {
    PointLocation(double(), double())
  }

  def pointLocationStash(): Stash = {
    stash(pointLocation())
  }

  def stash(location: Location): Stash = {
    Stash(uuidString(), uuidString(), string(), location)
  }

  def lineLocation(): LineLocation = {
    LineLocation(List(doublePair(), doublePair(), doublePair()))
  }

  def lineLocationStash(): Stash = {
    stash(lineLocation())
  }

  def polygonLocation(): PolygonLocation = {
    PolygonLocation(List(doublePair(), doublePair(), doublePair()))
  }

  def polygonLocationStash(): Stash = {
    stash(polygonLocation())
  }

  def uuidString(): String = {
    UUID.randomUUID().toString
  }

  def doublePair(): (Double, Double) = (double(), double())

  def jsonObj(): JsValue = {
    Json.obj(string() -> string())
  }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using LaunchPad2.ViewModels;

namespace LaunchPad2.Models
{
    [Serializable]
    public class GroupModel : ISerializable
    {
        private const string GroupsSerializationInfoKey = "groups";
        private const string CuesSerializationInfoKey = "cues";

        public GroupModel()
        {
        }

        public GroupModel(EventCueGroupViewModel groupViewModel, IDictionary<EventCueViewModel, string> cueSources)
        {
            var childGroups = groupViewModel.Children.OfType<EventCueGroupViewModel>();
            var childCues = groupViewModel.Children.OfType<EventCueViewModel>();

            Groups = new List<GroupModel>(childGroups.Select(childGroup => new GroupModel(childGroup, cueSources)));
            CueIds = new List<string>(childCues.Select(childCue => cueSources[childCue]));
        }

        public GroupModel(SerializationInfo info, StreamingContext context)
        {
            Groups = (List<GroupModel>) info.GetValue(GroupsSerializationInfoKey, typeof (List<GroupModel>));
            CueIds = (List<string>) info.GetValue(CuesSerializationInfoKey, typeof (List<string>));
        }

        public List<GroupModel> Groups { get; set; }

        public List<string> CueIds { get; set; }

        public EventCueGroupViewModel GetViewModel(EventCueGroupViewModel parent, IDictionary<string, EventCueViewModel> cueSources)
        {
            var groupViewModel = new EventCueGroupViewModel { Group = parent };
            var groups = Groups.Select(group => group.GetViewModel(groupViewModel, cueSources));
            var cues = CueIds.Select(cueId => cueSources[cueId]);
            var groupables = groups.Cast<IGroupable>().Union(cues).ToList();

            foreach (var group in groupables)
                group.Group = groupViewModel;

            groupViewModel.Children = new ObservableCollection<IGroupable>(groupables);

            return groupViewModel;
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(GroupsSerializationInfoKey, Groups);
            info.AddValue(CuesSerializationInfoKey, CueIds);
        }
    }
}


text:
package me.apqx.raspberrypi.util;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

/**
 * Created by chang on 2016/8/27.
 */
public class Util {
    //判断时间是否大于指定的时间
    public static boolean isOverTime(int time1,int time2,int time){
        if (time2>=time1&&time2<60){
            if ((time2-time1)<time){
                return false;
            }else {
                return true;
            }
        }else {
            if ((time2+60-time1)<time){
                return false;
            }else {
                return true;
            }
        }
    }
    //获取Android IP地址
    public static String getHostAddress(Context context){
        //获取wifi服务
        WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }
    private static String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }
    //获取两点间的距离
    public static double getDistance(int startX,int startY,int endX,int endY){
        return Math.hypot(endX-startX,endY-startY);
    }
}


text:
import {Component} from 'angular2/core';
import {RouterLink, RouteConfig, RouterOutlet} from 'angular2/router';
import {LoginComponent} from './login.component';
import {SignupComponent} from './signup.component';

@RouteConfig([
	{ path: '/login', name: 'Login', component: LoginComponent, useAsDefault: true},
	{ path: '/signup', name: 'Signup', component: SignupComponent }
])

@Component({
	selector:'mobile-app',
	directives: [RouterLink, RouterOutlet],
	template: `<router-outlet></router-outlet>`
})

export class MobileComponent {

}

// templateUrl: './components/mobileApp/mobileApp.component.html',
// styleUrls: ['./components/mobileApp/mobileApp.component.css', '../../node_modules/bootstrap/dist/css/bootstrap.css'],


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-71.js
 * @description Object.create - one property in 'Properties' is the global object that uses Object's [[Get]] method to access the 'enumerable' property (8.10.5 step 3.a)
 */

function testcase() {

        var accessed = false;

        try {
            fnGlobalObject().enumerable = true;

            var newObj = Object.create({}, {
                prop: fnGlobalObject()
            });
            for (var property in newObj) {
                if (property === "prop") {
                    accessed = true;
                }
            }
            return accessed;
        } finally {
            delete fnGlobalObject().enumerable;
        }
    }
runTestCase(testcase);


text:
class Tomify::Upload < Tomify.models.base
  include Tomify::Concerns::Upload
end


text:
function ressurectable(neighbourCount) {
  return neighbourCount === 3;
}
module.exports = ressurectable


text:
require 'active_support/concern'

# This module is only included if the order column is an integer.
module ClosureTree
  module NumericDeterministicOrdering
    extend ActiveSupport::Concern

    included do
      after_destroy :_ct_reorder_siblings
    end

    def _ct_reorder_prior_siblings_if_parent_changed
      as_5_1 = ActiveSupport.version >= Gem::Version.new('5.1.0')
      change_method = as_5_1 ? :saved_change_to_attribute? : :attribute_changed?

      if public_send(change_method, _ct.parent_column_name) && !@was_new_record
        attribute_method = as_5_1 ? :attribute_before_last_save : :attribute_was

        was_parent_id = public_send(attribute_method, _ct.parent_column_name)
        _ct.reorder_with_parent_id(was_parent_id)
      end
    end

    def _ct_reorder_siblings(minimum_sort_order_value = nil)
      _ct.reorder_with_parent_id(_ct_parent_id, minimum_sort_order_value)
      reload unless destroyed?
    end

    def _ct_reorder_children(minimum_sort_order_value = nil)
      _ct.reorder_with_parent_id(_ct_id, minimum_sort_order_value)
    end

    def self_and_descendants_preordered
      # TODO: raise NotImplementedError if sort_order is not numeric and not null?
      join_sql = <<-SQL
        JOIN #{_ct.quoted_hierarchy_table_name} anc_hier
          ON anc_hier.descendant_id = #{_ct.quoted_hierarchy_table_name}.descendant_id
        JOIN #{_ct.quoted_table_name} anc
          ON anc.#{_ct.quoted_id_column_name} = anc_hier.ancestor_id
        JOIN #{_ct.quoted_hierarchy_table_name} depths
          ON depths.ancestor_id = #{_ct.quote(self.id)} AND depths.descendant_id = anc.#{_ct.quoted_id_column_name}
      SQL

      self_and_descendants
        .joins(join_sql)
        .group("#{_ct.quoted_table_name}.#{_ct.quoted_id_column_name}")
        .reorder(self.class._ct_sum_order_by(self))
    end

    module ClassMethods

      # If node is nil, order the whole tree.
      def _ct_sum_order_by(node = nil)
        stats_sql = <<-SQL.squish
          SELECT
            count(*) as total_descendants,
            max(generations) as max_depth
          FROM #{_ct.quoted_hierarchy_table_name}
        SQL
        stats_sql += " WHERE ancestor_id = #{_ct.quote(node.id)}" if node
        h = _ct.connection.select_one(stats_sql)

        depth_column = node ? 'depths.generations' : 'depths.max_depth'

        node_score = "(1 + anc.#{_ct.quoted_order_column(false)}) * " +
          "power(#{h['total_descendants']}, #{h['max_depth'].to_i + 1} - #{depth_column})"

        # We want the NULLs to be first in case we are not ordering roots and they have NULL order.
        Arel.sql("SUM(#{node_score}) IS NULL DESC, SUM(#{node_score})")
      end

      def roots_and_descendants_preordered
        if _ct.dont_order_roots
          raise ClosureTree::RootOrderingDisabledError.new("Root ordering is disabled on this model")
        end

        join_sql = <<-SQL.squish
          JOIN #{_ct.quoted_hierarchy_table_name} anc_hier
            ON anc_hier.descendant_id = #{_ct.quoted_table_name}.#{_ct.quoted_id_column_name}
          JOIN #{_ct.quoted_table_name} anc
            ON anc.#{_ct.quoted_id_column_name} = anc_hier.ancestor_id
          JOIN (
            SELECT descendant_id, max(generations) AS max_depth
            FROM #{_ct.quoted_hierarchy_table_name}
            GROUP BY descendant_id
          ) #{ _ct.t_alias_keyword } depths ON depths.descendant_id = anc.#{_ct.quoted_id_column_name}
        SQL
        joins(join_sql)
          .group("#{_ct.quoted_table_name}.#{_ct.quoted_id_column_name}")
          .reorder(_ct_sum_order_by)
      end
    end

    def append_child(child_node)
      add_child(child_node)
    end

    def prepend_child(child_node)
      child_node.order_value = -1
      child_node.parent = self
      child_node._ct_skip_sort_order_maintenance!
      if child_node.save
        _ct_reorder_children
        child_node.reload
      else
        child_node
      end
    end

    def append_sibling(sibling_node)
      add_sibling(sibling_node, true)
    end

    def prepend_sibling(sibling_node)
      add_sibling(sibling_node, false)
    end

    def add_sibling(sibling, add_after = true)
      fail "can't add self as sibling" if self == sibling

      if _ct.dont_order_roots && parent.nil?
        raise ClosureTree::RootOrderingDisabledError.new("Root ordering is disabled on this model")
      end

      # Make sure self isn't dirty, because we're going to call reload:
      save

      _ct.with_advisory_lock do
        prior_sibling_parent = sibling.parent
        reorder_from_value = if prior_sibling_parent == self.parent
          [self.order_value, sibling.order_value].compact.min
        else
          self.order_value
        end

        sibling.order_value = self.order_value
        sibling.parent = self.parent
        sibling._ct_skip_sort_order_maintenance!
        sibling.save # may be a no-op

        _ct_reorder_siblings(reorder_from_value)

        # The sort order should be correct now except for self and sibling, which may need to flip:
        sibling_is_after = self.reload.order_value < sibling.reload.order_value
        if add_after != sibling_is_after
          # We need to flip the sort orders:
          self_ov, sib_ov = self.order_value, sibling.order_value
          update_order_value(sib_ov)
          sibling.update_order_value(self_ov)
        end

        if prior_sibling_parent != self.parent
          prior_sibling_parent.try(:_ct_reorder_children)
        end
        sibling
      end
    end
  end
end


text:
package org.simpleframework.xml.transform;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.simpleframework.xml.transform.Transform;

class DateFormatter implements Transform<Date> {

   private AtomicInteger count;

   private TaskQueue queue;

   private String format;

   public DateFormatter(String format) {
      this(format, 10);
   }

   public DateFormatter(String format, int count) {
      this.count = new AtomicInteger(count);
      this.queue = new TaskQueue(count);
      this.format = format;
   }

   public Date read(String value) throws Exception {
      return borrow().read(value);
   }

   public String write(Date value) throws Exception {
      return borrow().write(value);
   }

   private Task borrow() throws InterruptedException {
      int size = count.get();

      if(size > 0) {
         int next = count.getAndDecrement();

         if(next > 0) {
            return new Task(format);
         }
      }
      return queue.take();
   }

   private void release(Task task) {
      queue.offer(task);
   }

   private class Task {

      private SimpleDateFormat format;

      public Task(String format) {
         this.format = new SimpleDateFormat(format);
      }

      public Date read(String value) throws ParseException {
         try {
            return format.parse(value);
         } finally {
            release(this);
         }
      }

      public String write(Date value) {
         try {
            return format.format(value);
         } finally {
            release(this);
         }
      }
   }

   private class TaskQueue extends LinkedBlockingQueue<Task> {

      public TaskQueue(int size) {
         super(size);
      }
   }
}


text:
function HttpError(message, statusCode) {
  this.name = 'HttpError';
  this.message = message || 'HTTP Error';
  this.statusCode = statusCode;
}

HttpError.prototype = new Error();

HttpError.prototype.constructor = HttpError;

HttpError.prototype.toString = function() {
  if (this.statusCode) {
    var msg = 'StatusCode: ' + this.statusCode + '\n';
    return msg + Error.prototype.toString.call(this);
  }
  return Error.prototype.toString.call(this);
};

var error = (function() {
  'use strict';

  var error = {
    httpError: function(statusCode, message) {
      return new HttpError(message, statusCode);
    },

    throwHttpError: function(statusCode, message) {
      throw this.httpError(statusCode, message);
    }
  };

  return error;

}());

module.exports = error;


text:
package com.flexdms.flexims.users;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.eclipse.persistence.dynamic.DynamicEntity;

import com.flexdms.flexims.App;
import com.flexdms.flexims.jpa.JpaHelper;
import com.flexdms.flexims.jpa.eclipselink.FleximsDynamicEntityImpl;

public class FxUser extends FxRole {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	public static final String SESSION_USER_KEY = "fxuser";
	public static final String TYPE_NAME = "FxUser";

	public FxUser() {
		super();
	}

	public FxUser(FleximsDynamicEntityImpl entityImpl) {
		super(entityImpl);
	}

	public String getEmail() {
		return getUserSettings().getEmail();
	}

	public String getPassword() {
		return getUserSettings().getPassword();
	}

	public FxUser setEmail(String value) {
		getUserSettings().setEmail(value);
		return this;
	}

	public FxUser setPassword(String value) {
		getUserSettings().setPassword(value);
		return this;
	}

	FxUserSettings settings = null;

	public FxUserSettings getUserSettings() {
		if (settings == null) {
			settings = loadBy(App.getEM());

		}
		return settings;
	}

	public static FxUser loadByEmail(EntityManager em, String email) {
		TypedQuery<? extends DynamicEntity> jplquery = em.createQuery("select s from FxUserSettings s where s.Email= :email",
				JpaHelper.getEntityClass(em, "FxUserSettings"));
		jplquery.setParameter("email", email);
		List<? extends DynamicEntity> list = jplquery.getResultList();
		if (list == null || list.isEmpty()) {
			return null;
		}
		FxUserSettings settings = new FxUserSettings((FleximsDynamicEntityImpl) list.get(0));
		FxUser user = new FxUser((FleximsDynamicEntityImpl) settings.getEntityImpl().get(FxUserSettings.PROP_NAME_PROP_USER));
		user.settings = settings;
		return user;

	}
	public static FxUser loadById(EntityManager em, long id) {
		return new FxUser((FleximsDynamicEntityImpl) em.find(JpaHelper.getEntityClass(em, FxUser.TYPE_NAME), id));
	}

	public FxUserSettings loadBy(EntityManager em) {
		TypedQuery<? extends DynamicEntity> jplquery = em.createQuery("select s from FxUserSettings s where s.FxUser= :fxUser",
				JpaHelper.getEntityClass(em, "FxUserSettings"));
		jplquery.setParameter("fxUser", this.getEntityImpl());
		return new FxUserSettings((FleximsDynamicEntityImpl) jplquery.getSingleResult());

	}

	public static FxUser createUser(EntityManager em) {

		FleximsDynamicEntityImpl user = JpaHelper.createNewEntity(em, FxUser.TYPE_NAME);
		FleximsDynamicEntityImpl settings = JpaHelper.createNewEntity(em, FxUserSettings.TYPE_NAME);
		settings.set(FxUserSettings.PROP_NAME_PROP_USER, user);
		FxUser fxUser = new FxUser(user);
		FxUserSettings fxUserSettings = new FxUserSettings(settings);
		fxUser.settings = fxUserSettings;
		return fxUser;
	}
}


text:
package org.idreambox.pageModel;

public class Json implements java.io.Serializable {

	private static final long serialVersionUID = 7349672284757602670L;

	private boolean success = false;

	private String msg = "";

	private Object obj = null;

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

}


text:
from pywps import Service
from .common import client_for
from flyingpigeon.processes import processes

def test_wps_caps():
    client = client_for(Service(processes=processes))
    resp = client.get(service='wps', request='getcapabilities', version='1.0.0')
    names = resp.xpath_text('/wps:Capabilities'
                            '/wps:ProcessOfferings'
                            '/wps:Process'
                            '/ows:Identifier')
    assert sorted(names.split()) == [
        'climatechange_signal',
        'plot_map_timemean',
        'plot_spaghetti',
        'plot_spatial_analog',
        'plot_uncertainty',
        'plot_uncertaintyrcp',
        'pointinspection',
        'robustness_statistic',
        'spatial_analog',
        'subset-wfs-polygon',
        'subset_bbox',
        'subset_continents',
        'subset_countries',
    ]


text:
var connect      = require('gulp-connect'),
    gulp         = require('gulp'),
    gulpif       = require('gulp-if'),
    handleErrors = require('./handleErrors'),
    exitProcess  = require('./exitProcess'),
    sass         = require('gulp-sass'),
    sourcemaps   = require('gulp-sourcemaps');

/**
 * Compile css from scss files.
 * This will generate one unique output file (main.scss) according to several options :
 * - options.compress :
 *      Compress generated file's content (this will reduce the size of the file)
 * - options.sourceMaps :
 *      Generate a .map file (for debugging purpose only)
 */
var sassTask = function(exit, options) {
    return gulp.src('./demo/main.scss')
        .pipe(gulpif(options.sourceMaps, sourcemaps.init()))
        .pipe(sass({
            outputStyle: gulpif(options.compress, "compressed", "nested"),
            precision: 10
        }))
        .on('error', handleErrors)
        .on('error', exitProcess(exit))
        .pipe(gulpif(options.sourceMaps, sourcemaps.write('.')))
        .pipe(gulp.dest('./demo/build/css/'))
        .pipe(connect.reload());
};

gulp.task('sass', function (done) {
    sassTask(true, {
        compress: true,
        sourceMaps: false
    });
    done();
});

gulp.task('sass-dev', function (done) {
    sassTask(false, {
        compress: false,
        sourceMaps: true
    });
    done();
});


text:
package net.yslibrary.photosearcher.model.entity;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Created by yshrsmz on 15/08/29.
 */
public class SearchQuery extends RealmObject {

    @PrimaryKey
    private String query;

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }
}


text:
configs=$(mktemp)
#for config in /usr/share/openvpn/nordvpn/*.ovpn; do
  ## This works, but takes a LONG time
  #basename "$config" ".ovpn" >> "$configs"
#done
#find /usr/share/openvpn/nordvpn -exec echo {} +
countries=$(grep -o "^[a-x][a-x]" "$configs")
country=$(cat "$countries" | dmenu -i)
selection=$(cat "$configs" | dmenu -i)


text:
@implementation UIImage (extension)
- (void)was_roundImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor opaque:(BOOL)opaque completion:(void (^)(UIImage *))completion {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

//        NSTimeInterval start = CACurrentMediaTime();

        // 1. 利用绘图,建立上下文 BOOL选项为是否为不透明
        UIGraphicsBeginImageContextWithOptions(size, opaque, 0);

        CGRect rect = CGRectMake(0, 0, size.width, size.height);

        // 2. 设置填充颜色
        if (opaque) {
            [fillColor setFill];
            UIRectFill(rect);
        }

        // 3. 利用 贝赛尔路径 `裁切 效果
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];

        [path addClip];

        // 4. 绘制图像 如果图片为空那么为单色渲染
        if (self) {
            [self drawInRect:rect];
        }

        // 5. 取得结果
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

        // 6. 关闭上下文
        UIGraphicsEndImageContext();

//        NSLog(@"%f", CACurrentMediaTime() - start);

        // 7. 完成回调
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(result);
            }
        });
    });
}

//圆角矩形
- (void)was_roundRectImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor opaque:(BOOL)opaque radius:(CGFloat)radius completion:(void (^)(UIImage *))completion {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        //        NSTimeInterval start = CACurrentMediaTime();

        // 1. 利用绘图,建立上下文 BOOL选项为是否为不透明
        UIGraphicsBeginImageContextWithOptions(size, opaque, 0);

        CGRect rect = CGRectMake(0, 0, size.width, size.height);

        // 2. 设置填充颜色
        if (opaque) {
            [fillColor setFill];
            UIRectFill(rect);
        }

        // 3. 利用 贝赛尔路径 `裁切 效果
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
//        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];

        [path addClip];

        // 4. 绘制图像
        if (self) {
            [self drawInRect:rect];
        }

        // 5. 取得结果
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

        // 6. 关闭上下文
        UIGraphicsEndImageContext();

        //        NSLog(@"%f", CACurrentMediaTime() - start);

        // 7. 完成回调
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(result);
            }
        });
    });
}

@end

#pragma mark - UIImageView
@implementation UIImageView (Extension)
//圆
- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color{
    [self was_setCircleImageWithUrlString:urlString placeholder:image fillColor:color opaque:color];
}

//网络延迟下载--圆形 背景色为透明 无背景色
- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image{
    [self was_setCircleImageWithUrlString:urlString placeholder:image fillColor:nil opaque:NO];
}

//圆形矩阵
- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color cornerRadius:(CGFloat) cornerRadius{
    [self was_setRoundRectImageWithUrlString:urlString placeholder:image fillColor:color opaque:color cornerRadius:cornerRadius];
}

//网络延迟下载--圆形矩阵 背景色为透明 无背景色
- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image cornerRadius:(CGFloat) cornerRadius{
    [self was_setRoundRectImageWithUrlString:urlString placeholder:image fillColor:nil opaque:NO cornerRadius:cornerRadius];
}

- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color opaque:(BOOL)opaque{
    [self.superview layoutIfNeeded];
    NSURL *url = [NSURL URLWithString:urlString];
    //防止循环引用
    __weak typeof(self) weakSelf = self;
    CGSize size = self.frame.size;

    if (image) {
        //占位图片不为空的情况
        //1.现将占位图圆角化,这样就避免了如图片下载失败,使用占位图的时候占位图不是圆角的问题
        [image was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusPlaceHolder) {

            //2.使用sd的方法缓存异步下载的图片
            [weakSelf sd_setImageWithURL:url placeholderImage:radiusPlaceHolder completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

                //3.如果下载成功那么讲下载成功的图进行圆角化
                [img was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusImage) {
                    weakSelf.image = radiusImage;
                }];

            }];

        }];
    } else {
        //占位图片为空的情况
        //2.使用sd的方法缓存异步下载的图片
        [weakSelf sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

            //3.如果下载成功那么讲下载成功的图进行圆角化
            [img was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusImage) {
                weakSelf.image = radiusImage;
            }];
        }];
    }
}

- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color opaque:(BOOL)opaque cornerRadius:(CGFloat) cornerRadius{
    [self.superview layoutIfNeeded];
    NSURL *url = [NSURL URLWithString:urlString];
    //防止循环引用
    __weak typeof(self) weakSelf = self;
    CGSize size = self.frame.size;

    if (image) {
        //占位图片不为空的情况
        //1.现将占位图圆角化,这样就避免了如图片下载失败,使用占位图的时候占位图不是圆角的问题
        [image was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *roundRectPlaceHolder) {

            //2.使用sd的方法缓存异步下载的图片
            [weakSelf sd_setImageWithURL:url placeholderImage:roundRectPlaceHolder completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

                //3.如果下载成功那么讲下载成功的图进行圆角化
                [img was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *radiusImage) {
                    weakSelf.image = radiusImage;
                }];

            }];

        }];
    } else {
        //占位图片为空的情况
        //.使用sd的方法缓存异步下载的图片
        [weakSelf sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

            //3.如果下载成功那么讲下载成功的图进行圆角化
            [img was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *radiusImage) {
                weakSelf.image = radiusImage;
            }];
        }];
    }
}

@end

#pragma mark - UIButton

@implementation UIButton (Extension)
//圆形
- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color forState:(UIControlState)state {
    [self was_setCircleImageWithUrlString:urlString placeholder:image fillColor:color opaque:color forState:state];
}

//button--圆形    背景为透明 无背景色
- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image forState:(UIControlState)state{
    [self was_setCircleImageWithUrlString:urlString placeholder:image fillColor:nil opaque:NO forState:state];
}

//圆角矩阵
- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color cornerRadius:(CGFloat) cornerRadius forState:(UIControlState)state{

    [self was_setRoundRectImageWithUrlString:urlString placeholder:image fillColor:color opaque:color cornerRadius:cornerRadius forState:state];
}

//button--圆角矩形 背景为透明 无背景色
- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image cornerRadius:(CGFloat) cornerRadius forState:(UIControlState)state{
    [self was_setRoundRectImageWithUrlString:urlString placeholder:image fillColor:nil opaque:NO cornerRadius:cornerRadius forState:state];
}

- (void)was_setRoundRectImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color opaque:(BOOL)opaque cornerRadius:(CGFloat) cornerRadius forState:(UIControlState)state{
    NSURL *url = [NSURL URLWithString:urlString];
    [self.superview layoutIfNeeded];
    __weak typeof(self) weakSelf = self;
    CGSize size = self.frame.size;

    if (image) {
        //占位图片不为空的情况
        //占位处理
        [image was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *roundRectPlaceHolder) {
            //sd
            [weakSelf sd_setImageWithURL:url forState:state placeholderImage:roundRectPlaceHolder completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //3.如果下载成功那么讲下载成功的图进行圆角化
                [img was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *roundRectImage) {
                    [weakSelf setImage:roundRectImage forState:state];
                }];

            }];

        }];
    } else {
        //占位图片为空的情况
        [weakSelf sd_setImageWithURL:url forState:state placeholderImage:nil completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            //3.如果下载成功那么讲下载成功的图进行圆角化
            [img was_roundRectImageWithSize:size fillColor:color opaque:opaque radius:cornerRadius completion:^(UIImage *roundRectImage) {
                [weakSelf setImage:roundRectImage forState:state];
            }];

        }];
    }

}

- (void)was_setCircleImageWithUrlString:(NSString *)urlString placeholder:(UIImage *)image fillColor:(UIColor *)color opaque:(BOOL)opaque forState:(UIControlState)state{
    NSURL *url = [NSURL URLWithString:urlString];
    [self.superview layoutIfNeeded];
    __weak typeof(self) weakSelf = self;
    CGSize size = self.frame.size;

    if (image) {
        //占位图片不为空的情况
        //占位处理
        [image was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusPlaceHolder) {
            //sd
            [weakSelf sd_setImageWithURL:url forState:state placeholderImage:radiusPlaceHolder completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //3.如果下载成功那么讲下载成功的图进行圆角化
                [img was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusImage) {
                    [weakSelf setImage:radiusImage forState:state];
                }];

            }];

        }];
    } else {
        //占位图片为空的情况
        [weakSelf sd_setImageWithURL:url forState:state placeholderImage:nil completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            //3.如果下载成功那么讲下载成功的图进行圆角化
            [img was_roundImageWithSize:size fillColor:color opaque:opaque completion:^(UIImage *radiusImage) {
                [weakSelf setImage:radiusImage forState:state];
            }];

        }];
    }

}
@end


text:
export JSONWS_USERNAME=""
export JSONWS_PASSWORD=""
export MYSQL_USER=""
export MYSQL_PASSWORD=""


text:
import os
import sys
import subprocess
# Only allows a single process to run at a time in windows.
# Allows as many as you want elsewhere.
# First parameter is lock name the rest are the program arguments

if os.name == 'nt':
  from ctypes import *
  _create_mutex = windll.kernel32.CreateMutexA
  _wait_for_single_object = windll.kernel32.WaitForSingleObject
  _release_mutex = windll.kernel32.ReleaseMutex
  mutex = _create_mutex(None, False, sys.argv[1])
  if not mutex:
    raise("Could not create mutex")
  _wait_for_single_object(mutex, -1)
  print "-----------------------"
  print sys.argv
  print "-----------------------"
  try:
    print sys.argv[2:]
    subprocess.check_call(sys.argv[2:])
    pass
  except Exception as e:
    _release_mutex(mutex)
    raise e
  _release_mutex(mutex)
else:
  subprocess.check_call(sys.argv[2:])


text:
package de.wellenvogel.avnav.aislib.model;

/**
 * Created by andreas on 28.12.14.
 */
public class Position {
    private double longitude;
    private double latitude;
    public Position(double lat,double lon){
        latitude=lat;
        longitude=lon;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }
    public static boolean isValid(double latitude, double longitude) {
        return latitude <= 90 && latitude >= -90 && longitude <= 180 && longitude >= -180;
    }
    public static Position create( double latitude, double longitude) {
        return new Position(latitude, longitude);
    }
}


text:
import sys
import os

HERE='.'
LIBS=os.path.abspath(HERE + '/libs')

print(LIBS)
sys.path.append(LIBS)

import custommodules
from   custommodules import basemodule as B

B.info()


text:
FOUNDATION_EXPORT double TransitioningVersionNumber;

//! Project version string for Transitioning.
FOUNDATION_EXPORT const unsigned char TransitioningVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Transitioning/PublicHeader.h>


text:
**UPDATE**: _converting to flexboxes for maximum UI flexibility, see flex branch for latest changes.  Will release soon_

Highlights an array of instructions.  Glows.  Is somewhat efficient.  Uses [highlight.js](https://highlightjs.org/).

Example:

````html
<silicon-instructions instructions="[[instructions]]"></silicon-instructions>
````

Works well with [silicon-disassembler](http://github.com/m4b/silicon-disassembler).

See [documentation](http://m4b.github.io/silicon-instructions) for more information and a demo.

# TODO

* Allow memory on/off option?


text:
/**
 * @author Eugenio Depalo
 */
Grid.prototype = new Shape;
Grid.prototype.constructor = Grid;

function Grid(properties){
    this.lines = properties.lines;
    this.unit = properties.unit;

	properties.sortable = false;

    Shape.apply(this, arguments);
}

Grid.prototype.updatePolygons = function(){
    var gridStyle = {
        stroke: "#ccc"
    };

    var origin = this.unit * (this.lines - 1) / 2;

    for (var i = 0; i < this.lines; i++) {
        this.polygons.push(new Polygon([Vector.create([i * this.unit - origin, -origin, 0]),
										Vector.create([i * this.unit - origin, origin, 0])], gridStyle));

        this.polygons.push(new Polygon([Vector.create([-origin, i * this.unit - origin, 0]),
										Vector.create([origin, i * this.unit - origin, 0])], gridStyle));
    }
}


text:
/* Bedework Access control form functions

   Bedework sets access control by building a javascript object representing
   the acls on an item (e.g. an event), manipulating the object with the GUI, and
   sending all the acls in a single request parameter.  We would like to replace
   this approach with wizards that ask the user what they want to do (and hide
   the acls).

*/

// ========================================================================
//   Default strings are English (en_US).  Tranlations are found in
//   the sibling directory lang/ and are included as overrides based on the localeSettings.xsl
//   file for each web client (that uses a localeSettings file, e.g. the personal
//   and public web clients

var authenticatedStr = "authenticated";
var unauthenticatedStr = "unauthenticated";
var ownerStr = "owner";
var otherStr = "other";
var grantStr = "grant";
var denyStr = "deny"
var allStr = "all";

var bwAclWidgetDeleteStr = "remove";
var bwAclWidgetEntryStr = "Entry";
var bwAclWidgetAccessStr = "Access";
var bwAclWidgetInheritedStr = "Inherited from";

// note that resourcesRoot is passed in from the html head section defined in the xslt
var trashIcon = '';
var userIcon = '';
var groupIcon = '';

// How granted accesses appear
var howAllVal = "all";

var howReadVal = "read";
var howReadAclVal = "read-acl";
var howReadCurPrivSetVal = "read-curprivset";
var howReadFreebusyVal = "read-freebusy ";

var howWriteVal = "write";
var howWriteAclVal = "write-acl";
var howWritePropertiesVal = "write-properties";
var howWriteContentVal = "write-content";

var howBindVal = "create";

/* Old scheduling */
var howScheduleVal = "schedule";
var howScheduleRequestVal = "schedule-request";
var howScheduleReplyVal = "schedule-reply";
var howScheduleFreebusyVal = "schedule-freebusy";

var howUnbindVal = "delete";

var howUnlockVal = "unlock";

var howScheduleDeliverVal = "schedule-deliver";
var howScheduleDeliverInviteVal = "schedule-deliver-invite";
var howScheduleDeliverReplyVal = "schedule-deliver-reply";
var howScheduleQueryFreebusyVal = "schedule-query-freebusy";

var howScheduleSendVal = "schedule-send";
var howScheduleSendInviteVal = "schedule-send-invite";
var howScheduleSendReplyVal = "schedule-send-reply";
var howScheduleSendFreebusyVal = "schedule-send-freebusy";

// How denied accesses appear
var howDenyAllVal = "none";

var howDenyReadVal = "not-read";
var howDenyReadAclVal = "not-read-acl";
var howDenyReadCurPrivSetVal = "not-read-curprivset";
var howDenyReadFreebusyVal = "not-read-freebusy ";

var howDenyWriteVal = "not-write";
var howDenyWriteAclVal = "not-write-acl";
var howDenyWritePropertiesVal = "not-write-properties";
var howDenyWriteContentVal = "not-write-content";

var howDenyBindVal = "not-create";
var howDenyScheduleVal = "not-schedule";
var howDenyScheduleRequestVal = "not-schedule-request";
var howDenyScheduleReplyVal = "not-schedule-reply";
var howDenyScheduleFreebusyVal = "not-schedule-freebusy";

var howDenyUnbindVal = "not-delete";

var howDenyUnlockVal = "not-unlock";

var howDenyScheduleDeliverVal = "not-schedule-deliver";
var howDenyScheduleDeliverInviteVal = "not-schedule-deliver-invite";
var howDenyScheduleDeliverReplyVal = "not-schedule-deliver-reply";
var howDenyScheduleQueryFreebusyVal = "not-schedule-query-freebusy";

var howDenyScheduleSendVal = "not-schedule-send";
var howDenyScheduleSendInviteVal = "not-schedule-send-invite";
var howDenyScheduleSendReplyVal = "not-schedule-send-reply";
var howDenyScheduleSendFreebusy = "not-schedule-send-freebusy";

//var howNoneVal = "none";

/* We shouldn't use the word local - it probably doesn't mean too much and it might actually be
   inherited from something called /local for example */
var inheritedStr = "not inherited";

// **************************
// The prefixes come from the directory code so should be emitted by the jsp.
// We may have problems here as convertng from a user id to a principal might be
// awkward

var principalPrefix = "/principals/";
var userPrincipalPrefix = "/principals/users/";
var groupPrincipalPrefix = "/principals/groups/";
var resourcePrincipalPrefix = "/principals/resources/";

// ========================================================================
// ========================================================================

// .......................................................
// Some constants
// .......................................................

var xmlHeader = "<?xml version='1.0' encoding='utf-8'  ?>";
var nameSpaces = "xmlns:D='DAV:' " +
                 "xmlns:C='urn:ietf:params:xml:ns:caldav'";

var davNS = "D:";
var caldavNS = "C:";

/* Define how values,
    par: how,
    par: the contained hows
    par: dav element name
    par: display name */
function howVals(h, cont, davEl, dv, ddv) {
  var how;
  var contains;
  var davEl;
  var dispVal;
  var denyDispVal;

  this.how = h;
  this.contains = cont;
  this.davEl = davEl;
  this.dispVal = dv;
  this.denyDispVal = ddv;

  /* return true if ch is contained in this access */
  this.doesContain = function(ch) {
    return this.contains.match(ch) != null;
  }

  this.getDispVal = function(negated) {
    if (negated) {
      return this.denyDispVal;
    }

    return this.dispVal;
  }
}

var hows = new function() {
  var hv = new Array();

  hv.push(new howVals("A", "RrPFWapcbStysuNDieqTIEQ", "<D:all/>", howAllVal, howDenyAllVal));

  hv.push(new howVals("R", "rPF", "<D:read/>", howReadVal, howDenyReadVal));
  hv.push(new howVals("r", "", "<D:read-acl/>", howReadAclVal, howDenyReadAclVal));
  hv.push(new howVals("P", "", "<D:read-current-user-privilege-set/>", howReadCurPrivSetVal, howDenyReadCurPrivSetVal));
  hv.push(new howVals("F", "", "<C:read-free-busy/>", howReadFreebusyVal, howDenyReadFreebusyVal));

  hv.push(new howVals("W", "apcbStysuN", "<D:write/>", howWriteVal, howDenyWriteVal));
  hv.push(new howVals("a", "", "<D:write-acl/>", howWriteAclVal, howDenyWriteAclVal));
  hv.push(new howVals("p", "", "<D:write-properties/>", howWritePropertiesVal, howDenyWritePropertiesVal));
  hv.push(new howVals("c", "", "<D:write-content/>", howWriteContentVal, howDenyWriteContentVal));
  hv.push(new howVals("b", "Stys", "<D:bind/>", howBindVal, howDenyBindVal));

  /* Old caldav sched - should disallow use */
  hv.push(new howVals("S", "tys", "<C:schedule/>", howScheduleVal, howDenyScheduleVal));
  hv.push(new howVals("t", "", "<C:schedule-request/>", howScheduleRequestVal, howDenyScheduleRequestVal));
  hv.push(new howVals("y", "", "<C:schedule-reply/>", howScheduleReplyVal, howDenyScheduleReplyVal));
  hv.push(new howVals("s", "", "<C:schedule-free-busy/>", howScheduleFreebusyVal, howDenyScheduleFreebusyVal));

  hv.push(new howVals("u", "", "<D:unbind/>", howUnbindVal, howDenyUnbindVal));

  hv.push(new howVals("U", "", "<D:unlock/>", howUnlockVal, howDenyUnlockVal));

  hv.push(new howVals("D", "ieq", "<C:schedule-deliver/>",
      howScheduleDeliverVal, howDenyScheduleDeliverVal));
  hv.push(new howVals("i", "", "<C:schedule-deliver-invite/>",
      howScheduleDeliverInviteVal, howDenyScheduleDeliverInviteVal));
  hv.push(new howVals("e", "", "<C:schedule-deliver-reply/>",
      howScheduleDeliverReplyVal, howDenyScheduleDeliverReplyVal));
  hv.push(new howVals("q", "", "<C:schedule-query-freebusy/>",
      howScheduleQueryFreebusyVal, howDenyScheduleQueryFreebusyVal));

  hv.push(new howVals("T", "IEQ", "<C:schedule-send/>",
      howScheduleSendVal, howDenyScheduleSendVal));
  hv.push(new howVals("I", "", "<C:schedule-send-invite/>",
      howScheduleSendInviteVal, howDenyScheduleSendInviteVal));
  hv.push(new howVals("E", "", "<C:schedule-send-reply/>",
      howScheduleSendReplyVal, howDenyScheduleSendReplyVal));
  hv.push(new howVals("Q", "", "<C:schedule-send-freebusy/>",
      howScheduleSendFreebusyVal, howDenyScheduleSendFreebusy));

  //hv.push(new howVals("N", "rPFapcbStysu", "", howNoneVal)); // None is -A

  this.getHows = function(ch) {
    for (var i = 0; i < hv.length; i++) {
      if (hv[i].how == ch) {
        return hv[i];
      }
    }

    alert("No how values for how = " + ch);

    return null;
  }
}

function setupAccessForm(chkBoxObj, formObj) {
  var hvs;  // howVals

  /* If we checked/unchecked a value that contains other values we need
     to uncheck and disable the contained boxes. */

  hvs = hows.getHows(chkBoxObj.value);

  if (hvs.contains == "") {
    // Doesn't contain anything
    return;
  }

  for (i = 0; i < formObj.howItem.length; i++) {
    if (hvs.doesContain(formObj.howItem[i].value)) {
      if (chkBoxObj.checked == true) {
        formObj.howItem[i].checked = false;
        formObj.howItem[i].disabled = true;
        // now iterate over corresponding radio buttons for each howItem
        for (j = 0; j < formObj[formObj.howItem[i].id].length; j++) {
          formObj[formObj.howItem[i].id][j].disabled = true;
        }
      } else {
        formObj.howItem[i].disabled = false;
      }
    }
  }
}

// enable and disable corresponding allow/deny flags when a howItem checkbox is
// clicked
function toggleAllowDenyFlag(chkBoxObj,formObj) {
  if (chkBoxObj.checked == true) {
    activateAllowDenyFlag(chkBoxObj.id, formObj, false);
  } else {
    activateAllowDenyFlag(chkBoxObj.id, formObj, true);
  }
}

// iterate over the allow/deny radio buttons and set them to true or false
function activateAllowDenyFlag(val,formObj,disabledFlag) {
  for (i = 0; i < formObj[val].length; i++) {
    if (formObj[val][i].type == "radio") { //skip the checkbox with matching id
      formObj[val][i].disabled = disabledFlag;
    }
  }
}

// Gather up the how values on access form submission and return the value.
// If in "basic" mode:
//   Set the value of how to the value of the basicHowItem radio button.
// If in "advanced" mode:
//   Each howItem (checkbox) has a corresponding allow/deny flag (radio button)
//   named after the howItem's value (e.g. "A","R","F","N", etc).
//   The allow/deny flag contains the final values to be returned with
//   the "-" switch if we set the value to deny (e.g. "A" or "-A", "R" or "-R").
function setAccessHow(formObj) {
  var howString = "";
  if (formObj.setappvar[0].checked == true) { // "basic" mode is selected
    for (i = 0; i < formObj.basicHowItem.length; i++) {
      if (formObj.basicHowItem[i].checked == true) {
        howString = formObj.basicHowItem[i].value;
      }
    }
  } else { // "advanced" mode is selected
    for (i = 0; i < formObj.howItem.length; i++) {
      if (formObj.howItem[i].checked == true) {
        var howItemId = formObj.howItem[i].id; // get the howItem id and
        for (j = 0; j < formObj[howItemId].length; j++) { // look up the value from the corresponding allow/deny flag
          if ((formObj[howItemId][j].checked == true) && (formObj[howItemId][j].type == "radio")) {
            howString += formObj[howItemId][j].value;
          }
        }
      }
    }
  }
  return howString;
}

/* Information about a principal
 */
function bwPrincipal(who, whoType) {
  this.whoType = whoType;

  if ((whoType == "auth") ||
      (whoType == "unauth") ||
      (whoType == "owner") ||
      (whoType == "all") ||
      (whoType == "other")) {
    // Don't set who
  } else {
    this.who = who;

    // Don't touch email like addresses
//    if (who.indexOf("@") < 0) {
      // Normalize the who
      if (whoType == "user") {
        if (who.indexOf(principalPrefix) != "0") {
          who = userPrincipalPrefix + who;
        }
      } else if (whoType == "group") {
        if (who.indexOf(principalPrefix) != "0") {
          who = groupPrincipalPrefix + who;
        }
      } else if (whoType == "resource") {
        if (who.indexOf(principalPrefix) != "0") {
          who = resourcePrincipalPrefix + who;
        }
      }
  //  }
  }

  // format the who string for on-screen display
  this.format = function() {
    if (whoType == "user") {
      return userIcon + " " + who;
    }

    if (whoType == "group") {
      return groupIcon + " " + who;
    }

    if (whoType == "resource") {
      return who;
    }

    if (whoType == "auth") {
      return groupIcon + " " + authenticatedStr;
    }

    if (whoType == "unauth") {
      return groupIcon + " " + unauthenticatedStr;
    }

    if (whoType == "owner") {
      return userIcon + " " + ownerStr;
    }

    if (whoType == "other") {
      return groupIcon + " " + otherStr;
    }

    if (whoType == "all") {
      return groupIcon + " " + allStr;
    }

    return "***************" + whoType;
  }

  // format the who string for xml representation
  this.formatXml = function() {
    if (whoType == "user") {
      return who;
    }

    if (whoType == "group") {
      return who;
    }

    if (whoType == "resource") {
      return who;
    }

    if (whoType == "auth") {
      return authenticatedStr;
    }

    if (whoType == "unauth") {
      return unauthenticatedStr;
    }

    if (whoType == "owner") {
      return ownerStr;
    }

    if (whoType == "other") {
      return otherStr;
    }

    if (whoType == "all") {
      return allStr;
    }

    return "***************" + whoType;
  }

  this.toXml = function() {
    var w = this.formatXml();

    if (whoType == "other") {
      return "    <D:invert>\n        <D:principal><D:property><D:owner/></D:property></D:principal>\n      </D:invert>";
    }

    var res = "    <D:principal>\n";

    if (w.indexOf(principalPrefix) == "0") {
      res += "      <D:href>" + w + "</D:href>\n";
    } else if (whoType == "auth") {
      res += "      <D:authenticated/>\n";
    } else if (whoType == "unauth") {
      res += "      <D:unauthenticated/>\n";
    } else if (whoType == "all") {
      res += "      <D:all/>\n";
    } else if (whoType == "owner") {
      res += "    <D:property><D:owner/></D:property>\n";
    } else {
      res += "************??????" + whoType;
    }

    return res + "    </D:principal>\n";
  }

  this.toString = function() {
    return "bwPrincipal[who=" + this.who + ", whoType=" + this.whoType + "]";
  }

  this.equals = function(pr) {
    if (this.whoType != pr.whoType) {
      return false;
    }
    return this.who == pr.who;
  }
}

/* Access Control Entry (ACE) object
 */
function bwAce(who, whoType, how, inherited, invert) {
  this.principal = new bwPrincipal(who, whoType);
  this.how = how;
  this.inherited = inherited;
  this.invert = invert; // boolean

  this.equals = function(ace) {
    return this.principal.equals(ace.principal);
  }

  // format the who string for on-screen display
  this.formatWho = function() {
    return this.principal.format();
  }

  // format the how string for on-screen display
  this.formatHow = function() {
    var formattedHow = "";

    for (var i = 0; i < how.length; i++) {
      var h = how.charAt(i);
      var negated = false;
      var grantDenyStr = grantStr;
      if (h == "-") {
        negated = true;
        grantDenyStr = denyStr;
        i++;
        h = how.charAt(i);
      }

      formattedHow += '' + hows.getHows(h).getDispVal(negated) + '';
      if (i != how.length-1) {
        formattedHow += ', ';
      }
    }

    return formattedHow;
  }

  this.formatInherited = function() {
    if (inherited != "") {
      return inherited;
    }

    return inheritedStr;
  }

  this.howsToXml = function(doGrants) {
    var open = false;
    var res = "";

    for (var hi = 0; hi < how.length; hi++) {
      var h = how.charAt(hi);

      if (doGrants && (h == "-")) {
        // skip
        hi++;
      } else if (!doGrants && (h != "-")) {
        // skip
      } else {
        if (h == "-") {
          hi++;
          h = how.charAt(hi);
        }

        var hvs = hows.getHows(h);

        if (!open) {
          if (doGrants) {
            res += "    <D:grant>\n";
          } else {
            res += "    <D:deny>\n";
          }

          open = true;
        }

        res += "      <D:privilege>" + hvs.davEl + "</D:privilege>\n";
      }
    }

    if (open) {
      if (doGrants) {
        res += "    </D:grant>\n";
      } else {
        res += "    </D:deny>\n";
      }
    }

    return res;
  }

  this.toXml = function() {
    if (this.inherited != "") {
      return ""; // Should not emit inherited aces
    }

    var res = "  <D:ace>\n" + this.principal.toXml();

    res += this.howsToXml(true);
    res += this.howsToXml(false);

    //if (this.inherited != "") {
    //  res += "    <D:inherited><D:href>" + this.inherited + "</D:href></D:inherited>";
    //}

    return res + "  </D:ace>\n";
  }

  // row: current row in table
  // aceI: index of the ace
  // id: id of widget output block in the html
  this.toFormRow = function(row, aceI, id) {
    var td_0 = row.insertCell(0);
    td_0.innerHTML = this.principal.format();
    var td_1 = row.insertCell(1);
    td_1.innerHTML = this.formatHow();
    row.insertCell(2).appendChild(document.createTextNode(this.formatInherited()));
    var td_3 = row.insertCell(3);
    if (this.inherited == "") {
      td_3.innerHTML = "" + trashIcon + " " + bwAclWidgetDeleteStr + "";
    }
  }
}

// Access Control List (ACL) object - an array of ACEs
// The bwAcl object is initialized during the XSLT transform.
var bwAcl = new function() {
  var aces = new Array();

  /* If we delete an ace we need to reinstate any inherited access for the same principal
   */
  var savedInherited = new Array();

  // Initialize the list.
  // The function expects a comma-separated list of arguments grouped
  // into the five ACE properties.
  this.init = function(who, whoType, how, inherited, invert) {
    var newAce = new bwAce(who, whoType, how, inherited, invert);
    aces.push(newAce);
    if (inherited != "") {
      savedInherited.push(newAce);
    }
  }

  // Add or update an ace
  this.addAce = function(newAce) {
    // expects a bwAce object as parameter
    for (var i = 0; i < aces.length; i++) {
      if (aces[i].equals(newAce)) {
        // replace an existing ace
        aces[i] = newAce;
        return;
      }
    }
    // not found: add ace to end of array
    aces.push(newAce);
  }

  // Update the list - expects the browser form object
  this.update = function(formObj,id) {
    // get the type of ace being set
    var type;
    for (i = 0; i < formObj.whoType.length; i++) {
      if (formObj.whoType[i].checked == true) {
        type = formObj.whoType[i].value;
      }
    }

    // validate for user or group
    if ((type == 'user' || type == 'group') && formObj.who.value == '') {
      alert("you must enter a user or group name");
      formObj.who.focus();
      return;
    }

    // get the how string from the form
    var how = setAccessHow(formObj);

    //alert("About to update who=" + formObj.who.value +
    //       "\ntype= " + type + "\nhow=" + how);

    this.addAce(new bwAce(formObj.who.value, type, how, "" , false));
    formObj.who.value = "";

    // update the acl form field
    var formAcl = document.getElementById("bwCurrentAcl");
    formAcl.value = this.toXml();

    // redraw the display
    this.display(id);
  }

  this.deleteAce = function(index,id) {
    var ace = aces[index];
    var replace = false;

    for (var si = 0; si < savedInherited.length; si++) {
      if (savedInherited[si].equals(ace)) {
        ace = savedInherited[si];
        replace = true;
        break;
      }
    }

    if (replace) {
      aces[index] = ace;
    } else {
      aces.splice(index, 1);
    }

    // update the acl form field
    var formAcl = document.getElementById("bwCurrentAcl");
    formAcl.value = this.toXml();

    // redraw the display
    this.display(id);
  }

  // build the ACL widget displayed on screen in the given id
  this.display = function(id) {
    try {

      // get the aclWidget and throw out the existing contents
      var aclWidget = document.getElementById(id);
      aclWidget.removeChild(aclWidget.firstChild);

      var bwCurrentAccess = document.createElement("table");
      bwCurrentAccess.className = "common scheduling";
      bwCurrentAccess.id = "bwCurrentAccess";
      bwCurrentAccess.createTHead();
      bwCurrAccessHead = bwCurrentAccess.tHead.insertRow(0);
      // build the th row using the DOM to avoid IE8 issues (i.e. avoid innerHTML)
      var th1 = document.createElement("th");
      var txt1 = document.createTextNode(bwAclWidgetEntryStr);
      var th2 = document.createElement("th");
      var txt2 = document.createTextNode(bwAclWidgetAccessStr);
      var th3 = document.createElement("th");
      var txt3 = document.createTextNode(bwAclWidgetInheritedStr);
      var th4 = document.createElement("th");
      th1.appendChild(txt1);
      th2.appendChild(txt2);
      th3.appendChild(txt3);
      bwCurrAccessHead.appendChild(th1);
      bwCurrAccessHead.appendChild(th2);
      bwCurrAccessHead.appendChild(th3);
      bwCurrAccessHead.appendChild(th4);

      var bwCurrAccessTBody = document.createElement("tbody");
      bwCurrentAccess.appendChild(bwCurrAccessTBody);

      // finally, write the table back to the display
      aclWidget.appendChild(bwCurrentAccess);

      // get the table body
      var aclTableBody = document.getElementById("bwCurrentAccess").tBodies[0];

      // remove existing rows
      //for (i = aclTableBody.rows.length - 1; i >= 0; i--) {
      //  aclTableBody.deleteRow(i);
      //}

      // create the table rows
      for (var j = 0; j < aces.length; j++) {
        var curAce = aces[j];
        var tr = aclTableBody.insertRow(j);

        curAce.toFormRow(tr, j, id);
      }

    } catch (e) {
      alert(e);
    }
  }

  // generate webDAV ACl XML output
  this.toXml = function() {
    var res = xmlHeader + "\n<D:acl " + nameSpaces + " >\n";

    for (var j = 0; j < aces.length; j++) {
      res += aces[j].toXml();
    }

    return res + "</D:acl>";
  }
}


text:
'use strict';

// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('core');
ApplicationConfiguration.registerModule('core.admin', ['core']);
ApplicationConfiguration.registerModule('core.admin.routes', ['ui.router']);
ApplicationConfiguration.registerModule('d3');
ApplicationConfiguration.registerModule('crossfilter');
ApplicationConfiguration.registerModule('dc');


text:
rm -rf dist/*
python setup.py sdist
twine upload dist/*


text:
layout: post
title: "DevHealthy #25 - Bate-papo: Alda Rocha - Saúde Mental vs. Mercado de TI"
home-title: "DevHealthy #25 - Bate-papo: Alda Rocha - Saúde Mental vs. Mercado de TI"
type: "DevHealthy"
cast: "DH25_feedDEVNAESTRADA_AJUSTADO_V2.mp3"
cast-length: "68065387"
cast-time: "01:10:55"
description: |
  O tópico da vez é saúde mental! Batemos um papo com a Alda Rocha que bate nessa tecla faz um bom tempo! Burnout e "clichês" da área tech foram alguns dos tópicos da nossa conversa. Alda é design lead, UX research, UXD e DEV nas horas vagas! Além disso fundou o projeto CODAMOS e organiza o evento ELIXIR BRASIL.

libsyn-image: "DH-25-capa.jpg"
lybsyn-id: "19374254"
sponsors:
participants:
  -
    name: Keit Oliveira
    twitter: seescrevekeit
  -
    name: Raphael Fabeni
    twitter: raphaelfabeni
  -
    name: Alda Rocha
    twitter: mjcoffeeholick

links:
-
  name: "Codamos Club"
  url: https://codamos.club
-
  name: "Elixir Brasil"
  url: https://2020.elixirbrasil.com/pt/
-

---

  O tópico da vez é saúde mental! Batemos um papo com a Alda Rocha que bate nessa tecla faz um bom tempo! Burnout e "clichês" da área tech foram alguns dos tópicos da nossa conversa. Alda é design lead, UX research, UXD e DEV nas horas vagas! Além disso fundou o projeto CODAMOS e organiza o evento ELIXIR BRASIL.

  Nos siga no Twitter [@devnaestrada](https://twitter.com/devnaestrada) e [@devhealthy](https://twitter.com/devhealthy) e no Instagram [@devnaestrada](https://www.instagram.com/devnaestrada/).

CUPOM STICKERSDEVS 15%: DEVNAESTRADA

---

{% include modules/post-extras.html data=page %}


text:
package com.google.android.libraries.mobiledatadownload.internal;

import static com.google.android.libraries.mobiledatadownload.internal.MddConstants.SPLIT_CHAR;
import static com.google.android.libraries.mobiledatadownload.internal.util.SharedFilesMetadataUtil.MDD_SHARED_FILES;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.VisibleForTesting;
import com.google.android.libraries.mobiledatadownload.Flags;
import com.google.android.libraries.mobiledatadownload.SilentFeedback;
import com.google.android.libraries.mobiledatadownload.annotations.InstanceId;
import com.google.android.libraries.mobiledatadownload.internal.Migrations.FileKeyVersion;
import com.google.android.libraries.mobiledatadownload.internal.logging.LogUtil;
import com.google.android.libraries.mobiledatadownload.internal.util.SharedFilesMetadataUtil;
import com.google.android.libraries.mobiledatadownload.internal.util.SharedFilesMetadataUtil.FileKeyDeserializationException;
import com.google.android.libraries.mobiledatadownload.internal.util.SharedPreferencesUtil;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.mobiledatadownload.internal.MetadataProto.NewFileKey;
import com.google.mobiledatadownload.internal.MetadataProto.SharedFile;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;

/**
 * Stores and provides access to shared file metadata using SharedPreferences.
 *
 * <p>Synchronization on this class depends on the fact that MDD Control Flow are executed on a
 * SequentialExecutor.
 */
@CheckReturnValue
public final class SharedPreferencesSharedFilesMetadata implements SharedFilesMetadata {

  private static final String TAG = "SharedFilesMetadata";

  @VisibleForTesting static final String PREFS_KEY_NEXT_FILE_NAME_OLD = "next_file_name";
  @VisibleForTesting static final String PREFS_KEY_NEXT_FILE_NAME = "next_file_name_v2";

  private final Context context;
  private final SilentFeedback silentFeedback;
  private final Optional<String> instanceId;
  private final Flags flags;

  @Inject
  public SharedPreferencesSharedFilesMetadata(
      @ApplicationContext Context context,
      SilentFeedback silentFeedback,
      @InstanceId Optional<String> instanceId,
      Flags flags) {
    this.context = context;
    this.silentFeedback = silentFeedback;
    this.instanceId = instanceId;
    this.flags = flags;
  }

  @Override
  public ListenableFuture<Boolean> init() {
    // Migrate to the new file key.
    if (!Migrations.isMigratedToNewFileKey(context)) {
      LogUtil.d("%s Device isn't migrated to new file key, clear and set migration.", TAG);
      Migrations.setMigratedToNewFileKey(context, true);
      Migrations.setCurrentVersion(context, FileKeyVersion.getVersion(flags.fileKeyVersion()));
      return Futures.immediateFuture(false);
    }
    return Futures.immediateFuture(upgradeToNewVersion());
  }

  /**
   * Sequentially upgrade FileKey version to FeatureFlags.fileKeyVersion
   *
   * @return false if any upgrade fails which will result in clearing of all meta data, true on
   *     successful upgrade.
   */
  private boolean upgradeToNewVersion() {
    final FileKeyVersion targetVersion = FileKeyVersion.getVersion(flags.fileKeyVersion());
    final FileKeyVersion currentVersion = Migrations.getCurrentVersion(context, silentFeedback);

    if (targetVersion.value == currentVersion.value) {
      return true;
    }

    if (targetVersion.value < currentVersion.value) {
      // We don't support downgrading file key version. Clear everything.
      LogUtil.e(
          "%s Cannot migrate back from value %s to %s. Clear everything!",
          TAG, currentVersion, targetVersion);
      silentFeedback.send(
          new Exception(
              "Downgraded file key from " + currentVersion + " to " + targetVersion + "."),
          "FileKey migrations unexpected downgrade.");
      Migrations.setCurrentVersion(context, targetVersion);
      return false;
    }

    // Migrate one version at a time one by one
    try {
      for (int nextVersion = currentVersion.value + 1;
          nextVersion <= targetVersion.value;
          nextVersion++) {
        if (upgradeTo(FileKeyVersion.getVersion(nextVersion))) {
          Migrations.setCurrentVersion(context, FileKeyVersion.getVersion(nextVersion));
        } else {
          // If migration to next version fail, we will clear all data and set the currentVersion
          // to targetVersion (phFileKeyVersion)
          return false;
        }
      }
    } finally {
      if (Migrations.getCurrentVersion(context, silentFeedback).value != targetVersion.value) {
        if (!Migrations.setCurrentVersion(context, targetVersion)) {
          LogUtil.e(
              "Failed to commit migration version to disk. Fail to set target version to "
                  + targetVersion
                  + ".");
          silentFeedback.send(
              new Exception("Fail to set target version " + targetVersion + "."),
              "Failed to commit migration version to disk.");
        }
      }
    }

    return true;
  }

  private boolean upgradeTo(FileKeyVersion targetVersion) {
    switch (targetVersion) {
      case ADD_DOWNLOAD_TRANSFORM:
        return migrateToAddDownloadTransform();
      case USE_CHECKSUM_ONLY:
        return migrateToDedupOnChecksumOnly();
      default:
        throw new UnsupportedOperationException(
            "Upgrade to version " + targetVersion.name() + "not supported!");
    }
  }

  /** A one off method that is called when we migrate key to add download transform. */
  private boolean migrateToAddDownloadTransform() {
    LogUtil.d("%s: Starting migration to add download transform", TAG);
    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    SharedPreferences.Editor editor = prefs.edit();
    for (String serializedFileKey : prefs.getAll().keySet()) {

      // Remove the data that we are unable to read or parse.
      NewFileKey newFileKey;
      try {
        newFileKey =
            SharedFilesMetadataUtil.deserializeNewFileKey(
                serializedFileKey, context, silentFeedback);
      } catch (FileKeyDeserializationException e) {
        LogUtil.e(
            "%s Failed to deserialize file key %s, remove and continue.", TAG, serializedFileKey);
        silentFeedback.send(e, "Failed to deserialize file key, remove and continue.");
        editor.remove(serializedFileKey);
        continue;
      }
      SharedFile sharedFile =
          SharedPreferencesUtil.readProto(prefs, serializedFileKey, SharedFile.parser());
      if (sharedFile == null) {
        LogUtil.e("%s: Unable to read sharedFile from shared preferences.", TAG);
        editor.remove(serializedFileKey);
        continue;
      }

      // Remove the old key and write the new one.
      SharedPreferencesUtil.removeProto(editor, serializedFileKey);
      SharedPreferencesUtil.writeProto(
          editor,
          SharedFilesMetadataUtil.serializeNewFileKeyWithDownloadTransform(newFileKey),
          sharedFile);
    }

    if (!editor.commit()) {
      LogUtil.e("Failed to commit migration metadata to disk");
      silentFeedback.send(
          new Exception("Migrate to DownloadTransform failed."),
          "Failed to commit migration metadata to disk.");
      return false;
    }

    return true;
  }

  /** A one off method that is called when we migrate key to contain checksum and allowedReaders. */
  private boolean migrateToDedupOnChecksumOnly() {
    LogUtil.d("%s: Starting migration to dedup on checksum only", TAG);
    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    SharedPreferences.Editor editor = prefs.edit();
    for (String serializedFileKey : prefs.getAll().keySet()) {

      // Remove the data that we are unable to read or parse.
      NewFileKey newFileKey;
      try {
        newFileKey =
            SharedFilesMetadataUtil.deserializeNewFileKey(
                serializedFileKey, context, silentFeedback);
      } catch (FileKeyDeserializationException e) {
        LogUtil.e(
            "%s Failed to deserialize file key %s, remove and continue.", TAG, serializedFileKey);
        silentFeedback.send(e, "Failed to deserialize file key, remove and continue.");
        editor.remove(serializedFileKey);
        continue;
      }

      SharedFile sharedFile =
          SharedPreferencesUtil.readProto(prefs, serializedFileKey, SharedFile.parser());
      if (sharedFile == null) {
        LogUtil.e("%s: Unable to read sharedFile from shared preferences.", TAG);
        editor.remove(serializedFileKey);
        continue;
      }

      // Remove the old key and write the new one.
      SharedPreferencesUtil.removeProto(editor, serializedFileKey);
      SharedPreferencesUtil.writeProto(
          editor,
          SharedFilesMetadataUtil.serializeNewFileKeyWithChecksumOnly(newFileKey),
          sharedFile);
    }

    if (!editor.commit()) {
      LogUtil.e("Failed to commit migration metadata to disk");
      silentFeedback.send(
          new Exception("Migrate to ChecksumOnly failed."),
          "Failed to commit migration metadata to disk.");
      return false;
    }

    return true;
  }

  @SuppressWarnings("nullness")
  @Override
  public ListenableFuture<SharedFile> read(NewFileKey newFileKey) {
    String serializedFileKey =
        SharedFilesMetadataUtil.getSerializedFileKey(newFileKey, context, silentFeedback);

    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    SharedFile sharedFile =
        SharedPreferencesUtil.readProto(prefs, serializedFileKey, SharedFile.parser());

    return Futures.immediateFuture(sharedFile);
  }

  @Override
  public ListenableFuture<Boolean> write(NewFileKey newFileKey, SharedFile sharedFile) {
    String serializedFileKey =
        SharedFilesMetadataUtil.getSerializedFileKey(newFileKey, context, silentFeedback);

    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    return Futures.immediateFuture(
        SharedPreferencesUtil.writeProto(prefs, serializedFileKey, sharedFile));
  }

  @Override
  public ListenableFuture<Boolean> remove(NewFileKey newFileKey) {
    String serializedFileKey =
        SharedFilesMetadataUtil.getSerializedFileKey(newFileKey, context, silentFeedback);

    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    return Futures.immediateFuture(SharedPreferencesUtil.removeProto(prefs, serializedFileKey));
  }

  @Override
  public ListenableFuture<List<NewFileKey>> getAllFileKeys() {
    List<NewFileKey> newFileKeyList = new ArrayList<>();
    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    SharedPreferences.Editor editor = null;
    for (String serializedFileKey : prefs.getAll().keySet()) {
      try {
        NewFileKey newFileKey =
            SharedFilesMetadataUtil.deserializeNewFileKey(
                serializedFileKey, context, silentFeedback);
        newFileKeyList.add(newFileKey);
      } catch (FileKeyDeserializationException e) {
        LogUtil.e(e, "Failed to deserialize newFileKey:" + serializedFileKey);
        silentFeedback.send(
            e,
            "Failed to deserialize newFileKey, unexpected key size: %d",
            Splitter.on(SPLIT_CHAR).splitToList(serializedFileKey).size());
        // TODO(b/128850000): Refactor this code to a single corruption handling task during
        // maintenance.
        // Remove the corrupted file metadata and the related FileGroup metadata will be deleted
        // in next maintenance task.
        if (editor == null) {
          editor = prefs.edit();
        }
        editor.remove(serializedFileKey);
        continue;
      }
    }
    if (editor != null) {
      editor.commit();
    }
    return Futures.immediateFuture(newFileKeyList);
  }

  @Override
  public ListenableFuture<Void> clear() {
    SharedPreferences prefs =
        SharedPreferencesUtil.getSharedPreferences(context, MDD_SHARED_FILES, instanceId);
    prefs.edit().clear().commit();
    return Futures.immediateFuture(null);
  }
}