text:
package com.licenta.oauth;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author Lucian CONDESCU
 */
public class ProviderFactory {

    public static Provider getProviderByName(String providerName, javax.servlet.ServletContext context) {
        providerName = providerName.trim().toLowerCase();
        Properties properties = new Properties();
        InputStream inputStream = ProviderFactory.class.getClassLoader().getResourceAsStream("config/" + providerName + ".xml");
        try {
            properties.loadFromXML(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String apiKey = properties.getProperty("API_KEY");
        String apiSecret = properties.getProperty("API_SECRET");
        String domain = properties.getProperty("DOMAIN");
        if(domain.endsWith("/")) domain = domain.substring(0,domain.length() - 1);
        String callback = domain + context.getContextPath() + "/oauth2Callback";
        Provider provider = null;

        switch (providerName) {
            case "google" :
                provider = new GoogleProvider(apiKey, apiSecret, callback);
                break;
            case "facebook" :
                provider = new FacebookProvider(apiKey,apiSecret,callback);
                break;
            case "yahoo" :
                provider = new YahooProvider(apiKey,apiSecret,callback);
                break;
        }

        return provider;
    }
}


text: export { default } from 'ember-paper/components/paper-speed-dial-actions-action';

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readrz.com</title>
  <meta name="description" content="">

  <link rel="stylesheet" href="/lib/bootstrap/3.3.4/css/bootstrap-darkly.min.css">

  <link rel="canonical" href="http://www.readrz.com/">

Readrz.com

We regret to inform you that we've stopped Readrz.

The website and all the services have been hybernated.

Please visit the blog for more information.

Visit Readrz Blog


text:
//-----------------------------------------------------------------------
// <copyright file="Futures.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor.Internal;
using Akka.Dispatch.SysMsg;
using Akka.Util;
using Akka.Util.Internal;

namespace Akka.Actor
{
    /// <summary>
    ///     Extension method class designed to create Ask support for
    ///     non-ActorRef objects such as <see cref="ActorSelection" />.
    /// </summary>
    public static class Futures
    {
        //when asking from outside of an actor, we need to pass a system, so the FutureActor can register itself there and be resolvable for local and remote calls
        public static Task<object> Ask(this ICanTell self, object message, TimeSpan? timeout = null)
        {
            return self.Ask<object>(message, timeout);
        }

        public static async Task<T> Ask<T>(this ICanTell self, object message, TimeSpan? timeout = null)
        {
            IActorRefProvider provider = ResolveProvider(self);
            if (provider == null)
                throw new NotSupportedException("Unable to resolve the target Provider");

            ResolveReplyTo();
            var result = (T)await Ask(self, message, provider, timeout);
            return result;
        }

        internal static IActorRef ResolveReplyTo()
        {
            if (ActorCell.Current != null)
                return ActorCell.Current.Self;

            return null;
        }

        internal static IActorRefProvider ResolveProvider(ICanTell self)
        {
            if (ActorCell.Current != null)
                return InternalCurrentActorCellKeeper.Current.SystemImpl.Provider;

            if (self is IInternalActorRef)
                return self.AsInstanceOf<IInternalActorRef>().Provider;

            if (self is ActorSelection)
                return ResolveProvider(self.AsInstanceOf<ActorSelection>().Anchor);

            return null;
        }

        private static Task<object> Ask(ICanTell self, object message, IActorRefProvider provider,
            TimeSpan? timeout)
        {
            var result = new TaskCompletionSource<object>(TaskContinuationOptions.AttachedToParent);
            if (timeout.HasValue)
            {
                var cancellationSource = new CancellationTokenSource();
                cancellationSource.Token.Register(() => result.TrySetCanceled());
                cancellationSource.CancelAfter(timeout.Value);
            }

            //create a new tempcontainer path
            ActorPath path = provider.TempPath();
            //callback to unregister from tempcontainer
            Action unregister = () => provider.UnregisterTempActor(path);
            var future = new FutureActorRef(result, unregister, path);
            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            self.Tell(message, future);
            return result.Task;
        }
    }

    /// <summary>
    /// Akka private optimized representation of the temporary actor spawned to
    /// receive the reply to an "ask" operation.
    ///
    /// INTERNAL API
    /// </summary>
    internal sealed class PromiseActorRef : MinimalActorRef
    {
        public PromiseActorRef(IActorRefProvider provider, TaskCompletionSource<object> result, string mcn)
        {
            _provider = provider;
            Result = result;
            _mcn = mcn;
        }

        private readonly IActorRefProvider _provider;
        public readonly TaskCompletionSource<object> Result;

        /// <summary>
        /// This is necessary for weaving the PromiseActorRef into the asked message, i.e. the replyTo pattern.
        /// </summary>
        private volatile string _mcn;

        #region Internal states

        /**
           * As an optimization for the common (local) case we only register this PromiseActorRef
           * with the provider when the `path` member is actually queried, which happens during
           * serialization (but also during a simple call to `ToString`, `Equals` or `GetHashCode`!).
           *
           * Defined states:
           * null                  => started, path not yet created
           * Registering           => currently creating temp path and registering it
           * path: ActorPath       => path is available and was registered
           * StoppedWithPath(path) => stopped, path available
           * Stopped               => stopped, path not yet created
           */
        private AtomicReference<object> _stateDoNotCallMeDirectly = new AtomicReference<object>(null);

        internal sealed class Registering
        {
            private Registering() { }
            // ReSharper disable once InconsistentNaming
            private static readonly Registering _instance = new Registering();

            public static Registering Instance { get { return _instance; } }
        }

        internal sealed class Stopped
        {
            private Stopped() { }
            // ReSharper disable once InconsistentNaming
            private static readonly Stopped _instance = new Stopped();

            public static Stopped Instance { get { return _instance; } }
        }

        internal sealed class StoppedWithPath : IEquatable<StoppedWithPath>
        {
            public StoppedWithPath(ActorPath path)
            {
                Path = path;
            }

            public ActorPath Path { get; private set; }

            #region Equality

            public bool Equals(StoppedWithPath other)
            {
                if (ReferenceEquals(null, other)) return false;
                if (ReferenceEquals(this, other)) return true;
                return Equals(Path, other.Path);
            }

            public override bool Equals(object obj)
            {
                if (ReferenceEquals(null, obj)) return false;
                if (ReferenceEquals(this, obj)) return true;
                return obj is StoppedWithPath && Equals((StoppedWithPath)obj);
            }

            public override int GetHashCode()
            {
                return (Path != null ? Path.GetHashCode() : 0);
            }

            #endregion
        }

        #endregion

        #region Static methods

        private static readonly Status.Failure ActorStopResult = new Status.Failure(new ActorKilledException("Stopped"));

        public static PromiseActorRef Apply(IActorRefProvider provider, TimeSpan timeout, object targetName,
            string messageClassName, IActorRef sender = null)
        {
            sender = sender ?? ActorRefs.NoSender;
            var result = new TaskCompletionSource<object>();
            var a = new PromiseActorRef(provider, result, messageClassName);
            var scheduler = provider.Guardian.Underlying.System.Scheduler.Advanced;
            var c = new Cancelable(scheduler, timeout);
            scheduler.ScheduleOnce(timeout, () => result.TrySetResult(new Status.Failure(new AskTimeoutException(
                string.Format("Ask timed out on [{0}] after [{1} ms]. Sender[{2}] sent message of type {3}.", targetName, timeout.TotalMilliseconds, sender, messageClassName)))),
                c);

            result.Task.ContinueWith(r =>
            {
                try
                {
                    a.Stop();
                }
                finally
                {
                    c.Cancel(false);
                }
            }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously);

            return a;
        }

        #endregion

        //TODO: ActorCell.emptyActorRefSet ?
        private readonly AtomicReference<HashSet<IActorRef>> _watchedByDoNotCallMeDirectly = new AtomicReference<HashSet<IActorRef>>();

        private HashSet<IActorRef> WatchedBy
        {
            get { return _watchedByDoNotCallMeDirectly; }
        }

        private bool UpdateWatchedBy(HashSet<IActorRef> oldWatchedBy, HashSet<IActorRef> newWatchedBy)
        {
            return _watchedByDoNotCallMeDirectly.CompareAndSet(oldWatchedBy, newWatchedBy);
        }

        public override IActorRefProvider Provider
        {
            get { return _provider; }
        }

        /// <summary>
        /// Returns false if the <see cref="Result"/> is already completed.
        /// </summary>
        private bool AddWatcher(IActorRef watcher)
        {
            if (WatchedBy.Contains(watcher))
            {
                return false;
            }
            return UpdateWatchedBy(WatchedBy, WatchedBy.CopyAndAdd(watcher)) || AddWatcher(watcher);
        }

        private void RemoveWatcher(IActorRef watcher)
        {
            if (!WatchedBy.Contains(watcher))
            {
                return;
            }
            if (!UpdateWatchedBy(WatchedBy, WatchedBy.CopyAndRemove(watcher))) RemoveWatcher(watcher);
        }

        private HashSet<IActorRef> ClearWatchers()
        {
            //TODO: ActorCell.emptyActorRefSet ?
            if (WatchedBy == null) return new HashSet<IActorRef>();
            if (!UpdateWatchedBy(WatchedBy, null)) return ClearWatchers();
            else return WatchedBy;
        }

        private object State
        {
            get { return _stateDoNotCallMeDirectly; }
            set { _stateDoNotCallMeDirectly = value; }
        }

        private bool UpdateState(object oldState, object newState)
        {
            return _stateDoNotCallMeDirectly.CompareAndSet(oldState, newState);
        }

        public override IInternalActorRef Parent
        {
            get { return Provider.TempContainer; }
        }

        public override ActorPath Path
        {
            get { return GetPath(); }
        }

        /// <summary>
        ///  Contract of this method:
        ///  Must always return the same ActorPath, which must have
        ///  been registered if we haven't been stopped yet.
        /// </summary>
        private ActorPath GetPath()
        {
            while (true)
            {
                if (State == null)
                {
                    if (UpdateState(null, Registering.Instance))
                    {
                        ActorPath p = null;
                        try
                        {
                            p = Provider.TempPath();
                            Provider.RegisterTempActor(this, p);
                            return p;
                        }
                        finally
                        {
                            State = p;
                        }
                    }
                    continue;
                }

                if (State is ActorPath)
                    return State as ActorPath;
                if (State is StoppedWithPath)
                    return State.AsInstanceOf<StoppedWithPath>().Path;
                if (State is Stopped)
                {
                    //even if we are already stopped we still need to produce a proper path
                    UpdateState(Stopped.Instance, new StoppedWithPath(Provider.TempPath()));
                    continue;
                }
                if (State is Registering)
                    continue;
            }
        }

        protected override void TellInternal(object message, IActorRef sender)
        {
            if (message is ISystemMessage)
            {
                SendSystemMessage(message as ISystemMessage);
                return;
            }

            if (State is Stopped || State is StoppedWithPath) Provider.DeadLetters.Tell(message);
            else
            {
                if(message == null) throw new InvalidMessageException();
                var wrappedMessage = message;
                if (!(message is Status.Success || message is Status.Failure))
                {
                    wrappedMessage = new Status.Success(message);
                }
                if (!(Result.TrySetResult(wrappedMessage)))
                    Provider.DeadLetters.Tell(message);
            }
        }

        //TODO: isn't SendSystemMessage supposed to be a part of ActorRef? Why isn't it overridable?
        private void SendSystemMessage(ISystemMessage message)
        {
            if(message is Terminate) Stop();
            else if (message is DeathWatchNotification)
            {
                var dw = message as DeathWatchNotification;
                Tell(new Terminated(dw.Actor, dw.ExistenceConfirmed, dw.AddressTerminated), this);
            }
            else if (message is Watch)
            {
                var watch = message as Watch;
                if (watch.Watchee == this)
                {
                    if (!AddWatcher(watch.Watcher))
                    {
                        // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
                        watch.Watcher.Tell(new DeathWatchNotification(watch.Watchee, existenceConfirmed: true,
                            addressTerminated: false));
                    }
                    else
                    {
                        //TODO: find a way to get access to logger?
                        Console.WriteLine("BUG: illegal Watch({0},{1}) for {2}", watch.Watchee, watch.Watcher, this);
                    }
                }
            }
            else if (message is Unwatch)
            {
                var unwatch = message as Unwatch;
                if(unwatch.Watchee == this && unwatch.Watcher != this) RemoveWatcher(unwatch.Watcher);
                else Console.WriteLine("BUG: illegal Unwatch({0},{1}) for {2}", unwatch.Watchee, unwatch.Watcher, this);
            }
            else { }
        }

        public override void Stop()
        {
            Action ensureCompleted = () =>
            {
                Result.TrySetResult(ActorStopResult);
                var watchers = ClearWatchers();
                if (watchers.Any())
                {
                    foreach (var watcher in watchers)
                    {
                        watcher.Tell(new DeathWatchNotification(watcher, existenceConfirmed: true,
                            addressTerminated: false));
                    }
                }
            };

            var state = State;
            // if path was never queried nobody can possibly be watching us, so we don't have to publish termination either
            if (state == null)
            {
                if (UpdateState(null, Stopped.Instance)) ensureCompleted();
                else Stop();
            }
            else if (state is ActorPath)
            {
                var p = state as ActorPath;
                if (UpdateState(p, new StoppedWithPath(p)))
                {
                    try
                    {
                        ensureCompleted();
                    }
                    finally
                    {
                        Provider.UnregisterTempActor(p);
                    }
                }
                else
                {
                    Stop();
                }
            }
            else if (state is Stopped || state is StoppedWithPath)
            {
                //already stopped
            }
            else if (state is Registering)
            {
                //spin until registration is completed before stopping
                Stop();
            }
        }
    }
}


text:
import logging

import numpy as np
try:
    from plotly import plotly
except ImportError:
    plotly = None

from ..qt.widgets import ScatterWidget, HistogramWidget
from ..core.data import CategoricalComponent
from ..core.layout import Rectangle, snap_to_grid

SYM = {'o': 'circle', 's': 'square', '+': 'cross', '^': 'triangle-up',
       '*': 'cross'}

def _data(layer, component):
    """
    Extract the data associated with a Component

    For categorical components, extracts the categories and not
    the remapped integers
    """
    result = layer[component]
    comp = layer.data.get_component(component)
    if isinstance(comp, CategoricalComponent):
        result = comp._categories[result.astype(np.int)]
    return result

def _sanitize(*arrs):
    mask = np.ones(arrs[0].shape, dtype=np.bool)
    for a in arrs:
        try:
            mask &= (~np.isnan(a))
        except TypeError:  # non-numeric dtype
            pass

    return tuple(a[mask].ravel() for a in arrs)

def _position_plots(viewers, layout):
    rs = [Rectangle(v.position[0], v.position[1],
                    v.viewer_size[0], v.viewer_size[1])
          for v in viewers]
    right = max(r.x + r.w for r in rs)
    top = max(r.y + r.h for r in rs)
    for r in rs:
        r.x = 1. * r.x / right
        r.y = 1. - 1. * (r.y + r.h) / top
        r.w = 1. * r.w / right
        r.h = 1. * r.h / top

    grid = snap_to_grid(rs, padding=0.05)
    grid = dict((v, grid[r]) for v, r in zip(viewers, rs))

    for i, plot in enumerate(viewers, 1):
        g = grid[plot]
        xdomain = [g.x, g.x + g.w]
        ydomain = [g.y, g.y + g.h]
        suffix = '' if i == 1 else str(i)

        xax, yax = 'xaxis' + suffix, 'yaxis' + suffix
        layout[xax].update(domain=xdomain, anchor=yax.replace('axis', ''))
        layout[yax].update(domain=ydomain, anchor=xax.replace('axis', ''))

def _stack_horizontal(layout):
    layout['xaxis']['domain'] = [0, 0.45]
    layout['xaxis2']['domain'] = [0.55, 1]
    layout['yaxis2']['anchor'] = 'x2'

def _grid_2x23(layout):
    opts = {
        'xaxis': {'domain': [0, 0.45]},
        'yaxis': {'domain': [0, 0.45]},
        'xaxis2': {"domain": [0.55, 1]},
        'yaxis2': {"domain": [0, 0.45],
                   "anchor": "x2"
                   },
        'xaxis3': {
            "domain": [0, 0.45],
            "anchor": "y3"
        },
        'yaxis3': {
            "domain": [0.55, 1],
        },
        'xaxis4': {
            "domain": [0.55, 1],
            "anchor": "y4",
        },
        'yaxis4': {
            "domain": [0.55, 1],
            "anchor": "x4"
        }
    }
    for k, v in opts.items():
        if k not in layout:
            continue
        layout[k].update(**v)

def _axis(log=False, lo=0, hi=1, title='', categorical=False):
    if log:
        if lo < 0:
            lo = 1e-3
        if hi < 0:
            hi = 1e-3
        lo = np.log10(lo)
        hi = np.log10(hi)

    result = dict(type='log' if log else 'linear',
                  rangemode='normal',
                  range=[lo, hi], title=title)

    if categorical:
        result.pop('type')
        # about 10 categorical ticks per graph
        result['autotick'] = False
        result['dtick'] = max(int(hi - lo) / 10, 1)

    return result

def _fix_legend_duplicates(traces, layout):
    """Prevent repeat entries in the legend"""
    seen = set()
    for t in traces:
        key = (t.get('name'), t.get('marker', {}).get('color'))
        if key in seen:
            t['showlegend'] = False
        else:
            seen.add(key)

def _color(style):
    color = int(style.color[1:], base=16)
    r = color / 256 / 256
    g = color / 256 % 256
    b = color % 256
    a = style.alpha
    return 'rgba(%i, %i, %i, %0.1f)' % (r, g, b, a)

def export_scatter(viewer):
    """Export a scatter viewer to a list of
    plotly-formatted data dictionaries"""
    traces = []
    xatt, yatt = viewer.xatt, viewer.yatt
    xcat = ycat = False

    for layer in viewer.layers:
        if not layer.visible:
            continue
        l = layer.layer
        xcat |= isinstance(l.data.get_component(xatt), CategoricalComponent)
        ycat |= isinstance(l.data.get_component(yatt), CategoricalComponent)

        marker = dict(symbol=SYM.get(l.style.marker, 'circle'),
                      color=_color(l.style),
                      size=l.style.markersize)

        x, y = _sanitize(_data(l, xatt), _data(l, yatt))

        trace = dict(x=x, y=y,
                     type='scatter',
                     mode='markers',
                     marker=marker,
                     name=l.label)

        traces.append(trace)

    xaxis = _axis(log=viewer.xlog, lo=viewer.xmin, hi=viewer.xmax,
                  title=viewer.xatt.label, categorical=xcat)
    yaxis = _axis(log=viewer.ylog, lo=viewer.ymin, hi=viewer.ymax,
                  title=viewer.yatt.label, categorical=ycat)

    return traces, xaxis, yaxis

def export_histogram(viewer):
    traces = []
    att = viewer.component
    ymax = 1e-3
    for artist in viewer.layers:
        if not artist.visible:
            continue
        layer = artist.layer
        x, y = _sanitize(artist.x[:-1], artist.y)
        trace = dict(
            name=layer.label,
            type='bar',
            marker=dict(color=_color(layer.style)),
            x=x,
            y=y)
        traces.append(trace)
        ymax = max(ymax, artist.y.max())

    xlabel = att.label
    xmin, xmax = viewer.xmin, viewer.xmax
    if viewer.xlog:
        xlabel = 'Log ' + xlabel
        xmin = np.log10(xmin)
        xmax = np.log10(xmax)
    xaxis = _axis(lo=xmin, hi=xmax, title=xlabel)
    yaxis = _axis(log=viewer.ylog, lo=0 if not viewer.ylog else 1e-3,
                  hi=ymax * 1.05)

    return traces, xaxis, yaxis

def build_plotly_call(app):
    args = []
    layout = {'showlegend': True, 'barmode': 'overlay',
              'title': 'Autogenerated by Glue'}
    dispatch = {ScatterWidget: export_scatter,
                HistogramWidget: export_histogram
                }

    ct = 1
    for tab in app.viewers:
        for viewer in tab:
            if hasattr(viewer, '__plotly__'):
                p, xaxis, yaxis = viewer.__plotly__()
            else:
                assert type(viewer) in dispatch
                p, xaxis, yaxis = dispatch[type(viewer)](viewer)

            xaxis['zeroline'] = False
            yaxis['zeroline'] = False

            suffix = '' if ct == 1 else '%i' % ct
            layout['xaxis' + suffix] = xaxis
            layout['yaxis' + suffix] = yaxis
            if ct > 1:
                yaxis['anchor'] = 'x' + suffix
                for item in p:
                    item['xaxis'] = 'x' + suffix
                    item['yaxis'] = 'y' + suffix
            ct += 1
            args.extend(p)

    _position_plots([v for tab in app.viewers for v in tab], layout)
    _fix_legend_duplicates(args, layout)

    return [dict(data=args, layout=layout)], {}

def can_save_plotly(application):
    """
    Check whether an application can be exported to plotly

    Raises an exception if not
    """
    if not plotly:
        raise ValueError("Plotly Export requires the plotly python library. "
                         "Please install first")

    user = application.get_setting('PLOTLY_USER')
    apikey = application.get_setting('PLOTLY_APIKEY')
    if not user or not apikey:
        raise ValueError("Plotly username and API Key required. "
                         "Please enter them in File->Edit Settings")

    for tab in application.viewers:
        for viewer in tab:
            if hasattr(viewer, '__plotly__'):
                continue

            if not isinstance(viewer, (ScatterWidget, HistogramWidget)):
                raise ValueError("Plotly Export cannot handle viewer: %s"
                                 % type(viewer))

    if len(application.viewers) != 1:
        raise ValueError("Plotly Export only supports a single tab. "
                         "Please close other tabs to export")

    nplot = sum(len(t) for t in application.viewers)
    if nplot == 0:
        raise ValueError("Plotly Export requires at least one plot")

    if nplot > 4:
        raise ValueError("Plotly Export supports at most 4 plots")

def save_plotly(application, label):
    """Save a Glue session to a plotly plot

    This is currently restricted to 1-4 scatterplots or histograms

    :param application: Glue application to save
    :param label: Label for the exported plot
    """
    user = application.get_setting('PLOTLY_USER')
    apikey = application.get_setting('PLOTLY_APIKEY')

    args, kwargs = build_plotly_call(application)
    kwargs['filename'] = label

    logging.getLogger(__name__).debug(args, kwargs)

    plotly.sign_in(user, apikey)
    plotly.plot(*args, **kwargs)

def setup():
    from ..config import exporters, settings
    exporters.add('Plotly', save_plotly, can_save_plotly, outmode='label')
    settings.add('PLOTLY_USER', 'Glue')
    settings.add('PLOTLY_APIKEY', 't24aweai14')


text:
markdown_view
=============

simple markdown view, use local browser,written in python.

install
---

    git clone https://github.com/duoduo369/markdown_view.git /you/path
    pip install -r requirement.txt
    sudo ln -s /you/path/markdown_view.py /usr/local

Usage:
---

    markdown_view.py <markdown_file>
    markdown_view.py --version

Options:
---

    -h --help     Show this screen.
    --version     Show version.


text:
Mezzanine Client is a **Python SDK** and **remote CLI** for [Mezzanine API](index.md). It enables a user or service to remotely read or write to Mezzanine CMS using Python or the command line. For example, you can write an article in Markdown on your laptop and type a simple command to automatically upload it and create a new blog post from it on your website.

This page concerns mainly the Python SDK part of the Mezzanine Client package. You can also refer to the [CLI page](cli.md) for information on the command line tool.

## Installation

    pip install -U mezzanine-client

[*Star* the Client on Github](https://github.com/gcushen/mezzanine-client-python/) to help support further development. You can also *watch* it on Github to keep track of updates.

## Prerequisites

Install [Mezzanine API](index.md#installation) either locally (for development) or remotely (for production), as we need an API to connect to.

Once Mezzanine API is installed,

1. Login to your Mezzanine CMS Admin Panel (e.g. [http://127.0.0.1:8000/admin/](http://127.0.0.1:8000/admin/))
2. In the menu, click *OAuth* > *Applications*
3. Create a new application with the following details:

        App Name: Mezzanine Python Client
        App ID: id
        App Secret: secret
        Client Type: Confidential
        Grant Type: Code
        Redirect URI: https://httpbin.org/get

For development purposes, you can define the simple app ID and secret above, otherwise use the automatically generated ones.

## Getting started

The client's `Mezzanine` class in the `api` module contains a set of methods for accessing the API. Some of the most common methods are demonstrated in the following command line interface examples:

- `posts_list.py` List published blog posts
- `posts_retrieve.py <post_id>` Retrieve the specified blog post
- `posts_create.py` Create a new blog post

Start by downloading the examples included in <https://github.com/gcushen/mezzanine-client-python/archive/master.zip> , or directly with `wget`:

    $ mkdir mezzanine-client-examples && cd $_ && wget https://raw.githubusercontent.com/gcushen/mezzanine-client-python/master/examples/posts_list.py \
    https://raw.githubusercontent.com/gcushen/mezzanine-client-python/master/examples/posts_retrieve.py \
    https://raw.githubusercontent.com/gcushen/mezzanine-client-python/master/examples/posts_create.py

Allow examples to be executed without explicit `python` command:

    $ chmod u+x posts_*.py

Prior to running the examples, export your app ID and secret to your terminal environment:

    $ export MZN_ID='id'
    $ export MZN_SECRET='secret'

Then run an example:

    $ ./posts_list.py

## Authorize the app

If you have previously used apps for platforms like Facebook, Google, or Twitter, then you may be familiar with the OAuth app authorization process. More specifically, the Mezzanine Client uses the latest OAuth2 code authorization flow.

The first time that the Client app attempts to access the API, it will ask you to click a link to authorize it. First you will be taken to the login page on your API website, where you should login using your Mezzanine account:

![mezzanine api](img/client_app_login.png)

Next, you will be asked if you wish to authorize the Mezzanine Client app:

![mezzanine api](img/client_app_authorize.png)

If you confirm the authorization request, you will be given a confirmation code, displayed similar to that below.

    "args": {
        "code": "vYQqcQSHmqkezX09xh8qflGVYUw6F8",
        "state": "Euf91j3H6uEE9VQ9mWsvFC5s3eEMJt"
    },

The confirmation code in this case is "vYQqcQSHmqkezX09xh8qflGVYUw6F8" *without* the speech marks and should be pasted back into the app within one hour to complete the authorization.

After successful authentication, Mezzanine Client stores the OAuth refresh token in `~/.mezzanine.cfg` to prevent you needing to manually re-authenticate every time you run the app. If you wish to completely logout of the app, you can delete this file.

Now you can have fun trying some of the CLI or SDK examples!

Otherwise, if there were any issues authorizing the app, it is worth checking that you followed all the [prerequisite](#prerequisites) steps. Or for help, refer to the [Community](#community) section below.

## Community

[Chat Room](https://gitter.im/gcushen/mezzanine-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - if the room is quiet, feel free to leave a message and someone will try to get back to you.

[Report a bug or feature request](https://github.com/gcushen/mezzanine-client-python/issues) for the client.

## Roadmap

- Test suite
- Further documentation and examples


text:
helpers do
  def current_user
    @current_user ||= User.find(session[:id])
  end

  def challenge_converter(str)
    case str
      when 'A' then "Affordable Housing"
      when 'D' then "Drug/Alcohol Treatment"
      when 'ED' then "Educational Opportunities"
      when 'EM' then "Employment/Job Search"
      when 'F' then "Family Counseling"
      when 'MC' then "Medical Care"
      when 'MH' then "Mental Health Services"
      when 'N' then "Nonviolent Conflict Resolution"
    end
  end

  def contact_converter(str)
    case str
      when 'P' then 'Phone'
      when 'E' then 'Email'
      when 'W' then 'WiseFriend Messaging'
    end
  end

  def get_tweets
    @original_tweets = TWITTER_CLIENT.search("ex-offender", result_type: "recent").take(50)
    tweet_hash = {}
    @original_tweets.each do |tweet|
      tweet_hash[tweet.text] ||= tweet
    end
    @tweets = []
    tweet_hash.each do |k, v|
      @tweets.push(v)
    end
  end
end


text:
from cinderclient import exceptions as cinderclient
from glanceclient.common import exceptions as glanceclient
from heatclient import exc as heatclient
from keystoneclient import exceptions as keystoneclient
from neutronclient.common import exceptions as neutronclient
from novaclient import exceptions as novaclient
from swiftclient import client as swiftclient
try:
    from troveclient import exceptions as troveclient
    with_trove = True
except ImportError:
    with_trove = False

UNAUTHORIZED = (keystoneclient.Unauthorized,
                keystoneclient.Forbidden,
                cinderclient.Unauthorized,
                cinderclient.Forbidden,
                novaclient.Unauthorized,
                novaclient.Forbidden,
                glanceclient.Unauthorized,
                neutronclient.Unauthorized,
                neutronclient.Forbidden,
                heatclient.HTTPUnauthorized,
                heatclient.HTTPForbidden,)

NOT_FOUND = (keystoneclient.NotFound,
             cinderclient.NotFound,
             novaclient.NotFound,
             glanceclient.NotFound,
             neutronclient.NetworkNotFoundClient,
             neutronclient.PortNotFoundClient,
             heatclient.HTTPNotFound,)

# NOTE(gabriel): This is very broad, and may need to be dialed in.
RECOVERABLE = (keystoneclient.ClientException,
               # AuthorizationFailure is raised when Keystone is "unavailable".
               keystoneclient.AuthorizationFailure,
               cinderclient.ClientException,
               novaclient.ClientException,
               glanceclient.ClientException,
               # NOTE(amotoki): Neutron exceptions other than the first one
               # are recoverable in many cases (e.g., NetworkInUse is not
               # raised once VMs which use the network are terminated).
               neutronclient.NeutronClientException,
               neutronclient.NetworkInUseClient,
               neutronclient.PortInUseClient,
               neutronclient.AlreadyAttachedClient,
               neutronclient.StateInvalidClient,
               swiftclient.ClientException,
               heatclient.HTTPException,)

if with_trove:
    UNAUTHORIZED += (troveclient.Unauthorized,)
    NOT_FOUND += (troveclient.NotFound,)
    RECOVERABLE += (troveclient.ClientException,)


text:
"use strict";
var React = require("react");
var PatchView = require("./patch-view");
var CommentView = require("./comment-view");
var Patch = require("../logic/models/patch");
var LineComment = require("../logic/models/line-comment");

module.exports = React.createClass({displayName: 'CommentDiffListView',
    propTypes: {
        patch: React.PropTypes.instanceOf(Patch).isRequired,
        comments: React.PropTypes.array.isRequired,
        onToggleCommits: React.PropTypes.func,
        numLines: React.PropTypes.number
    },

    getDefaultProps: function() {
        return {
            numLines: 5,
            onToggleCommits: function() {}
        };
    },

    onToggleCommits: function(cmt, wantEarlierCommits) {
        this.props.onToggleCommits(cmt, wantEarlierCommits);
    },

    render: function() {
        var self = this;
        var patch = this.props.patch;
        if (this.props.patch.getUnifiedData().length > this.props.numLines) {
            patch = new Patch(this.props.patch.getRaw());
            patch.setMaxLines(this.props.numLines);
        }

        return (
            <div className="CommentDiffListView">
                <PatchView
                    showUnified={true}
                    patch={patch}
                    enabledComments={false}
                    comments={[]} />
                {self.props.comments.map(function(cmt) {
                    var key;
                    if (cmt instanceof LineComment) {
                        key = cmt.getComment().getId();
                    }
                    else {
                        key = cmt.getId();
                    }
                    return (
                        <CommentView
                            key={key}
                            comment={cmt}
                            onToggleCommits={self.onToggleCommits.bind(self, cmt)}/>
                    );
                })}
            </div>
        );
    }
});


text:
import * as angular from 'angular';
import { ICollection, IResource } from '../interfaces';
import { ICacheMemory } from '../interfaces/cachememory.d';
import { Base } from './base';
import { Converter } from './converter';
import { ResourceFunctions } from './resource-functions';

export class CacheMemory implements ICacheMemory {
    private collections: { [url: string]: ICollection } = {};
    private collections_lastupdate: { [url: string]: number } = {};
    public resources: { [id: string]: IResource } = {};

    public isCollectionExist(url: string): boolean {
        return (url in this.collections && this.collections[url].$source !== 'new' ? true : false);
    }

    public isCollectionLive(url: string, ttl: number): boolean {
        return (Date.now() <= (this.collections_lastupdate[url] + ttl * 1000));
    }

    public isResourceLive(id: string, ttl: number): boolean {
        return this.resources[id] && (Date.now() <= (this.resources[id].lastupdate + ttl * 1000));
    }

    public getOrCreateCollection(url: string): ICollection {
        if (!(url in this.collections)) {
            this.collections[url] = Base.newCollection();
            this.collections[url].$source = 'new';
        }

        return this.collections[url];
    }

    public setCollection(url: string, collection: ICollection): void  {
        // clone collection, because after maybe delete items for localfilter o pagination
        this.collections[url] = Base.newCollection();
        angular.forEach(collection, (resource: IResource, resource_id: string) => {
            this.collections[url][resource_id] = resource;
            this.setResource(resource);
        });
        this.collections[url].page = collection.page;
        this.collections_lastupdate[url] = Date.now();
    }

    public getOrCreateResource(type: string, id: string): IResource {
        if (Converter.getService(type).cachememory && id in Converter.getService(type).cachememory.resources) {
            return Converter.getService(type).cachememory.resources[id];
        } else {
            let resource = Converter.getService(type).new();
            resource.id = id;
            // needed for a lot of request (all and get, tested on multinexo.com)
            this.setResource(resource, false);

            return resource;
        }
    }

    public setResource(resource: IResource, update_lastupdate = false): void  {
        // we cannot redefine object, because view don't update.
        if (resource.id in this.resources) {
            ResourceFunctions.resourceToResource(resource, this.resources[resource.id]);
        } else {
            this.resources[resource.id] = resource;
        }
        this.resources[resource.id].lastupdate = (update_lastupdate ? Date.now() : 0);
    }

    public deprecateCollections(path_start_with: string): boolean {
        angular.forEach(this.collections_lastupdate, (lastupdate: number, key: string) => {
            // we don't need check, memorycache has one collection per resoure type
            // if (key.startsWith(path_start_with) === true) {
                this.collections_lastupdate[key] = 0;
            // }
        });

        return true;
    }

    public removeResource(id: string): void  {
        angular.forEach(this.collections, (value, url) => {
            delete value[id];
        });
        this.resources[id].attributes = {}; // just for confirm deletion on view
        this.resources[id].relationships = {}; // just for confirm deletion on view
        delete this.resources[id];
    }
}


text:
package org.tylproject.vaadin.addon.fieldbinder.behavior;

import org.tylproject.vaadin.addon.datanav.events.CurrentItemChange;

/**
 * A shorthand interface for common editing operations on a
 * {@link org.tylproject.vaadin.addon.datanav.DataNavigation}
 */
public interface Behavior extends
        CurrentItemChange.Listener,
        CrudListeners,
        FindListeners {
}


text:
module Arel # :nodoc: all
  class TreeManager
    include Arel::FactoryMethods

    attr_reader :ast

    def initialize
      @ctx = nil
    end

    def to_dot
      collector = Arel::Collectors::PlainString.new
      collector = Visitors::Dot.new.accept @ast, collector
      collector.value
    end

    def to_sql(engine = Table.engine)
      collector = Arel::Collectors::SQLString.new
      collector = engine.connection.visitor.accept @ast, collector
      collector.value
    end

    def initialize_copy(other)
      super
      @ast = @ast.clone
    end

    def where(expr)
      if Arel::TreeManager === expr
        expr = expr.ast
      end
      @ctx.wheres << expr
      self
    end
  end
end


text:
const AP_Param::GroupInfo AC_HELI_PID::var_info[] PROGMEM = {
    // @Param: P
    // @DisplayName: PID Proportional Gain
    // @Description: P Gain which produces an output value that is proportional to the current error value
    AP_GROUPINFO("P",    0, AC_HELI_PID, _kp, 0),

    // @Param: I
    // @DisplayName: PID Integral Gain
    // @Description: I Gain which produces an output that is proportional to both the magnitude and the duration of the error
    AP_GROUPINFO("I",    1, AC_HELI_PID, _ki, 0),

    // @Param: D
    // @DisplayName: PID Derivative Gain
    // @Description: D Gain which produces an output that is proportional to the rate of change of the error
    AP_GROUPINFO("D",    2, AC_HELI_PID, _kd, 0),

    // @Param: FC
    // @DisplayName: PID+FF FeedForward Gain
    // @Description: FF Gain which produces an output value that is proportional to the current error value
    AP_GROUPINFO("FF",    4, AC_HELI_PID, _ff, 0),

    // @Param: IMAX
    // @DisplayName: PID Integral Maximum
    // @Description: The maximum/minimum value that the I term can output
    AP_GROUPINFO("IMAX", 5, AC_HELI_PID, _imax, 0),

    // @Param: FILT_HZ
    // @DisplayName: PID Input filter frequency in Hz
    // @Description:
    AP_GROUPINFO("FILT_HZ", 6, AC_HELI_PID, _filt_hz, AC_PID_FILT_HZ_DEFAULT),
    AP_GROUPEND
};

/// Constructor for PID
AC_HELI_PID::AC_HELI_PID(float initial_p, float initial_i, float initial_d, float initial_imax, float initial_filt_hz, float dt) :
    AC_PID(initial_p, initial_i, initial_d, initial_imax, initial_filt_hz, dt)
{
     _ff = 0.0f;
}

float AC_HELI_PID::get_ff(float requested_rate) const
{
    return (float)requested_rate * _ff;
}

// This is an integrator which tends to decay to zero naturally
// if the error is zero.

float AC_HELI_PID::get_leaky_i(float leak_rate)
{
	if((_ki != 0) && (_dt != 0)){
		_integrator -= (float)_integrator * leak_rate;
		_integrator += ((float)_input * _ki) * _dt;
		if (_integrator < -_imax) {
			_integrator = -_imax;
		} else if (_integrator > _imax) {
			_integrator = _imax;
		}

		return _integrator;
	}
	return 0;
}


text:
@implementation CHRedEnvelopsAssistance

+ (void)load{
    [self registerSubclass];
}
- (NSString *)title{
    return @"红包";
}
- (NSString *)picture{
    return @"red_packet";
}
- (void)executeEvent:(id )responder{
    // 进入发送红包界面
    _responsed = responder;
    [self postEvent];
}

@end


text:
\hypertarget{classdensities_1_1UniformSampler}{}\section{densities\+:\+:Uniform\+Sampler Class Reference}
\label{classdensities_1_1UniformSampler}\index{densities\+::\+Uniform\+Sampler@{densities\+::\+Uniform\+Sampler}}

A class that performs sampling from a continuous uniform distribution.

{\ttfamily \#include $<$densities.\+h$>$}

\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classdensities_1_1UniformSampler_a29714b42a62dd91603d42b3a2b82eec8}{Uniform\+Sampler} ()\hypertarget{classdensities_1_1UniformSampler_a29714b42a62dd91603d42b3a2b82eec8}{}\label{classdensities_1_1UniformSampler_a29714b42a62dd91603d42b3a2b82eec8}

\begin{DoxyCompactList}\small\item\em The default constructor. Gives a lower bound of 0 and upper bound of 1. \end{DoxyCompactList}\item
\hyperlink{classdensities_1_1UniformSampler_a8dbc3ef50efd8b6b9aa64819f7f71095}{Uniform\+Sampler} (double lower, double upper)
\begin{DoxyCompactList}\small\item\em The constructor. \end{DoxyCompactList}\item
double \hyperlink{classdensities_1_1UniformSampler_a1c4ab518cac3aecb0f4aa199cbc7a312}{sample} ()
\begin{DoxyCompactList}\small\item\em Draws a sample. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
A class that performs sampling from a continuous uniform distribution.

\begin{DoxyAuthor}{Author}
taylor
\end{DoxyAuthor}
\begin{DoxyDate}{Date}
04/05/17
\end{DoxyDate}

\subsection{Constructor \& Destructor Documentation}
\index{densities\+::\+Uniform\+Sampler@{densities\+::\+Uniform\+Sampler}!Uniform\+Sampler@{Uniform\+Sampler}}
\index{Uniform\+Sampler@{Uniform\+Sampler}!densities\+::\+Uniform\+Sampler@{densities\+::\+Uniform\+Sampler}}
\subsubsection[{\texorpdfstring{Uniform\+Sampler(double lower, double upper)}{UniformSampler(double lower, double upper)}}]{\setlength{\rightskip}{0pt plus 5cm}densities\+::\+Uniform\+Sampler\+::\+Uniform\+Sampler (
\begin{DoxyParamCaption}
\item[{double}]{lower, }
\item[{double}]{upper}
\end{DoxyParamCaption}
)}\hypertarget{classdensities_1_1UniformSampler_a8dbc3ef50efd8b6b9aa64819f7f71095}{}\label{classdensities_1_1UniformSampler_a8dbc3ef50efd8b6b9aa64819f7f71095}

The constructor.

\begin{DoxyParams}{Parameters}
{\em lower} & the lower bound of the P\+R\+NG. \\
\hline
{\em upper} & the upper bound of the P\+R\+NG. \\
\hline
\end{DoxyParams}

\subsection{Member Function Documentation}
\index{densities\+::\+Uniform\+Sampler@{densities\+::\+Uniform\+Sampler}!sample@{sample}}
\index{sample@{sample}!densities\+::\+Uniform\+Sampler@{densities\+::\+Uniform\+Sampler}}
\subsubsection[{\texorpdfstring{sample()}{sample()}}]{\setlength{\rightskip}{0pt plus 5cm}double densities\+::\+Uniform\+Sampler\+::sample (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\hypertarget{classdensities_1_1UniformSampler_a1c4ab518cac3aecb0f4aa199cbc7a312}{}\label{classdensities_1_1UniformSampler_a1c4ab518cac3aecb0f4aa199cbc7a312}

Draws a sample.

\begin{DoxyReturn}{Returns}
a sample of type double.
\end{DoxyReturn}

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
include/\hyperlink{densities_8h}{densities.\+h}\end{DoxyCompactItemize}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of toolbar</title>
  <meta name="keywords" content="toolbar">
  <meta name="description" content="handle input">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../../../m2html.css">

Home >  .. > SMASHtoolbox > +SMASH > +MUI > @Figure > old > toolbar.m

toolbar

PURPOSE

handle input

SYNOPSIS

function toolbar(fig)

DESCRIPTION

 handle input

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

MinimalFigure	MinimalFigure: create a minimalistic figure useful for GUIs

slice

SOURCE CODE

0001 function toolbar(fig)
0002
0003 % handle input
0004 if (nargin<1) || isempty(fig)
0005     fig=gcf;
0006 end
0007
0008 % create toolbar
0009 data=[];
0010 hb=uitoolbar('Parent',fig,'Tag','MinimalFigureToolbar','UserData',data,...
0011     'DeleteFcn',@DeleteMinimalFigure);
0012
0013 % create push buttons
0014 uipushtool('Parent',hb,'Tag','directory',...
0015     'ToolTipString','Set working directory',...
0016     'CData',local_graphic('FolderIcon'),'ClickedCallback',@ButtonClick);
0017
0018 uipushtool('Parent',hb,'Tag','save','ToolTipString','Save figure',...
0019     'Cdata',local_graphic('SaveIcon'),'ClickedCallback',@ButtonClick);%,'Visible','off');
0020
0021 uitoggletool('Parent',hb,'Tag','zoom','ToolTipString','Zoom',...
0022     'Cdata',local_graphic('ZoomIcon'),'Separator','on',...
0023     'ClickedCallback',@ToggleButton);
0024
0025 uitoggletool('Parent',hb,'Tag','pan','ToolTipString','Pan',...
0026     'Cdata',local_graphic('PanIcon'),...
0027     'ClickedCallback',@ToggleButton);
0028
0029 % callbacks
0030
0031 end

<address>Generated on Tue 10-Nov-2020 17:53:50 by m2html © 2005</address>


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Avenue Victor Hugo</title>
    <meta name="description" content="Webdocumentaire sur Paris vu par... 50 ans après !">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" sizes="57x57" href="img/favicon/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="img/favicon/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="img/favicon/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="img/favicon/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="img/favicon/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="img/favicon/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="img/favicon/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="img/favicon/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="img/favicon/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="img/favicon/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="img/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="img/favicon/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="img/favicon/favicon-16x16.png">
    <link rel="manifest" href="img/favicon/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="img/favicon/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

    <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' type='text/css'>
    <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Advent+Pro:400,700' type='text/css'>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="bootstrap/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="jquery/css/jquery-ui.min.css">
    <link rel="stylesheet" href="jquery/css/jquery-ui.structure.min.css">
    <link rel="stylesheet" href="jquery/css/jquery-ui.theme.min.css">
    <link rel="stylesheet" href="css/custom.css">

Aujourd'hui

            Deux lieux de cette avenue méritent le coup d'œil : la façade du restaurant Prunier et la Cité de l'Argentine.
            La première est l'œuvre magnifique du mosaïste Auguste Labouret. Classée monument historique depuis 1992,
            cette incroyable façade de mosaïque bleue ne présente aucune répétition. Elle fait écho aux produits de la mer servis par Prunier et
            l'on y aperçoit en filigrane des étoiles, des poissons ou encore des méduses.
            La deuxième, la Cité de l'Argentine, est une galerie commerciale dont les éléments en fonte s'inspirent du style Art Nouveau.
            Conçue par Henri Sauvage et Charles Sarrazin en 1904 pour le compte de l'argentin Mayol de Senillosa, elle y accueille toujours sous sa verrière de nombreux commerces.

Hier

                A l'origine l'avenue se nommait avenue d'Eylau.
                Victor Hugo écrivain, poète et homme politique français, a connu de son vivant une très forte reconnaissance populaire et officielle.
                Il a vécu les dernières années de sa vie dans un hôtel de l'avenue Victor-Hugo, au numéro 502, aujourd'hui 124.
                Ainsi lui adressait-on son courrier libellé : « À monsieur Victor Hugo, En son avenue, à Paris ».
                C'est pour son 80ème anniversaire que l'avenue dans laquelle il habitait : l'avenue d'Eylau a été rebaptisé en son nom : l'avenue Victor Hugo.
                L'avenue Victor Hugo est plantée d'arbres et ornée de la statue de l'écrivain à son carrefour avec l'avenue Henre-Martin.
                Ignacy Paderewski, Premier ministre polonais et pianiste, a vécu de 1889 à 1906, au numéro 94 de cette avenue.


text:
No.

The AZ of a disk cannot be changed after you have created the disk. If you want to change the AZ, delete the disk and create a new one.


text:
/** @externs */
/**
 * @externs
 * @suppress {duplicate,checkTypes}
 */
// NOTE: generated by tsickle, do not edit.
// externs from /private/var/folders/7d/r6b3nrdj7bn9t_w_dclm6y9r00kg80/T/angular-release-latest.XXXXXXX.FjdRL2Ds/sandbox/darwin-sandbox/345/execroot/angular/packages/router/src/utils/preactivation.ts:
/** @const */
var angular$packages$router$src$utils$preactivation = {};

/** @typedef {?} */
angular$packages$router$src$utils$preactivation.Checks;
// externs from /private/var/folders/7d/r6b3nrdj7bn9t_w_dclm6y9r00kg80/T/angular-release-latest.XXXXXXX.FjdRL2Ds/sandbox/darwin-sandbox/345/execroot/angular/packages/router/src/operators/prioritized_guard_value.ts:
/** @const */
var angular$packages$router$src$operators$prioritized_guard_value = {};

/** @typedef {?} */
var INTERIM_VALUES;


text:
'use strict';

const escape = require('regexp.escape');
const pumpify = require('pumpify');
const replace = require('gulp-regexp-sourcemaps');

/* eslint-disable */
const POLYMER_BSD_FULL = [
'This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt',
'The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt',
'The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt',
'Code distributed by Google as part of the polymer project is also',
'subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt',
].join('\n ');

const BSD_SHORT = [
'Use of this source code is governed by a BSD-style',
'license that can be found in the LICENSE file or at',
'https://developers.google.com/open-source/licenses/bsd',
].join('\n ');

/* eslint-enable */

const LICENSES = [[POLYMER_BSD_FULL, BSD_SHORT]];

const PATHS = ['third_party/webcomponentsjs/ShadowCSS.js'];

/**
 * We can replace full-text of standard licenses with a pre-approved shorten
 * version.
 * @return {!Pumpify}
 */
exports.shortenLicense = function() {
  const streams = LICENSES.map(tuple => {
    const regex = new RegExp(escape(tuple[0]), 'g');
    return replace(regex, tuple[1], 'shorten-license');
  });

  // Pumpify requires at least 2 streams
  if (streams.length === 1) {
    return streams[0];
  }
  return pumpify.obj(streams);
};

/**
 * Returns true if a source file has a license that needs to be shortened.
 * @param {!Vinyl} file
 * @return {boolean}
 */
exports.shouldShortenLicense = function(file) {
  return PATHS.some(path => file.path.endsWith(path));
};


text:
import {buffer, KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';

import {MathBackendWebGL} from '../backend_webgl';
import {stridedSliceImplCPU} from '../kernel_utils/shared';
import {StridedSliceProgram} from '../strided_slice_gpu';

import {reshape} from './Reshape';
import {slice} from './Slice';

export function stridedSlice(args: {
  inputs: StridedSliceInputs,
  backend: MathBackendWebGL,
  attrs: StridedSliceAttrs
}): TensorInfo {
  const {inputs, backend, attrs} = args;
  const {x} = inputs;
  const {
    begin,
    end,
    strides,
    beginMask,
    endMask,
    ellipsisMask,
    newAxisMask,
    shrinkAxisMask
  } = attrs;

  const {
    finalShapeSparse,
    finalShape,
    isIdentity,
    sliceDim0,
    isSimpleSlice,
    begin: $begin,
    end: $end,
    strides: $strides
  } =
      slice_util.sliceInfo(
          x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,
          newAxisMask, shrinkAxisMask);

  let result;

  if (isIdentity) {
    // Optimization #1, slice is a no-op plus reshape
    result = reshape({inputs: {x}, backend, attrs: {shape: finalShape}});
  } else if (sliceDim0 || isSimpleSlice) {
    // Optimization #2, slice is memory contiguous (only occurs in dim 0)
    util.assert(
        x.shape.length >= 1,
        () => `Input must have rank at least 1, got: ${x.shape.length}`);

    const size = slice_util.computeOutShape($begin, $end, $strides);
    // To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).
    const sliced = slice({inputs: {x}, backend, attrs: {begin: $begin, size}});
    result =
        reshape({inputs: {x: sliced}, backend, attrs: {shape: finalShape}});
    backend.disposeIntermediateTensorInfo(sliced);
  } else {
    const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);
    if (shouldExecuteOnCPU) {
      // tslint:disable-next-line: no-unnecessary-type-assertion
      const values = backend.readSync(x.dataId) as TypedArray;
      // tslint:disable-next-line: no-unnecessary-type-assertion
      const xBuf = buffer(x.shape, x.dtype, values) as TensorBuffer<Rank>;
      const resultValues =
          stridedSliceImplCPU(finalShapeSparse, xBuf, $strides, $begin);
      result = backend.makeTensorInfo(finalShape, x.dtype, resultValues.values);
    } else {
      const program =
          new StridedSliceProgram($begin, $strides, finalShapeSparse);
      result = backend.runWebGLProgram(program, [x], x.dtype);
    }
  }

  const resultReshaped =
      reshape({inputs: {x: result}, backend, attrs: {shape: finalShape}});

  backend.disposeIntermediateTensorInfo(result);

  return resultReshaped;
}

export const stridedSliceConfig: KernelConfig = {
  kernelName: StridedSlice,
  backendName: 'webgl',
  kernelFunc: stridedSlice as {} as KernelFunc
};


text: ActionView::Base.send(:include, Paypal::Helpers)


text:
#include <aws/ec2/model/ScheduledInstancesMonitoring.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace EC2
{
namespace Model
{

ScheduledInstancesMonitoring::ScheduledInstancesMonitoring() :
    m_enabled(false),
    m_enabledHasBeenSet(false)
{
}

ScheduledInstancesMonitoring::ScheduledInstancesMonitoring(const XmlNode& xmlNode) :
    m_enabled(false),
    m_enabledHasBeenSet(false)
{
  *this = xmlNode;
}

ScheduledInstancesMonitoring& ScheduledInstancesMonitoring::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode enabledNode = resultNode.FirstChild("Enabled");
    if(!enabledNode.IsNull())
    {
      m_enabled = StringUtils::ConvertToBool(StringUtils::Trim(enabledNode.GetText().c_str()).c_str());
      m_enabledHasBeenSet = true;
    }
  }

  return *this;
}

void ScheduledInstancesMonitoring::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_enabledHasBeenSet)
  {
      oStream << location << index << locationValue << ".Enabled=" << std::boolalpha << m_enabled << "&";
  }

}

void ScheduledInstancesMonitoring::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_enabledHasBeenSet)
  {
      oStream << location << ".Enabled=" << std::boolalpha << m_enabled << "&";
  }
}

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
from .core import unify, reify
from .variable import var, isvar
from .utils import _toposort, freeze
from toolz import groupby, first

class Dispatcher(object):
    def __init__(self, name):
        self.name = name
        self.funcs = dict()
        self.ordering = []

    def add(self, signature, func):
        self.funcs[freeze(signature)] = func
        self.ordering = ordering(self.funcs)

    def __call__(self, *args, **kwargs):
        func, s = self.resolve(args)
        return func(*args, **kwargs)

    def resolve(self, args):
        n = len(args)
        for signature in self.ordering:
            if len(signature) != n:
                continue
            s = unify(freeze(args), signature)
            if s is not False:
                result = self.funcs[signature]
                return result, s
        raise NotImplementedError("No match found. \nKnown matches: "
                + str(self.ordering) + "\nInput: " + str(args))

    def register(self, *signature):
        def _(func):
            self.add(signature, func)
            return self
        return _

class VarDispatcher(Dispatcher):
    """ A dispatcher that calls functions with variable names

    >>> d = VarDispatcher('d')
    >>> x = var('x')

    >>> @d.register('inc', x)
    ... def f(x):
    ...     return x + 1

    >>> @d.register('double', x)
    ... def f(x):
    ...     return x * 2

    >>> d('inc', 10)
    11

    >>> d('double', 10)
    20
    """
    def __call__(self, *args, **kwargs):
        func, s = self.resolve(args)
        d = dict((k.token, v) for k, v in s.items())
        return func(**d)

global_namespace = dict()

def match(*signature, **kwargs):
    namespace = kwargs.get('namespace', global_namespace)
    dispatcher = kwargs.get('Dispatcher', Dispatcher)
    def _(func):
        name = func.__name__

        if name not in namespace:
            namespace[name] = dispatcher(name)
        d = namespace[name]

        d.add(signature, func)

        return d
    return _

def supercedes(a, b):
    """ ``a`` is a more specific match than ``b`` """
    if isvar(b) and not isvar(a):
        return True
    s = unify(a, b)
    if s is False:
        return False
    s = dict((k, v) for k, v in s.items() if not isvar(k) or not isvar(v))
    if reify(a, s) == a:
        return True
    if reify(b, s) == b:
        return False

# Taken from multipledispatch
def edge(a, b, tie_breaker=hash):
    """ A should be checked before B

    Tie broken by tie_breaker, defaults to ``hash``
    """
    if supercedes(a, b):
        if supercedes(b, a):
            return tie_breaker(a) > tie_breaker(b)
        else:
            return True
    return False

# Taken from multipledispatch
def ordering(signatures):
    """ A sane ordering of signatures to check, first to last

    Topoological sort of edges as given by ``edge`` and ``supercedes``
    """
    signatures = list(map(tuple, signatures))
    edges = [(a, b) for a in signatures for b in signatures if edge(a, b)]
    edges = groupby(first, edges)
    for s in signatures:
        if s not in edges:
            edges[s] = []
    edges = dict((k, [b for a, b in v]) for k, v in edges.items())
    return _toposort(edges)


text:
function render_visualize_exif() {
    row_selector($('#rowPrefixDrop'), {startRow: $('#startRow'), stopRow: $('#stopRow')});
    $('#runButton').click(function () {
        var startRow = unescape($('#startRow').val());
        var stopRow = unescape($('#stopRow').val());
        var max_size = Number($('#maxSize').val());
        var exif_column = 'meta:exif';
        if (startRow.length == 0 || stopRow.length == 0) {
            display_alert('Must specify rows');
            return;
        }
        images = new PicarusRows([], {'table': 'images'});
        function done() {
            $('#results').html('');
            if (!images.length)
                return;
            // TODO: Change to use RowsView
            var AppView = Backbone.View.extend({
                initialize: function() {
                    _.bindAll(this, 'render');
                    this.collection.bind('reset', this.render);
                    this.collection.bind('change', this.render);
                    this.collection.bind('add', this.render);
                },
                render: function() {
                    var cur_images = this.collection.filter(function (x) {return x.get(exif_column) != '{}' && !_.isUndefined(x.get(exif_column))});
                    columns = _.uniq(_.flatten(_.map(cur_images, function (x) {
                        return _.keys(JSON.parse(x.get(exif_column)));
                    }))).concat(['row']);
                    picarus_table = new Backbone.Table({
                        collection: this.collection,
                        columns: _.map(columns, function (v) {
                            if (v === "row")
                                return [v, v];
                            return {header: v, getFormatted: function() {
                                var cur_exif = JSON.parse(this.get(exif_column));
                                var out = cur_exif[v];
                                if (typeof out !== 'undefined') {
                                    if (!_.isString(out))
                                        return _.escape(JSON.stringify(out));
                                    out = base64.decode(out);
                                    if (typeof out.length <= max_size)
                                        return _.escape(out);
                                    else
                                        return '' + _.escape(out.slice(0, max_size)) + ''
                                }
                            }};
                        })
                    });
                    this.$el.html(picarus_table.render().el);
                }
            });
            av = new AppView({collection: images, el: $('#results')});
            av.render();
        }
        function success(row, columns) {
            columns.row = row;
            if (columns[exif_column] != '{}')
                images.add(columns);
        }
        var params = {success: success, maxRows: 1000, done: done, columns: [exif_column]};
        PICARUS.scanner("images", startRow, stopRow, params)
    });
}


text:
title:  Att vila i löftena
date:  17/06/2021
---

Det finns en berättelse om den kände kardinalen Bellarmine, en stor katolsk apologet som hela sitt liv kämpade mot budskapet om rättfärdiggörelse enbart genom tron. När han låg för döden förde man till honom krucifix och helgonens meriter för att hjälpa honom att finna en trygghet inför döden. Men Bellarmine sade: "Ta bort de där. Jag tror att det är tryggare att lita på Kristus meriter."

Många som närmar sig slutet av sitt liv ser tillbaka och inser hur meningslösa, fåfänga och onödiga deras gärningar och handlingar är när det gäller att förtjäna frälsning hos en helig Gud. De inser hur mycket de behöver Kristus rättfärdighet.

Men de goda nyheterna är att vi inte behöver vänta tills döden närmar sig för att finna trygghet i Herren. Hela förbundet är grundat på Guds säkra löften till oss nu, löften som kan göra vårt liv bättre redan nu.

`Läs följande texter och fundera på hur du kan utveckla, bevara och stärka din relation med Gud:`

`Ps. 34:9 (Hur kan du smaka Herrens godhet?)`

`Matt. 11:28-30 (På vilket område vill Jesus lätta din börda?)`

`Rom. 5:1 (Hur hänger rättfärdighet genom tro ihop med frid?)`

`Fil. 2:7, 8 (Vad betyder det för dig att Jesus var beredd att göra detta?)`

Be, fundera kring ditt liv och fråga dig själv: Vad gör jag redan nu som stärker min relation med Gud? Finns det något jag gör som skadar den? Är det något jag vill förändra för att min relation med Gud ska bli ännu bättre?


text:
puts "Installing jqGrid, jquery, jqueryui javascripts and stylesheets..."

FileUtils.mkdir_p(js_dir = Rails.root.join('public', 'javascripts', 'grid_widget'))
FileUtils.mkdir_p(css_dir = Rails.root.join('public', 'stylesheets', 'grid_widget'))

puts "Copying Javascript to " + js_dir.to_s

FileUtils.cp_r File.join(File.dirname(__FILE__), 'lib', 'public', 'javascripts'), js_dir

puts "Copying Stylesheets and images to " + css_dir.to_s

FileUtils.cp_r File.join(File.dirname(__FILE__), 'lib', 'public', 'stylesheets'), css_dir

puts "Files copied."


text:
<?php

namespace Club\UtilidadBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('UtilidadBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
export default function locate(source, index) {
	var lines = source.split('\n');
	var len = lines.length;

	var lineStart = 0;
	var i;

	for (i = 0; i < len; i += 1) {
		var line = lines[i];
		var lineEnd = lineStart + line.length + 1; // +1 for newline

		if (lineEnd > index) {
			return { line: i + 1, column: index - lineStart, char: i };
		}

		lineStart = lineEnd;
	}

	throw new Error('Could not determine location of character');
}


text:
package org.jasig.portal.events;

import java.util.List;
import java.util.Map;

/**
 * @author Eric Dalquist
 * @version $Revision$
 */
public final class PortletRenderHeaderExecutionEvent extends PortletExecutionEvent {
    private static final long serialVersionUID = 1L;

    private final boolean targeted;
    private final boolean cached;

    @SuppressWarnings("unused")
    private PortletRenderHeaderExecutionEvent() {
        this.targeted = false;
        this.cached = false;
    }

    PortletRenderHeaderExecutionEvent(PortalEventBuilder eventBuilder, String fname, long executionTime, Map<String, List<String>> parameters, boolean targeted, boolean cached) {
        super(eventBuilder, fname, executionTime, parameters);
        this.targeted = targeted;
        this.cached = cached;
    }

    /**
     * @return If the portlet was explicitly targeted by the request that resulted in it rendering
     */
    public boolean isTargeted() {
        return this.targeted;
    }

    /**
     * @return If the rendering was from cache
     */
    public boolean isCached() {
        return this.cached;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return super.toString() +
                ", targeted=" + this.targeted +
                ", cached=" + this.cached + "]";
    }
}


text:
import { WorldReader } from './format/WorldFormat'
import { World } from './World'
import { SimpleWorldReader, SimpleWorldFormatChecker, SimpleWorldWriter } from './format/SimpleWorldFormat'
import { InvalidWorldError } from './error/InvalidWorldError'
import { Vokkit } from '../Vokkit'
import { InvalidWorldFormatError } from './error/InvalidWorldFormatError'
import { Logger } from '../utils/Logger'

import fs from 'fs'
import path from 'path'

export class WorldLoader {
  static worldDirectory = path.resolve('worlds')

  static loadAllWorlds () {
    const worlds: World[] = []
    const worldPathList = fs.readdirSync(this.worldDirectory)
    worldPathList.forEach((worldPath) => {
      try {
        Logger.info(Vokkit.getServer().getLanguageFormatter().format('world_loading_started', { worldPath }))
        worlds.push(this.load(path.join(this.worldDirectory, worldPath)))
        Logger.info(Vokkit.getServer().getLanguageFormatter().format('world_loaded', { worldPath }))
      } catch (error) {
        Logger.error(Vokkit.getServer().getLanguageFormatter().format('world_error_while_loading', { error }))
      }
    })
    return worlds
  }

  static load (worldDirectory: string) {
    const formatPath = path.join(worldDirectory, 'format.txt')
    if (!fs.existsSync(formatPath)) {
      throw new InvalidWorldError(Vokkit.getServer().getLanguageFormatter().format('world_format_file_not_exist'))
    }
    const { reader } = this.getFormatFromName(fs.readFileSync(formatPath).toString())
    return reader.read(worldDirectory)
  }

  static getFormatFromName (format: string) {
    switch (format) {
      case 'SimpleWorldFormat': {
        return {
          reader: SimpleWorldReader,
          formatChecker: SimpleWorldFormatChecker,
          writer: SimpleWorldWriter
        }
      }
      default: {
        throw new InvalidWorldFormatError(Vokkit.getServer().getLanguageFormatter().format('world_unknown_format_name', { format }))
      }
    }
  }
}


text:
/**
 * Fix most common html formatting misbehaviors of browsers implementation when inserting
 * content via copy & paste contentEditable
 *
 * @author Christopher Blum
 */
wysihtml.quirks.cleanPastedHTML = (function() {

  var styleToRegex = function (styleStr) {
    var trimmedStr = wysihtml.lang.string(styleStr).trim(),
        escapedStr = trimmedStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

    return new RegExp("^((?!^" + escapedStr + "$).)*$", "i");
  };

  var extendRulesWithStyleExceptions = function (rules, exceptStyles) {
    var newRules = wysihtml.lang.object(rules).clone(true),
        tag, style;

    for (tag in newRules.tags) {

      if (newRules.tags.hasOwnProperty(tag)) {
        if (newRules.tags[tag].keep_styles) {
          for (style in newRules.tags[tag].keep_styles) {
            if (newRules.tags[tag].keep_styles.hasOwnProperty(style)) {
              if (exceptStyles[style]) {
                newRules.tags[tag].keep_styles[style] = styleToRegex(exceptStyles[style]);
              }
            }
          }
        }
      }
    }

    return newRules;
  };

  var pickRuleset = function(ruleset, html) {
    var pickedSet, defaultSet;

    if (!ruleset) {
      return null;
    }

    for (var i = 0, max = ruleset.length; i < max; i++) {
      if (!ruleset[i].condition) {
        defaultSet = ruleset[i].set;
      }
      if (ruleset[i].condition && ruleset[i].condition.test(html)) {
        return ruleset[i].set;
      }
    }

    return defaultSet;
  };

  return function(html, options) {
    var exceptStyles = {
          'color': wysihtml.dom.getStyle("color").from(options.referenceNode),
          'fontSize': wysihtml.dom.getStyle("font-size").from(options.referenceNode)
        },
        rules = extendRulesWithStyleExceptions(pickRuleset(options.rules, html) || {}, exceptStyles),
        newHtml;

    newHtml = wysihtml.dom.parse(html, {
      "rules": rules,
      "cleanUp": true, // <span> elements, empty or without attributes, should be removed/replaced with their content
      "context": options.referenceNode.ownerDocument,
      "uneditableClass": options.uneditableClass,
      "clearInternals" : true, // don't paste temprorary selection and other markings
      "unjoinNbsps" : true
    });

    return newHtml;
  };

})();


text:
class ModificationOperationResult(object):
    """NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually."""

    def __init__(self):
        """
        Attributes:
          swaggerTypes (dict): The key is attribute name and the value is attribute type.
          attributeMap (dict): The key is attribute name and the value is json key in definition.
        """
        self.swaggerTypes = {
            'Source': 'Link',
            'Dest': 'Link'

        }

        self.attributeMap = {
            'Source': 'Source','Dest': 'Dest'}

        self.Source = None # Link
        self.Dest = None # Link


text:
using System;

namespace Azure.Storage.Files.Shares.Models
{
    /// <summary> An Access policy. </summary>
    public partial class ShareAccessPolicy
    {
        /// <summary> Initializes a new instance of ShareAccessPolicy. </summary>
        public ShareAccessPolicy()
        {
        }

        /// <summary> Initializes a new instance of ShareAccessPolicy. </summary>
        /// <param name="policyStartsOn"> The date-time the policy is active. </param>
        /// <param name="policyExpiresOn"> The date-time the policy expires. </param>
        /// <param name="permissions"> The permissions for the ACL policy. </param>
        internal ShareAccessPolicy(DateTimeOffset? policyStartsOn, DateTimeOffset? policyExpiresOn, string permissions)
        {
            PolicyStartsOn = policyStartsOn;
            PolicyExpiresOn = policyExpiresOn;
            Permissions = permissions;
        }
    }
}