text:
package org.wikipedia.page.gallery;

import org.json.JSONObject;
import org.mediawiki.api.json.Api;
import org.mediawiki.api.json.RequestBuilder;
import org.wikipedia.Constants;
import org.wikipedia.Site;
import org.wikipedia.page.PageQueryTask;
import org.wikipedia.page.PageTitle;

import java.util.Map;

public abstract class GalleryCollectionFetchTask extends PageQueryTask<GalleryItem> {
    private static final String MAX_ITEM_COUNT = "256";
    private final boolean getThumbs;

    public GalleryCollectionFetchTask(Api api, Site site, PageTitle title) {
        this(api, site, title, false);
    }

    public GalleryCollectionFetchTask(Api api, Site site, PageTitle title, boolean getThumbs) {
        super(api, site, title);
        this.getThumbs = getThumbs;
    }

    @Override
    public void buildQueryParams(RequestBuilder builder) {
        builder.param("prop", "imageinfo")
               .param("iiprop", getThumbs ? "dimensions|mime|url" : "dimensions|mime")
               .param("generator", "images")
               .param("redirects", "")
               .param("gimlimit", MAX_ITEM_COUNT);
        // If we've been asked to retrieve the thumbnail url for each of the images, then
        // we need to specify the width and height of the thumbnails. Otherwise, we would
        // just get the name of each image, and we would need to send a separate request
        // to get the url (and other info) for the image.
        if (getThumbs) {
            builder.param("iiurlwidth", Integer.toString(Constants.PREFERRED_THUMB_SIZE))
                    .param("iiurlheight", Integer.toString(Constants.PREFERRED_THUMB_SIZE));
        }
    }

    @Override
    public GalleryItem processPage(int pageId, PageTitle pageTitle, JSONObject pageData) throws Throwable {
        return new GalleryItem(pageData);
    }

    @Override
    public void onFinish(Map<PageTitle, GalleryItem> result) {
        GalleryCollection collection = new GalleryCollection(result);
        onGalleryResult(collection);
    }

    public abstract void onGalleryResult(GalleryCollection result);
}


text:
<md-card ng-show="vm.hasData">
    <md-toolbar style="padding: 0 1rem;">

    </md-toolbar>
    <md-card-content>

{{ 'CASE.CASE' | translate }}: {{ vm.case["oe:id"].value }}

{{ 'CASE.CREATED_BY' | translate: {at:vm.dateFlt(vm.case["cm:created"].value), by:vm.case["cm:creator"].fullname} }}

{{ 'CASE.MODIFIED_BY' | translate: {at:vm.dateFlt(vm.case["cm:modified"].value), by:vm.case["cm:modifier"].fullname} }}

{{ vm.case["cm:title"].value }}

{{ vm.case["cm:description"].value }}

    </md-card-content>

        {{ 'CASE.VIEW_CASE_DETAILS' | translate }}

</md-card>

redpajama_set_name: RedPajamaGithub


text:
docker rm cyclus-local
docker run -w /cyclus --name cyclus-local -v $PWD:/cyclus cyclus/cyclus-deps bash -c "mkdir -p Debug && cd Debug && cmake .. && make -j2 && make install"
docker commit cyclus-local cyclus/cyclus:local


text:
const canvas = document.querySelector('canvas');

canvas.width = 500;
canvas.height = 500 + 300;

let dots = new CollectionDots(canvas);

let bullets = new Bullets(canvas, 6, 15, 10);

function start() {
  clear(canvas);
  circle(canvas, 1);
  dots.draw();
  if (bullets._move) {
    bullets.move();
    if (!bullets._move) {
      if (dots.add(90, 15, -0.75) === null)
        return;
      --bullets.count;
    }
  } else {
    bullets.draw();
  }
  window.requestAnimationFrame(start);
}

window.requestAnimationFrame(start);

canvas.addEventListener('click', () => {
  bullets.shoot();
});


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer">

<meta name="description" content="From time to time, I’m finding a need to record a portion of my desktop, upload it and share with somebody. On OSX, one way which worked for me was using a nifty tool called GifGrabber.
Available for free from the App Store, makes the whole process as painless as it can be. Features are limitied, but honestly - it has exactly what you want: you can capture a part of desktop, edit it, setting the starting point, and upload it to gfycat, getting a link in return.">

<meta property="og:title" content="Capturing gifs from desktop on OS X" />
<meta property="og:description" content="From time to time, I’m finding a need to record a portion of my desktop, upload it and share with somebody. On OSX, one way which worked for me was using a nifty tool called GifGrabber.
Available for free from the App Store, makes the whole process as painless as it can be. Features are limitied, but honestly - it has exactly what you want: you can capture a part of desktop, edit it, setting the starting point, and upload it to gfycat, getting a link in return." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://zerodivisible.io/blog/capturing-gifs-from-desktop-on-os-x/" />

<meta property="article:published_time" content="2015-01-11T00:04:03+00:00"/>

<meta property="article:modified_time" content="2015-01-11T00:04:03+00:00"/>

<title>

     Capturing gifs from desktop on OS X

</title>
<link rel="canonical" href="https://zerodivisible.io/blog/capturing-gifs-from-desktop-on-os-x/">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/styles/default.min.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Ubuntu+Mono:400,400i,700,700i|Raleway:500">

    <link rel="stylesheet" href="https://zerodivisible.io/css/reset.css">
    <link rel="stylesheet" href="https://zerodivisible.io/css/pygments.css">
    <link rel="stylesheet" href="https://zerodivisible.io/css/main.css">

<link rel="shortcut icon"

    href="https://zerodivisible.io/img/favicon.ico"

>

I hope I'll write some posts this time.

blog

about

code

    Capturing gifs from desktop on OS X

Jan 11, 2015

One minute read

From time to time, I’m finding a need to record a portion of my desktop, upload it and share with somebody. On OSX, one way which worked for me was using a nifty tool called GifGrabber.

Available for free from the App Store, makes the whole process as painless as it can be. Features are limitied, but honestly - it has exactly what you want: you can capture a part of desktop, edit it, setting the starting point, and upload it to gfycat, getting a link in return.

Awesome!

Highly recommended.

Back to posts

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Evolution Line Style</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="../css/evo-elements.css">

Evo

Line Style

Change the style of <hr /> horizontal rule lines.

line-[style]

line-solid

line-dotted

line-dashed

line-double

Create an <hr /> tag with an line-[style] class.

<hr class="line-solid" />
<hr class="line-dotted" />
<hr class="line-dashed" />
<hr class="line-double" />


text:
.. _usersguide_track:

=================
Track File Format
=================

The current revision of the particle track file format is 1.

**/filetype** (*char[]*)

    String indicating the type of file.

**/revision** (*int*)

    Revision of the track file format. Any time a change is made in the format,
    this integer is incremented.

**/n_particles** (*int*)

    Number of particles for which tracks are recorded.

**/n_coords** (*int[]*)

    Number of coordinates for each particle.

*do i = 1, n_particles*

    **/coordinates_i** (*double[][3]*)

        (x,y,z) coordinates for the *i*-th particle.


text:
<!DOCTYPE html>

          <?php
              require('side_menu.html');
          ?>

            Search Referred Patient Record
            Cash Sheet of the Patient

 Home

Dashboard

              <?php
              if(isset($suc)&&!empty($suc)){
                ?>

                  ×
                  Success!&nbsp&nbsp Information Added Successfully.

<?php
              }
               ?>
          <form action="<?php echo base_url(); ?>index.php/Fetch/index2" method="post" id="#formId" name="upload" enctype="multipart/form-data">

                  Patient ID / NRK ID / Patient Name / Referred Hospital Name
                  <input type="text" autocomplete="off" type="text" id="id" class="form-control" name="pat_id"  placeholder="Enter Referred ID / Patient ID / NRK ID / Patient Name / Referred Hospital Name" required="" >

                  <input  type="submit"  value="submit" name="submit"  class="btn btn-primary">

            </form>

       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
       <link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />
       <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css" />


text:
package dagger.internal.codegen;

import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.testing.compile.Compiler.javac;
import static java.util.stream.Collectors.joining;

import com.google.auto.value.processor.AutoAnnotationProcessor;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.testing.compile.Compiler;

/** {@link Compiler} instances for testing Dagger. */
final class Compilers {
  private static final String GUAVA = "guava";

  static final ImmutableList<String> CLASS_PATH_WITHOUT_GUAVA_OPTION =
      ImmutableList.of(
          "-classpath",
          Splitter.on(PATH_SEPARATOR.value())
              .splitToList(JAVA_CLASS_PATH.value())
              .stream()
              .filter(jar -> !jar.contains(GUAVA))
              .collect(joining(PATH_SEPARATOR.value())));

  /** Returns a compiler that runs the Dagger processor. */
  static Compiler daggerCompiler() {
    return javac().withProcessors(new ComponentProcessor(), new AutoAnnotationProcessor());
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Symbols
{
    public class WorkspaceSymbolsTests : AbstractLanguageServerProtocolTests
    {
        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_Class()
        {
            var markup =
@"class {|class:A|}
{
    void M()
    {
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Class, "A", locations["class"].Single())
            };

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "A").ConfigureAwait(false);
            AssertJsonEquals(expected, results);
        }

        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_Class_Streaming()
        {
            var markup =
@"class {|class:A|}
{
    void M()
    {
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Class, "A", locations["class"].Single())
            };

            using var progress = BufferedProgress.Create<LSP.SymbolInformation>(null);

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "A", progress).ConfigureAwait(false);

            Assert.Empty(results);

            results = progress.GetValues().ToArray();

            AssertJsonEquals(expected, results);
        }

        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_Method()
        {
            var markup =
@"class A
{
    void {|method:M|}()
    {
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Method, "M", locations["method"].Single())
            };

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "M").ConfigureAwait(false);
            AssertJsonEquals(expected, results);
        }

        [Fact(Skip = "GetWorkspaceSymbolsAsync does not yet support locals.")]
        // TODO - Remove skip & modify once GetWorkspaceSymbolsAsync is updated to support all symbols.
        // https://github.com/dotnet/roslyn/projects/45#card-20033822
        public async Task TestGetWorkspaceSymbolsAsync_Local()
        {
            var markup =
@"class A
{
    void M()
    {
        int {|local:i|} = 1;
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Variable, "i", locations["local"].Single())
            };

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "i").ConfigureAwait(false);
            AssertJsonEquals(expected, results);
        }

        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_MultipleKinds()
        {
            var markup =
@"class A
{
    int {|field:F|};
    void M()
    {
    }
    class {|class:F|}
    {
        int {|field:F|};
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Field, "F", locations["field"][0]),
                CreateSymbolInformation(LSP.SymbolKind.Class, "F", locations["class"].Single()),
                CreateSymbolInformation(LSP.SymbolKind.Field, "F", locations["field"][1])
            };

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "F").ConfigureAwait(false);
            AssertJsonEquals(expected, results);
        }

        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_MultipleDocuments()
        {
            var markups = new string[]
            {
@"class A
{
    void {|method:M|}()
    {
    }
}",
@"class B
{
    void {|method:M|}()
    {
    }
}"
            };

            using var workspace = CreateTestWorkspace(markups, out var locations);
            var expected = new LSP.SymbolInformation[]
            {
                CreateSymbolInformation(LSP.SymbolKind.Method, "M", locations["method"][0]),
                CreateSymbolInformation(LSP.SymbolKind.Method, "M", locations["method"][1])
            };

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "M").ConfigureAwait(false);
            AssertJsonEquals(expected, results);
        }

        [Fact]
        public async Task TestGetWorkspaceSymbolsAsync_NoSymbols()
        {
            var markup =
@"class A
{
    void M()
    {
    }
}";
            using var workspace = CreateTestWorkspace(markup, out var _);

            var results = await RunGetWorkspaceSymbolsAsync(workspace.CurrentSolution, "NonExistingSymbol").ConfigureAwait(false);
            Assert.Empty(results);
        }

        private static async Task<LSP.SymbolInformation[]> RunGetWorkspaceSymbolsAsync(Solution solution, string query, IProgress<LSP.SymbolInformation[]> progress = null)
        {
            var request = new LSP.WorkspaceSymbolParams
            {
                Query = query,
                PartialResultToken = progress
            };

            var queue = CreateRequestQueue(solution);
            return await GetLanguageServer(solution).ExecuteRequestAsync<LSP.WorkspaceSymbolParams, LSP.SymbolInformation[]>(queue, LSP.Methods.WorkspaceSymbolName,
                request, new LSP.ClientCapabilities(), null, CancellationToken.None);
        }
    }
}


text:
import * as _ from 'lodash';

export class EntryPoint {
  public url: string;
  public operations: Array<string> = [];

  constructor(public model: string = '') {}

  /**
   * @param {Array<string>|string} operations
   */
  addOperations(operations) {
    if ('string' === typeof operations) {
      operations = [operations];
    }
    if (true === Array.isArray(operations)) {
      this.operations = _.union(this.operations, operations);
    }
  }

}


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>113 nips-2003-Learning with Local and Global Consistency</title>

nips nips2003 nips2003-113 nips2003-113-reference knowledge-graph by maker-knowledge-mining

113 nips-2003-Learning with Local and Global Consistency

Source: pdf

Author: Dengyong Zhou, Olivier Bousquet, Thomas N. Lal, Jason Weston, Bernhard Schölkopf

Abstract: We consider the general problem of learning from labeled and unlabeled data, which is often called semi-supervised learning or transductive inference. A principled approach to semi-supervised learning is to design a classifying function which is sufficiently smooth with respect to the intrinsic structure collectively revealed by known labeled and unlabeled points. We present a simple algorithm to obtain such a smooth solution. Our method yields encouraging experimental results on a number of classification problems and demonstrates effective use of unlabeled data. 1

reference text

[1] J. R. Anderson. The architecture of cognition. Harvard Univ. press, Cambridge, MA, 1983.

[2] M. Belkin and P. Niyogi. Semi-supervised learning on manifolds. Machine Learning Journal, to appear.

[3] A. Blum and S. Chawla. Learning from labeled and unlabeled data using graph mincuts. In ICML, 2001.

[4] O. Chapelle, J. Weston, and B. Sch¨ lkopf. Cluster kernels for semi-supervised learno ing. In NIPS, 2002.

[5] D. DeCoste and B. Sch¨ lkopf. Training invariant support vector machines. Machine o Learning, 46:161–190, 2002.

[6] T. Joachims. Transductive learning via spectral graph partitioning. In ICML, 2003.

[7] J. Kandola, J. Shawe-Taylor, and N. Cristianini. Learning semantic similarity. In NIPS, 2002.

[8] R. I. Kondor and J. Lafferty. Diffusion kernels on graphs and other discrete input spaces. In ICML, 2002.

[9] A. Y. Ng, M. I. Jordan, and Y. Weiss. On spectral clustering: analysis and an algorithm. In NIPS, 2001.

[10] M. Seeger. Learning with labeled and unlabeled data. Technical report, The University of Edinburgh, 2000.

[11] J. Shrager, T. Hogg, and B. A. Huberman. Observation of phase transitions in spreading activation networks. Science, 236:1092–1094, 1987.

[12] A. Smola and R. I. Kondor. Kernels and regularization on graphs. In Learning Theory and Kernel Machines, Berlin - Heidelberg, Germany, 2003. Springer Verlag.

[13] M. Szummer and T. Jaakkola. Partially labeled classification with markov random walks. In NIPS, 2001.

[14] V. N. Vapnik. Statistical learning theory. Wiley, NY, 1998.

[15] X. Zhu, Z. Ghahramani, and J. Lafferty. Semi-supervised learning using gaussian fields and harmonic functions. In ICML, 2003.


text:
class CreateNodesServicesTable < ActiveRecord::Migration
  def up
    create_table :nodes_services, :id => false do |t|
      t.references :node
      t.references :service
    end
    add_index :nodes_services, [:node_id, :service_id]
    add_index :nodes_services, [:service_id, :node_id]
  end

  def down
  end
end


text:
package com.intellij.execution.process;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NotNull;

/** @deprecated use {@link KillableColoredProcessHandler#KillableColoredProcessHandler(GeneralCommandLine, boolean)} (to be removed in IDEA 16) */
@SuppressWarnings({"unused", "deprecation"})
public class RunnerWinProcess extends ProcessWrapper {

  private RunnerWinProcess(@NotNull Process originalProcess) {
    super(originalProcess);
  }

  /**
   * Sends Ctrl+C or Ctrl+Break event to the process.
   * @param softKill if true, Ctrl+C event will be sent (otherwise, Ctrl+Break)
   */
  public void destroyGracefully(boolean softKill) {
    RunnerMediator.destroyProcess(this, softKill);
  }

  @NotNull
  public static Process create(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
    if (!SystemInfo.isWindows) {
      throw new RuntimeException("RunnerWinProcess works on Windows only!");
    }
    boolean success = RunnerMediator.injectRunnerCommand(commandLine);
    Process process = commandLine.createProcess();
    return success ? new RunnerWinProcess(process) : process;
  }
}


text:
//
//  AGXDelegateForwarder.h
//  AGXCore
//
//  Created by Char Aznable on 2019/4/18.
//  Copyright © 2019 github.com/CharLemAznable. All rights reserved.
//

#ifndef AGXCore_AGXDelegateForwarder_h
#define AGXCore_AGXDelegateForwarder_h

#import "AGXArc.h"

// forwarder_interface
#define forwarder_interface(className, targetClassName, protocolName)   \
interface className : NSObject <protocolName>                           \
@property (nonatomic, AGX_WEAK) targetClassName *internalDelegate;      \
@property (nonatomic, AGX_WEAK) id<protocolName> externalDelegate;      \
@end

// forwarder_implementation
#define forwarder_implementation(className, targetClassName, protocolName)                              \
implementation className                                                                                \
- (AGX_INSTANCETYPE)initWithInternalDelegate:(targetClassName *)internalDelegate                        \
                            externalDelegate:(id<protocolName>)externalDelegate {                       \
    if AGX_EXPECT_T(self = [super init]) {                                                              \
        _internalDelegate = internalDelegate;                                                           \
        _externalDelegate = externalDelegate;                                                           \
    }                                                                                \
    return self;                                                                                \
}                                                                                \
- (void)dealloc {                                                                                \
    _internalDelegate = nil;                                                                            \
    _externalDelegate = nil;                                                                            \
    AGX_SUPER_DEALLOC;                                                                                \
}                                                                                \
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {                                      \
    return([super methodSignatureForSelector:aSelector] ?:                                              \
           [_internalDelegate methodSignatureForSelector:aSelector] ?:                                  \
           [(NSObject *)_externalDelegate methodSignatureForSelector:aSelector]);                       \
}                                                                                \
- (BOOL)respondsToSelector:(SEL)aSelector {                                                             \
    return([super respondsToSelector:aSelector] ||                                                      \
           [_internalDelegate respondsToSelector:aSelector] ||                                          \
           [(NSObject *)_externalDelegate respondsToSelector:aSelector]);                               \
}                                                                                \
- (void)forwardInvocation:(NSInvocation *)anInvocation {                                                \
    SEL aSelector = [anInvocation selector];                                                            \
    BOOL internalDelegateWillRespond = [_internalDelegate respondsToSelector:aSelector];                \
    BOOL externalDelegateWillRespond = [(NSObject *)_externalDelegate respondsToSelector:aSelector];    \
    if (internalDelegateWillRespond) [anInvocation invokeWithTarget:_internalDelegate];                 \
    if (externalDelegateWillRespond) [anInvocation invokeWithTarget:_externalDelegate];                 \
    if (!internalDelegateWillRespond && !externalDelegateWillRespond)                                   \
        [super forwardInvocation:anInvocation];                                                         \
}                                                                                \
- (id)forwardingTargetForSelector:(SEL)aSelector {                                                      \
    BOOL internalDelegateWillRespond = [_internalDelegate respondsToSelector:aSelector];                \
    BOOL externalDelegateWillRespond = [(NSObject *)_externalDelegate respondsToSelector:aSelector];    \
    if (internalDelegateWillRespond && !externalDelegateWillRespond) return _internalDelegate;          \
    if (externalDelegateWillRespond && !internalDelegateWillRespond) return _externalDelegate;          \
    return nil;                                                                                \
}                                                                                \
@end

#endif /* AGXCore_AGXDelegateForwarder_h */


text:
<!DOCTYPE html>

    <title>那些碎碎念</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
    <meta content="yes" name="apple-mobile-web-app-capable"/>
    <meta content="black" name="apple-mobile-web-app-status-bar-style"/>

    <link href="../themes/foghorn/foghorn.css" type="text/css" rel="stylesheet"/>

文章列表

                    聊聊管理

                    我们这一代人的困惑


text:
describe('setting: disable', function() {
  beforeEach(() => {
    cy.visit('/');
  });

  it('Should properly disable AOS', function() {
    cy.initAOS({
      disable: true
    });

    cy.get('.aos-item[data-aos]').should('have.length', 0);
    cy.get('.aos-init').should('have.length', 0);
    cy.get('.aos-animate').should('have.length', 0);
  });

  it('Should respect function passed as "disable" value', function() {
    cy.viewport(360, 420);

    cy.window().then(({ AOS, innerWidth }) => {
      AOS.init({
        disable: () => innerWidth < 400
      });
    });

    cy.get('.aos-item[data-aos]').should('have.length', 0);
    cy.get('.aos-init').should('have.length', 0);
    cy.get('.aos-animate').should('have.length', 0);
  });
});


text:
'use strict';

import {IQuickFixSupport, IQuickFix} from 'vs/editor/common/modes';
import LanguageFeatureRegistry from 'vs/editor/common/modes/languageFeatureRegistry';

const QuickFixRegistry = new LanguageFeatureRegistry<IQuickFixSupport>('quickFixSupport');

export default QuickFixRegistry;

export interface IQuickFix2 extends IQuickFix {
	support: IQuickFixSupport;
}


text:
package org.immutables.mongo.fixture.ent;

import com.google.common.base.Optional;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.GsonBuilder;
import com.mongodb.MongoClient;
import java.util.concurrent.Executors;
import org.immutables.gson.Gson.TypeAdapters;
import org.immutables.mongo.Mongo.Repository;
import org.immutables.mongo.fixture.ent.EntRepository.Criteria;
import org.immutables.mongo.repository.RepositorySetup;
import org.immutables.mongo.types.TimeInstant;
import org.immutables.value.Value.Immutable;

@Immutable
@Repository
@TypeAdapters
public abstract class Ent {
  public abstract String uuid();

  public abstract String action();

  public abstract Optional<TimeInstant> expires();

  public static void main(String... args) {
    MongoClient client = new MongoClient("localhost");
    RepositorySetup setup = RepositorySetup.builder()
        .database(client.getDatabase("test"))
        .executor(MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()))
        .gson(new GsonBuilder()
            .registerTypeAdapterFactory(new GsonAdaptersEnt())
            .create())
        .build();

    EntRepository repository = new EntRepository(setup);

    EntRepository.Criteria where = repository.criteria()
        .uuid("8b7a881c-6ccb-4ada-8f6a-60cc99e6aa20")
        .actionIn("BAN", "IPBAN");

    Criteria or = where.expiresAbsent()
        .or()
        .with(where)
        .expiresGreaterThan(TimeInstant.of(1467364749679L));

    System.out.println(or);

    repository.find(or).fetchAll().getUnchecked();
  }
}


text:
namespace Runtime
{
    using System;

    public interface IValueProvider
    {
        object GetValue();
    }
}


text:
layout: post
title: Infographic semi-done
---

![infographic]({{site.baseurl}}/images/flatbody.png)
![infographic]({{site.baseurl}}/images/flatbody1.png)
![infographic]({{site.baseurl}}/images/flatbody2.png)
![infographic]({{site.baseurl}}/images/flatbody3.png)
![infographic]({{site.baseurl}}/images/flatbody4.png)
![infographic]({{site.baseurl}}/images/flatbody5.png)
![infographic]({{site.baseurl}}/images/flatbody6.png)
Infographic for making body of the lamp
blank space is to place REAL photograph of our models into

![infographic]({{site.baseurl}}/images/flatelectronic.png)
![infographic]({{site.baseurl}}/images/flatelectronic1.png)
![infographic]({{site.baseurl}}/images/flatelectronic2.png)
![infographic]({{site.baseurl}}/images/flatelectronic3.png)
![infographic]({{site.baseurl}}/images/flatelectronic4.png)
![infographic]({{site.baseurl}}/images/flatelectronic5.png)
![infographic]({{site.baseurl}}/images/flatelectronic6.png)
Infographic for making electronic (planning to finish off all the processes tomorrow)


text:
ALife::_STORY_ID	story_id		(LPCSTR story_id);
u16					storyId2GameId	(ALife::_STORY_ID);

using namespace luabind;

ALife::_STORY_ID	story_id	(LPCSTR story_id)
{
	int res=
							(
		object_cast<int>(
			luabind::object(
				luabind::get_globals(
					ai().script_engine().lua()
				)
				["story_ids"]
			)
			[story_id]
		)
	);
	return ALife::_STORY_ID(res);
}

u16 storyId2GameId	(ALife::_STORY_ID id)
{
	if(ai().get_alife()){
		CSE_ALifeDynamicObject* so = ai().alife().story_objects().object(id, true);
		return (so)?so->ID:u16(-1);
	}else{
		u32 cnt = Level().Objects.o_count();
		for(u32 it=0;it<cnt;++it){
			CObject* O = Level().Objects.o_get_by_iterator(it);
			CGameObject* GO = smart_cast<CGameObject*>(O);
			if(GO->story_id()==id)
				return GO->ID();
		}
	return u16(-1);
	}
}

CUIXml*	g_gameTaskXml=NULL;

CGameTask::CGameTask(const TASK_ID& id)
{
	m_ReceiveTime	= 0;
	m_FinishTime	= 0;
	m_Title			= NULL;
	m_priority		= u32(-1);
	Load			(id);
}

CGameTask::CGameTask()
{
	m_ReceiveTime	= 0;
	m_FinishTime	= 0;
	m_Title			= NULL;
	m_ID			= NULL;
}

void CGameTask::Load(const TASK_ID& id)
{
	m_ID							= id;

	if(!g_gameTaskXml){
		g_gameTaskXml				= xr_new<CUIXml>();
		g_gameTaskXml->Init			(CONFIG_PATH, "gameplay", "game_tasks.xml");
	}
	XML_NODE* task_node				= g_gameTaskXml->NavigateToNodeWithAttribute("game_task","id",*id);

	THROW3							(task_node, "game task id=", *id);
	g_gameTaskXml->SetLocalRoot		(task_node);
	m_Title							= g_gameTaskXml->Read(g_gameTaskXml->GetLocalRoot(), "title", 0, NULL);
	m_priority						= g_gameTaskXml->ReadAttribInt(g_gameTaskXml->GetLocalRoot(), "prio", -1);
#ifdef DEBUG
	if(m_priority == u32(-1))
	{
		Msg("Game Task [%s] has no priority", *id);
	}
#endif // DEBUG
	int tag_num						= g_gameTaskXml->GetNodesNum(g_gameTaskXml->GetLocalRoot(),"objective");
	m_Objectives.clear		();
	for(int i=0; i<tag_num; i++)
	{
		XML_NODE*	l_root = NULL;
		l_root							= g_gameTaskXml->NavigateToNode("objective",i);
		g_gameTaskXml->SetLocalRoot		(l_root);

		m_Objectives.push_back			(SGameTaskObjective(this,i));
		SGameTaskObjective&				objective = m_Objectives.back();

//.
		LPCSTR tag_text					= g_gameTaskXml->Read(l_root, "text", 0, NULL);
		objective.description			= tag_text;
//.
		tag_text						= g_gameTaskXml->Read(l_root, "article", 0, NULL);
		if(tag_text)
			objective.article_id		= tag_text;

//.
		tag_text						= g_gameTaskXml->ReadAttrib(l_root, "key", NULL);
		if(tag_text)
			objective.article_key		= tag_text;

//.
		if(i==0)
		{
			objective.icon_texture_name		= g_gameTaskXml->Read(g_gameTaskXml->GetLocalRoot(), "icon", 0, NULL);
			if( objective.icon_texture_name.size() &&
				0 != stricmp(*objective.icon_texture_name, "ui\\ui_icons_task") )
			{
				objective.icon_rect			= CUITextureMaster::GetTextureRect(*objective.icon_texture_name);
				objective.icon_rect.rb.sub(objective.icon_rect.rb, objective.icon_rect.lt);
				objective.icon_texture_name	= CUITextureMaster::GetTextureFileName(*objective.icon_texture_name);
			}else
				if(objective.icon_texture_name.size()){
				objective.icon_rect.x1			= g_gameTaskXml->ReadAttribFlt(l_root, "icon", 0, "x");
				objective.icon_rect.y1			= g_gameTaskXml->ReadAttribFlt(l_root, "icon", 0, "y");
				objective.icon_rect.x2			= g_gameTaskXml->ReadAttribFlt(l_root, "icon", 0, "width");
				objective.icon_rect.y2			= g_gameTaskXml->ReadAttribFlt(l_root, "icon", 0, "height");
			}
		}
//.
		objective.map_location			= g_gameTaskXml->Read(l_root, "map_location_type", 0, NULL);

		LPCSTR object_story_id			= g_gameTaskXml->Read(l_root, "object_story_id", 0, NULL);

//*
		LPCSTR ddd;
		ddd								= g_gameTaskXml->Read(l_root, "map_location_hidden", 0, NULL);
		if(ddd)
			objective.def_location_enabled = false;

		bool b1,b2;
		b1								= (0==objective.map_location.size());
		b2								= (NULL==object_story_id);
		VERIFY3							(b1==b2,"check [map_location_type] and [object_story_id] fields in objective definition for: ",*objective.description);

//.
		objective.object_id				= u16(-1);

//.
		objective.map_hint				= g_gameTaskXml->ReadAttrib(l_root, "map_location_type", 0, "hint", NULL);

		if(object_story_id){
			ALife::_STORY_ID _sid		= story_id(object_story_id);
			objective.object_id			= storyId2GameId(_sid);
		}

//------infoportion_complete
		int info_num					= g_gameTaskXml->GetNodesNum(l_root,"infoportion_complete");
		objective.m_completeInfos.resize(info_num);
		int j;
		for(j=0; j<info_num; ++j)
			objective.m_completeInfos[j]= g_gameTaskXml->Read(l_root, "infoportion_complete", j, NULL);

//------infoportion_fail
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"infoportion_fail");
		objective.m_failInfos.resize	(info_num);

		for(j=0; j<info_num; ++j)
			objective.m_failInfos[j]	= g_gameTaskXml->Read(l_root, "infoportion_fail", j, NULL);

//------infoportion_set_complete
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"infoportion_set_complete");
		objective.m_infos_on_complete.resize(info_num);
		for(j=0; j<info_num; ++j)
			objective.m_infos_on_complete[j]= g_gameTaskXml->Read(l_root, "infoportion_set_complete", j, NULL);

//------infoportion_set_fail
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"infoportion_set_fail");
		objective.m_infos_on_fail.resize(info_num);
		for(j=0; j<info_num; ++j)
			objective.m_infos_on_fail[j]= g_gameTaskXml->Read(l_root, "infoportion_set_fail", j, NULL);

//------function_complete
		LPCSTR		str;
		bool functor_exists;
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"function_complete");
		objective.m_complete_lua_functions.resize(info_num);
		for(j=0; j<info_num; ++j){
			str							= g_gameTaskXml->Read(l_root, "function_complete", j, NULL);
			functor_exists				= ai().script_engine().functor(str ,objective.m_complete_lua_functions[j]);
			THROW3						(functor_exists, "Cannot find script function described in task objective  ", str);
		}

//------function_fail
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"function_fail");
		objective.m_fail_lua_functions.resize(info_num);
		for(j=0; j<info_num; ++j){
			str							= g_gameTaskXml->Read(l_root, "function_fail", j, NULL);
			functor_exists				= ai().script_engine().functor(str ,objective.m_fail_lua_functions[j]);
			THROW3						(functor_exists, "Cannot find script function described in task objective  ", str);
		}

//------function_on_complete
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"function_call_complete");
		objective.m_lua_functions_on_complete.resize(info_num);
		for(j=0; j<info_num; ++j){
			str							= g_gameTaskXml->Read(l_root, "function_call_complete", j, NULL);
			functor_exists				= ai().script_engine().functor(str ,objective.m_lua_functions_on_complete[j]);
			THROW3						(functor_exists, "Cannot find script function described in task objective  ", str);
		}

//------function_on_fail
		info_num						= g_gameTaskXml->GetNodesNum(l_root,"function_call_fail");
		objective.m_lua_functions_on_fail.resize(info_num);
		for(j=0; j<info_num; ++j){
			str							= g_gameTaskXml->Read(l_root, "function_call_fail", j, NULL);
			functor_exists				= ai().script_engine().functor(str ,objective.m_lua_functions_on_fail[j]);
			THROW3						(functor_exists, "Cannot find script function described in task objective  ", str);
		}

		g_gameTaskXml->SetLocalRoot		(task_node);
	}
	g_gameTaskXml->SetLocalRoot		(g_gameTaskXml->GetRoot());
}

bool CGameTask::HasLinkedMapLocations			()
{
	for(u32 i=0; i<m_Objectives.size(); ++i)
		if(m_Objectives[i].LinkedMapLocation()!=NULL)return true;

	return false;
}

bool CGameTask::HasInProgressObjective()
{
	for(u32 i=1; i<m_Objectives.size(); ++i)
		if(m_Objectives[i].TaskState()==eTaskStateInProgress)return true;
	return false;
}

SGameTaskObjective::SGameTaskObjective		(CGameTask* parent, int _idx)
:description		(NULL),
article_id			(NULL),
map_location		(NULL),
object_id			(u16(-1)),
task_state			(eTaskStateInProgress),
def_location_enabled(true),
parent				(parent),
idx					(_idx)
{
}

SGameTaskObjective::SGameTaskObjective()
:description		(NULL),
article_id			(NULL),
map_location		(NULL),
object_id			(u16(-1)),
task_state			(eTaskStateInProgress),
def_location_enabled(true),
parent				(NULL),
idx					(0)
{
}

CMapLocation* SGameTaskObjective::LinkedMapLocation		()
{
	if( map_location.size()==0) return NULL;
	return Level().MapManager().GetMapLocation(map_location, object_id);
}

void SGameTaskObjective::SetTaskState		(ETaskState new_state)
{
	task_state = new_state;
	if( (new_state==eTaskStateFail) || (new_state==eTaskStateCompleted) ){

		if( task_state==eTaskStateFail ){
				SendInfo				(m_infos_on_fail);
				CallAllFuncs			(m_lua_functions_on_fail);
		}else
		if( task_state==eTaskStateCompleted ){
				SendInfo				(m_infos_on_complete);
				CallAllFuncs			(m_lua_functions_on_complete);
		}
		//callback for scripters
		ChangeStateCallback();
	}
}

ETaskState SGameTaskObjective::UpdateState	()
{
	if( (idx==0) && (parent->m_ReceiveTime != parent->m_TimeToComplete) )
	{
		if(Level().GetGameTime() > parent->m_TimeToComplete)
		{
			return		eTaskStateFail;
		}
	}
//check fail infos
	if( CheckInfo(m_failInfos) )
		return		eTaskStateFail;

//check fail functor
	if( CheckFunctions(m_fail_lua_functions) )
		return		eTaskStateFail;

//check complete infos
	if( CheckInfo(m_completeInfos) )
		return		eTaskStateCompleted;

//check complete functor
	if( CheckFunctions(m_complete_lua_functions) )
		return		eTaskStateCompleted;

	return TaskState();
}

void SGameTaskObjective::SendInfo		(xr_vector<shared_str>& v)
{
	xr_vector<shared_str>::iterator it	= v.begin();
	for(;it!=v.end();++it)
		Actor()->TransferInfo					((*it),true);

}

bool SGameTaskObjective::CheckInfo		(xr_vector<shared_str>& v)
{
	bool res = false;
	xr_vector<shared_str>::iterator it	= v.begin();
	for(;it!=v.end();++it){
		res = Actor()->HasInfo					(*it);
		if(!res) break;
	}
	return res;
}

bool SGameTaskObjective::CheckFunctions	(xr_vector<luabind::functor<bool> >& v)
{
	bool res = false;
	xr_vector<luabind::functor<bool> >::iterator it	= v.begin();
	for(;it!=v.end();++it){
		if( (*it).is_valid() ) res = (*it)(*(parent->m_ID), idx);
		if(!res) break;
	}
	return res;

}

void SGameTaskObjective::CallAllFuncs	(xr_vector<luabind::functor<bool> >& v)
{
	xr_vector<luabind::functor<bool> >::iterator it	= v.begin();
	for(;it!=v.end();++it){
		if( (*it).is_valid() ) (*it)(*(parent->m_ID), idx);
	}
}
void SGameTaskObjective::SetDescription_script(LPCSTR _descr)
{
	description = _descr;
}

void SGameTaskObjective::SetArticleID_script(LPCSTR _id)
{
	article_id = _id;
}

void SGameTaskObjective::SetMapHint_script(LPCSTR _str)
{
	map_hint = _str;
}

void SGameTaskObjective::SetMapLocation_script(LPCSTR _str)
{
	map_location = _str;
}

void SGameTaskObjective::SetObjectID_script(u16 id)
{
	object_id = id;
}

void SGameTaskObjective::SetIconName_script(LPCSTR _str)
{
	icon_texture_name	= _str;
	icon_rect			= CUITextureMaster::GetTextureRect(icon_texture_name.c_str());
	icon_rect.rb.sub	(icon_rect.rb, icon_rect.lt);
	icon_texture_name	= CUITextureMaster::GetTextureFileName(icon_texture_name.c_str());
}

void SGameTaskObjective::SetArticleKey_script(LPCSTR _str)
{
	article_key = _str;
}

void SGameTaskObjective::AddCompleteInfo_script(LPCSTR _str)
{
	m_completeInfos.push_back(_str);
}

void SGameTaskObjective::AddFailInfo_script(LPCSTR _str)
{
	m_failInfos.push_back(_str);
}

void SGameTaskObjective::AddOnCompleteInfo_script(LPCSTR _str)
{
	m_infos_on_complete.push_back(_str);
}

void SGameTaskObjective::AddOnFailInfo_script(LPCSTR _str)
{
	m_infos_on_fail.push_back(_str);
}

void SGameTaskObjective::AddCompleteFunc_script(LPCSTR _str)
{
	m_pScriptHelper.m_s_complete_lua_functions.push_back(_str);
}
void SGameTaskObjective::AddFailFunc_script(LPCSTR _str)
{
	m_pScriptHelper.m_s_fail_lua_functions.push_back(_str);
}
void SGameTaskObjective::AddOnCompleteFunc_script(LPCSTR _str)
{
	m_pScriptHelper.m_s_lua_functions_on_complete.push_back(_str);
}
void SGameTaskObjective::AddOnFailFunc_script(LPCSTR _str)
{
	m_pScriptHelper.m_s_lua_functions_on_fail.push_back(_str);
}

void CGameTask::Load_script(LPCSTR _id)
{
	Load(_id);
}

void CGameTask::SetTitle_script(LPCSTR _title)
{
	m_Title	= _title;
}

void CGameTask::SetPriority_script(int _prio)
{
	m_priority	= _prio;
}

void CGameTask::AddObjective_script(SGameTaskObjective* O)
{
	O->m_pScriptHelper.init_functors(O->m_pScriptHelper.m_s_complete_lua_functions,		O->m_complete_lua_functions);
	O->m_pScriptHelper.init_functors(O->m_pScriptHelper.m_s_fail_lua_functions,			O->m_fail_lua_functions);
	O->m_pScriptHelper.init_functors(O->m_pScriptHelper.m_s_lua_functions_on_complete,	O->m_lua_functions_on_complete);
	O->m_pScriptHelper.init_functors(O->m_pScriptHelper.m_s_lua_functions_on_fail,		O->m_lua_functions_on_fail);

	m_Objectives.push_back(*O);
}

void SGameTaskObjective::ChangeStateCallback()
{
	Actor()->callback(GameObject::eTaskStateChange)(parent, this, task_state);
}

void SGameTaskObjective::save(IWriter &stream)
{
		save_data(idx,					stream);
		save_data(task_state,			stream);

		save_data(description,			stream);
		save_data(map_location,			stream);
		save_data(object_id,			stream);
		save_data(task_state,			stream);
		save_data(def_location_enabled,	stream);
		save_data(map_hint,				stream);
		save_data(icon_texture_name,	stream);
		save_data(icon_rect,			stream);
		save_data(article_id,			stream);

		save_data(m_completeInfos,		stream);
		save_data(m_failInfos,			stream);
		save_data(m_infos_on_complete,	stream);
		save_data(m_infos_on_fail,		stream);

		bool b_script					= m_pScriptHelper.not_empty();
		save_data(b_script,				stream);
		if(b_script)
			save_data(m_pScriptHelper,	stream);

}

void SGameTaskObjective::load(IReader &stream)
{
		load_data(idx,					stream);
		load_data(task_state,			stream);

		load_data(description,			stream);
		load_data(map_location,			stream);
		load_data(object_id,			stream);
		load_data(task_state,			stream);
		load_data(def_location_enabled,	stream);
		load_data(map_hint,				stream);
		load_data(icon_texture_name,	stream);
		load_data(icon_rect,			stream);
		load_data(article_id,			stream);

		load_data(m_completeInfos,		stream);
		load_data(m_failInfos,			stream);
		load_data(m_infos_on_complete,	stream);
		load_data(m_infos_on_fail,		stream);

		bool b_script;
		load_data(b_script,				stream);
		if(b_script){
			load_data(m_pScriptHelper,	stream);

			m_pScriptHelper.init_functors	(m_pScriptHelper.m_s_complete_lua_functions,	m_complete_lua_functions);
			m_pScriptHelper.init_functors	(m_pScriptHelper.m_s_fail_lua_functions,		m_fail_lua_functions);
			m_pScriptHelper.init_functors	(m_pScriptHelper.m_s_lua_functions_on_complete, m_lua_functions_on_complete);
			m_pScriptHelper.init_functors	(m_pScriptHelper.m_s_lua_functions_on_fail,		m_lua_functions_on_fail);
		}
}

void SScriptObjectiveHelper::init_functors(xr_vector<shared_str>& v_src, xr_vector<luabind::functor<bool> >& v_dest)
{
	xr_vector<shared_str>::iterator it		= v_src.begin();
	xr_vector<shared_str>::iterator it_e	= v_src.end();
	v_dest.resize(v_src.size());

	for(u32 idx=0 ;it!=it_e;++it,++idx)
	{
			bool functor_exists		= ai().script_engine().functor(*(*it) ,v_dest[idx]);
			if(!functor_exists)		Log("Cannot find script function described in task objective  ", *(*it));
	}
}

void SScriptObjectiveHelper::load(IReader &stream)
{
		load_data(m_s_complete_lua_functions,		stream);
		load_data(m_s_fail_lua_functions,			stream);
		load_data(m_s_lua_functions_on_complete,	stream);
		load_data(m_s_lua_functions_on_fail,		stream);
}

void SScriptObjectiveHelper::save(IWriter &stream)
{
		save_data(m_s_complete_lua_functions,		stream);
		save_data(m_s_fail_lua_functions,			stream);
		save_data(m_s_lua_functions_on_complete,	stream);
		save_data(m_s_lua_functions_on_fail,		stream);
}

void SGameTaskKey::save(IWriter &stream)
{
	save_data(task_id,						stream);
	save_data(game_task->m_ReceiveTime,		stream);
	save_data(game_task->m_FinishTime,		stream);
	save_data(game_task->m_TimeToComplete,	stream);
	save_data(game_task->m_Title,			stream);

	u32 cnt	= game_task->m_Objectives.size();
	save_data(cnt, stream);

	OBJECTIVE_VECTOR_IT it		= game_task->m_Objectives.begin();
	OBJECTIVE_VECTOR_IT it_e	= game_task->m_Objectives.end();
	for(;it!=it_e;++it)
		save_data(*it, stream);

}

void SGameTaskKey::load(IReader &stream)
{
	load_data(task_id,						stream);
	game_task = xr_new<CGameTask>			(task_id);
	load_data(game_task->m_ReceiveTime,		stream);
	load_data(game_task->m_FinishTime,		stream);
	load_data(game_task->m_TimeToComplete,	stream);

	load_data(game_task->m_Title,			stream);

	u32 cnt;
	load_data(cnt, stream);

	if(cnt>game_task->m_Objectives.size())
		game_task->m_Objectives.resize(cnt);

	for(u32 i=0; i<cnt; ++i){
		load_data(game_task->m_Objectives[i], stream);
		game_task->m_Objectives[i].parent = game_task;
	}
}

void SGameTaskKey::destroy()
{
	delete_data(game_task);
}


text:
package com.percolate.sdk.android.dto;

import android.os.Parcel;
import android.os.Parcelable;
import com.percolate.sdk.dto.InstagramPhotoPosition;

import java.util.HashMap;

/**
 * Android version of {@link com.percolate.sdk.dto.InstagramUsersInPhoto}.  Implements {@link Parcelable}
 */
public class InstagramUsersInPhoto extends com.percolate.sdk.dto.InstagramUsersInPhoto implements Parcelable {
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeSerializable(this.user);
        dest.writeSerializable(this.position);
        dest.writeMap(this.extraFields);
    }

    public InstagramUsersInPhoto() {
    }

    protected InstagramUsersInPhoto(Parcel in) {
        this.user = (com.percolate.sdk.dto.InstagramUserData) in.readSerializable();
        this.position = (InstagramPhotoPosition) in.readSerializable();
        this.extraFields = new HashMap<>();
        in.readMap(this.extraFields, HashMap.class.getClassLoader());
    }

    public static final Creator<InstagramUsersInPhoto> CREATOR = new Creator<InstagramUsersInPhoto>() {
        public InstagramUsersInPhoto createFromParcel(Parcel source) {
            return new InstagramUsersInPhoto(source);
        }

        public InstagramUsersInPhoto[] newArray(int size) {
            return new InstagramUsersInPhoto[size];
        }
    };
}


text:
module Awspec::Generator
  module Spec
    class AutoscalingGroup
      include Awspec::Helper::Finder
      def generate_by_vpc_id(vpc_id)
        describes = %w[
          auto_scaling_group_name auto_scaling_group_arn min_size max_size desired_capacity
          default_cooldown availability_zones health_check_type health_check_grace_period
          vpc_zone_identifier termination_policies new_instances_protected_from_scale_in
        ]
        vpc = find_vpc(vpc_id)
        raise 'Not Found VPC' unless vpc

        @vpc_id = vpc[:vpc_id]
        @vpc_tag_name = vpc.tag_name
        autoscaling_groups = select_autoscaling_group_by_vpc_id(@vpc_id)
        specs = autoscaling_groups.map do |autoscaling_group|
          content = ERB.new(autoscaling_group_spec_template, nil, '-').result(binding).gsub(/^\n/, '')
        end
        specs.join("\n")
      end

      def autoscaling_group_spec_template
        <<-'EOF'
describe autoscaling_group('<%= autoscaling_group.auto_scaling_group_name %>') do
  it { should exist }
<% describes.each do |describe| %>
<%- if autoscaling_group.members.include?(describe.to_sym) && !autoscaling_group[describe.to_sym].nil? -%>
<%- if autoscaling_group[describe].is_a?(String) -%>
  its(:<%= describe %>) { should eq '<%= autoscaling_group[describe] %>' }
<%- else -%>
  its(:<%= describe %>) { should eq <%= autoscaling_group[describe] %> }
<%- end -%>
<%- end -%>
<% end %>
<%- unless autoscaling_group.launch_configuration_name.nil? -%>
  it { should have_launch_configuration('<%= autoscaling_group.launch_configuration_name %>') }
<%- else -%>
  its('launch_template.launch_template_name') { should eq '<%= autoscaling_group.launch_template.launch_template_name %>' }
<%- end -%>
<% autoscaling_group[:load_balancer_names].each do |desc| %>
  it { should have_elb('<%= desc %>') }
<% end %>
<% autoscaling_group[:target_group_arns].join(",").gsub(/arn:.+?:targetgroup\/(.[^\/]*)\/.[^,]*/, '\1').split(",").each do |desc| %>
  <%- if not find_alb_target_group(desc).nil? -%>
  it { should have_alb_target_group('<%= desc %>') }
  <%- elsif not find_nlb_target_group(desc).nil? -%>
  it { should have_nlb_target_group('<%= desc %>') }
  <%- end -%>
<% end %>
end
EOF
      end
    end
  end
end


text:
var baseRepeat = require('./_baseRepeat'),
    stringSize = require('./_stringSize'),
    stringToArray = require('./_stringToArray');

/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
    rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
    rsComboSymbolsRange = '\\u20d0-\\u20f0',
    rsVarRange = '\\ufe0e\\ufe0f';

/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';

/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange  + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil;

/**
 * Creates the padding for `string` based on `length`. The `chars` string
 * is truncated if the number of characters exceeds `length`.
 *
 * @private
 * @param {number} length The padding length.
 * @param {string} [chars=' '] The string used as padding.
 * @returns {string} Returns the padding for `string`.
 */
function createPadding(length, chars) {
  chars = chars === undefined ? ' ' : (chars + '');

  var charsLength = chars.length;
  if (charsLength < 2) {
    return charsLength ? baseRepeat(chars, length) : chars;
  }
  var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
  return reHasComplexSymbol.test(chars)
    ? stringToArray(result).slice(0, length).join('')
    : result.slice(0, length);
}

module.exports = createPadding;


text:
Bootstraps
==========

python-for-android (p4a) supports multiple *bootstraps*. These fulfill a
similar role to recipes, but instead of describing how to compile a
specific module they describe how a full Android project may be put
together from a combination of individual recipes and other
components such as Android source code and various build files.

If you do not want to modify p4a, you don't need to worry about
bootstraps, just make sure you specify what modules you want to use
(or specify an existing bootstrap manually), and p4a will
automatically build everything appropriately. The existing choices are
explained on the :ref:`build options <bootstrap_build_options>` page.

This page describes the basics of how bootstraps work so that you can
create and use your own if you like, making it easy to build new kinds
of Python project for Android.

Creating a new bootstrap
------------------------

A bootstrap class consists of just a few basic components, though one of them must do a lot of work.

For instance, the SDL2 bootstrap looks like the following::

    from pythonforandroid.toolchain import Bootstrap, shprint, current_directory, info, warning, ArchAndroid, logger, info_main, which
    from os.path import join, exists
    from os import walk
    import glob
    import sh

    class SDL2Bootstrap(Bootstrap):
        name = 'sdl2'

        recipe_depends = ['sdl2']

        def run_distribute(self):
            # much work is done here...

The declaration of the bootstrap name and recipe dependencies should
be clear. However, the :code:`run_distribute` method must do all the
work of creating a build directory, copying recipes etc into it, and
adding or removing any extra components as necessary.

If you'd like to create a bootstrap, the best resource is to check the
existing ones in the p4a source code. You can also :doc:`contact the
developers <troubleshooting>` if you have problems or questions.


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>1.3. Grammar Notation</title>
<link rel="stylesheet" type="text/css" href="docbook.css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<meta name="keywords" content="MASL, Action Language, Action Semantics, UML, Unified Modelling Language, Shlaer Mellor">
<link rel="home" href="index.html" title="MASL Reference Manual">
<link rel="up" href="Grammars.html" title="Chapter 1. Grammars">
<link rel="prev" href="GrammarsSyntacticGrammar.html" title="1.2. The Syntactic Grammar">
<link rel="next" href="LexicalStructure.html" title="Chapter 2. Lexical Structure">
<link rel="preface" href="preface.html" title="Preface">
<link rel="chapter" href="Grammars.html" title="Chapter 1. Grammars">
<link rel="chapter" href="LexicalStructure.html" title="Chapter 2. Lexical Structure">
<link rel="chapter" href="Types.html" title="Chapter 3. Types">
<link rel="chapter" href="TypeConversion.html" title="Chapter 4. Type Conversion">
<link rel="chapter" href="Domains.html" title="Chapter 5. Domains">
<link rel="chapter" href="Objects.html" title="Chapter 6. Objects">
<link rel="chapter" href="Relationships.html" title="Chapter 7. Relationships">
<link rel="chapter" href="Lifecycles.html" title="Chapter 8. Lifecycles">
<link rel="chapter" href="Functions.html" title="Chapter 9. Functions">
<link rel="chapter" href="Services.html" title="Chapter 10. Services">
<link rel="chapter" href="Exceptions.html" title="Chapter 11. Exceptions">
<link rel="chapter" href="Statements.html" title="Chapter 12. Statements">
<link rel="chapter" href="Names.html" title="Chapter 13. Names">
<link rel="chapter" href="Expressions.html" title="Chapter 14. Expressions">
<link rel="appendix" href="LanguageDefinedCharacteristics.html" title="Appendix A. Language Defined Characteristics">
<link rel="appendix" href="SyntaxSummary.html" title="Appendix B. Syntax Summary">
<link rel="index" href="ix01.html" title="Index">

OFFICIAL

1.3. Grammar Notation

Prev
Chapter 1. Grammars
 Next

1.3. Grammar Notation

The EBNF

notation is used for the grammar
[EBNF96]. The EBNF

notation provides a standardized, simple and unambiguous means of expressing the
grammar of a language.

Prev
Up
 Next

1.2. The Syntactic Grammar

Home | ToC

 Chapter 2. Lexical Structure

OFFICIAL


text:
import datetime
from os.path import exists, join
import base64
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa

def create_self_signed_certificate(device_id, valid_days, cert_output_dir):
    cert_file = device_id + '-cert.pem'
    key_file = device_id + '-key.pem'

    # create a key pair
    key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

    # create a self-signed cert
    subject_name = x509.Name(
        [
            x509.NameAttribute(NameOID.COMMON_NAME, device_id),
        ]
    )
    cert = (
        x509.CertificateBuilder()
        .subject_name(subject_name)
        .issuer_name(subject_name)
        .public_key(key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(datetime.datetime.utcnow())
        .not_valid_after(
            datetime.datetime.utcnow() + datetime.timedelta(days=valid_days)
        )
        .sign(key, hashes.SHA256())
    )

    key_dump = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    ).decode("utf-8")
    cert_dump = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
    thumbprint = cert.fingerprint(hashes.SHA1()).hex().upper()

    if cert_output_dir is not None and exists(cert_output_dir):
        open(join(cert_output_dir, cert_file), "wt").write(cert_dump)
        open(join(cert_output_dir, key_file), "wt").write(key_dump)
    return {
        'certificate': cert_dump,
        'privateKey': key_dump,
        'thumbprint': thumbprint
    }

def open_certificate(certificate_path):
    certificate = ""
    if certificate_path.endswith('.pem') or certificate_path.endswith('.cer'):
        with open(certificate_path, "rb") as cert_file:
            certificate = cert_file.read()
        certificate = base64.b64encode(certificate).decode("utf-8")
    else:
        raise ValueError("Certificate file type must be either '.pem' or '.cer'.")
    # Remove trailing white space from the certificate content
    return certificate.rstrip()

def generate_key(byte_length=32):
    """
    Generate cryptographically secure device key.
    """
    import secrets

    token_bytes = secrets.token_bytes(byte_length)
    return base64.b64encode(token_bytes).decode("utf8")

def _dps_certificate_response_transform(certificate_response):
    from azure.mgmt.iothubprovisioningservices.models import (CertificateListDescription,
                                                              CertificateResponse,
                                                              VerificationCodeResponse)
    if isinstance(certificate_response, CertificateListDescription) and certificate_response.value:
        for cert in certificate_response.value:
            cert = _replace_certificate_bytes(cert)
    if isinstance(certificate_response, (CertificateResponse, VerificationCodeResponse)):
        certificate_response = _replace_certificate_bytes(certificate_response)
    return certificate_response

def _replace_certificate_bytes(cert_object):
    properties = getattr(cert_object, 'properties', {})
    body = getattr(properties, 'certificate', None)
    if body:
        cert_bytes = _safe_decode(body)
        if not cert_bytes:
            from knack.log import get_logger
            logger = get_logger(__name__)
            logger.warning('Certificate `%s` contains invalid unicode characters; its body was omitted from output.',
                           cert_object.name)
        cert_object.properties.certificate = cert_bytes
    return cert_object

def _safe_decode(cert_bytes):
    if isinstance(cert_bytes, str):
        return cert_bytes
    if isinstance(cert_bytes, (bytearray, bytes)):
        try:
            return cert_bytes.decode('utf-8')
        except UnicodeDecodeError:
            return None
    return None


text:
import { Component, Input, OnChanges } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

import { getType, SecurityGroup, SecurityGroupType } from '../sg.model';
import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component';
import { SecurityGroupCardItemComponent } from '../sg-list-item/card-item/security-group-card-item.component';
import { SecurityGroupRowItemComponent } from '../sg-list-item/row-item/security-group-row-item.component';
import { ListService } from '../../shared/components/list/list.service';
import { SecurityGroupViewMode } from '../sg-view-mode';
import { VirtualMachine } from '../../vm';
import { NgrxEntities } from '../../shared/interfaces';

@Component({
  selector: 'cs-security-group-list',
  templateUrl: 'security-group-list.component.html',
})
export class SecurityGroupListComponent implements OnChanges {
  @Input()
  public securityGroups: SecurityGroup[];
  @Input()
  public query: string;
  @Input()
  public mode: ViewMode;
  @Input()
  public viewMode: SecurityGroupViewMode;
  @Input()
  public vmList: NgrxEntities<VirtualMachine>;
  public groupings = [];

  public inputs;
  public outputs;

  constructor(private translateService: TranslateService, public listService: ListService) {
    this.inputs = {
      searchQuery: () => this.query,
      isSelected: (item: SecurityGroup) => this.listService.isSelected(item.id),
      vmList: this.vmList,
    };

    this.outputs = {
      onClick: this.selectSecurityGroup.bind(this),
    };
  }

  public ngOnChanges(changes) {
    this.groupings =
      this.viewMode === SecurityGroupViewMode.Templates
        ? [
            {
              key: 'types',
              label: 'SECURITY_GROUP_PAGE.FILTERS.GROUP_BY_TYPES',
              selector: getType,
              name: (item: SecurityGroup) => {
                switch (getType(item)) {
                  case SecurityGroupType.PredefinedTemplate: {
                    return this.translateService.instant(
                      'SECURITY_GROUP_PAGE.LIST.SYSTEM_SECURITY_GROUPS',
                    );
                  }
                  case SecurityGroupType.CustomTemplate: {
                    return this.translateService.instant(
                      'SECURITY_GROUP_PAGE.LIST.CUSTOM_SECURITY_GROUPS',
                    );
                  }
                  default:
                    break;
                }
              },
            },
          ]
        : [];

    if (changes['vmList']) {
      this.inputs.vmList = this.vmList;
    }
  }

  public get itemComponent() {
    return this.mode === ViewMode.BOX
      ? SecurityGroupCardItemComponent
      : SecurityGroupRowItemComponent;
  }

  public selectSecurityGroup(securityGroup: SecurityGroup): void {
    this.listService.showDetails(securityGroup.id);
  }
}


text:
package com.android.camera;

// Use a different activity for secure camera only. So it can have a different
// task affinity from others. This makes sure non-secure camera activity is not
// started in secure lock screen.
public class SecureCameraActivity extends CameraActivity {
}


text:
#pragma once
#include <aws/drs/Drs_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace drs
{
namespace Model
{

  /**
   *
An object representing a block storage device on the Recovery
   * Instance.

See Also:
   AWS
   * API Reference

   */
  class AWS_DRS_API RecoveryInstanceDisk
  {
  public:
    RecoveryInstanceDisk();
    RecoveryInstanceDisk(Aws::Utils::Json::JsonView jsonValue);
    RecoveryInstanceDisk& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The amount of storage on the disk in bytes.

     */
    inline long long GetBytes() const{ return m_bytes; }

    /**
     *
The amount of storage on the disk in bytes.

     */
    inline bool BytesHasBeenSet() const { return m_bytesHasBeenSet; }

    /**
     *
The amount of storage on the disk in bytes.

     */
    inline void SetBytes(long long value) { m_bytesHasBeenSet = true; m_bytes = value; }

    /**
     *
The amount of storage on the disk in bytes.

     */
    inline RecoveryInstanceDisk& WithBytes(long long value) { SetBytes(value); return *this;}

    /**
     *
The EBS Volume ID of this disk.

     */
    inline const Aws::String& GetEbsVolumeID() const{ return m_ebsVolumeID; }

    /**
     *
The EBS Volume ID of this disk.

     */
    inline bool EbsVolumeIDHasBeenSet() const { return m_ebsVolumeIDHasBeenSet; }

    /**
     *
The EBS Volume ID of this disk.

     */
    inline void SetEbsVolumeID(const Aws::String& value) { m_ebsVolumeIDHasBeenSet = true; m_ebsVolumeID = value; }

    /**
     *
The EBS Volume ID of this disk.

     */
    inline void SetEbsVolumeID(Aws::String&& value) { m_ebsVolumeIDHasBeenSet = true; m_ebsVolumeID = std::move(value); }

    /**
     *
The EBS Volume ID of this disk.

     */
    inline void SetEbsVolumeID(const char* value) { m_ebsVolumeIDHasBeenSet = true; m_ebsVolumeID.assign(value); }

    /**
     *
The EBS Volume ID of this disk.

     */
    inline RecoveryInstanceDisk& WithEbsVolumeID(const Aws::String& value) { SetEbsVolumeID(value); return *this;}

    /**
     *
The EBS Volume ID of this disk.

     */
    inline RecoveryInstanceDisk& WithEbsVolumeID(Aws::String&& value) { SetEbsVolumeID(std::move(value)); return *this;}

    /**
     *
The EBS Volume ID of this disk.

     */
    inline RecoveryInstanceDisk& WithEbsVolumeID(const char* value) { SetEbsVolumeID(value); return *this;}

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline const Aws::String& GetInternalDeviceName() const{ return m_internalDeviceName; }

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline bool InternalDeviceNameHasBeenSet() const { return m_internalDeviceNameHasBeenSet; }

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline void SetInternalDeviceName(const Aws::String& value) { m_internalDeviceNameHasBeenSet = true; m_internalDeviceName = value; }

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline void SetInternalDeviceName(Aws::String&& value) { m_internalDeviceNameHasBeenSet = true; m_internalDeviceName = std::move(value); }

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline void SetInternalDeviceName(const char* value) { m_internalDeviceNameHasBeenSet = true; m_internalDeviceName.assign(value); }

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline RecoveryInstanceDisk& WithInternalDeviceName(const Aws::String& value) { SetInternalDeviceName(value); return *this;}

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline RecoveryInstanceDisk& WithInternalDeviceName(Aws::String&& value) { SetInternalDeviceName(std::move(value)); return *this;}

    /**
     *
The internal device name of this disk. This is the name that is visible on
     * the machine itself and not from the EC2 console.

     */
    inline RecoveryInstanceDisk& WithInternalDeviceName(const char* value) { SetInternalDeviceName(value); return *this;}

  private:

    long long m_bytes;
    bool m_bytesHasBeenSet = false;

    Aws::String m_ebsVolumeID;
    bool m_ebsVolumeIDHasBeenSet = false;

    Aws::String m_internalDeviceName;
    bool m_internalDeviceNameHasBeenSet = false;
  };

} // namespace Model
} // namespace drs
} // namespace Aws


text:
FROM postgres:9.2

# add backup scripts
ADD backup.sh /usr/local/bin/backup
ADD restore.sh /usr/local/bin/restore
ADD list-backups.sh /usr/local/bin/list-backups

# make them executable
RUN chmod +x /usr/local/bin/restore
RUN chmod +x /usr/local/bin/list-backups
RUN chmod +x /usr/local/bin/backup


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::RequestBinding::RequestInfo;
use dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::ResponseMethods;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
use dom::bindings::error::Error;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::trace::RootedTraceableBox;
use dom::globalscope::GlobalScope;
use dom::headers::Guard;
use dom::promise::Promise;
use dom::request::Request;
use dom::response::Response;
use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsapi::JSAutoCompartment;
use net_traits::{FetchChannels, FetchResponseListener, NetworkError};
use net_traits::{FilteredMetadata, FetchMetadata, Metadata};
use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch;
use net_traits::request::{Request as NetTraitsRequest, ServiceWorkersMode};
use net_traits::request::RequestInit as NetTraitsRequestInit;
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};

struct FetchContext {
    fetch_promise: Option<TrustedPromise>,
    response_object: Trusted<Response>,
    body: Vec<u8>,
}

fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
    request.referrer.to_url().map(|url| url.clone())
}

fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit {
    NetTraitsRequestInit {
        method: request.method.clone(),
        url: request.url(),
        headers: request.headers.clone(),
        unsafe_request: request.unsafe_request,
        body: request.body.clone(),
        destination: request.destination,
        synchronous: request.synchronous,
        mode: request.mode.clone(),
        use_cors_preflight: request.use_cors_preflight,
        credentials_mode: request.credentials_mode,
        use_url_credentials: request.use_url_credentials,
        origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(),
        referrer_url: from_referrer_to_referrer_url(&request),
        referrer_policy: request.referrer_policy,
        pipeline_id: request.pipeline_id,
        redirect_mode: request.redirect_mode,
        ..NetTraitsRequestInit::default()
    }
}

// https://fetch.spec.whatwg.org/#fetch-method
#[allow(unrooted_must_root)]
pub fn Fetch(global: &GlobalScope, input: RequestInfo, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> {
    let core_resource_thread = global.core_resource_thread();

    // Step 1
    let promise = Promise::new(global);
    let response = Response::new(global);

    // Step 2
    let request = match Request::Constructor(global, input, init) {
        Err(e) => {
            promise.reject_error(e);
            return promise;
        },
        Ok(r) => r.get_request(),
    };
    let mut request_init = request_init_from_request(request);

    // Step 3
    if global.downcast::<ServiceWorkerGlobalScope>().is_some() {
        request_init.service_workers_mode = ServiceWorkersMode::Foreign;
    }

    // Step 4
    response.Headers().set_guard(Guard::Immutable);

    // Step 5
    let (action_sender, action_receiver) = ipc::channel().unwrap();
    let fetch_context = Arc::new(Mutex::new(FetchContext {
        fetch_promise: Some(TrustedPromise::new(promise.clone())),
        response_object: Trusted::new(&*response),
        body: vec![],
    }));
    let listener = NetworkListener {
        context: fetch_context,
        task_source: global.networking_task_source(),
        canceller: Some(global.task_canceller())
    };

    ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| {
        listener.notify_fetch(message.to().unwrap());
    }));
    core_resource_thread.send(
        NetTraitsFetch(request_init, FetchChannels::ResponseMsg(action_sender))).unwrap();

    promise
}

impl PreInvoke for FetchContext {}

impl FetchResponseListener for FetchContext {
    fn process_request_body(&mut self) {
        // TODO
    }

    fn process_request_eof(&mut self) {
        // TODO
    }

    #[allow(unrooted_must_root)]
    fn process_response(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) {
        let promise = self.fetch_promise.take().expect("fetch promise is missing").root();

        // JSAutoCompartment needs to be manually made.
        // Otherwise, Servo will crash.
        let promise_cx = promise.global().get_cx();
        let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get());
        match fetch_metadata {
            // Step 4.1
            Err(_) => {
                promise.reject_error(Error::Type("Network error occurred".to_string()));
                self.fetch_promise = Some(TrustedPromise::new(promise));
                self.response_object.root().set_type(DOMResponseType::Error);
                return;
            },
            // Step 4.2
            Ok(metadata) => {
                match metadata {
                    FetchMetadata::Unfiltered(m) => {
                        fill_headers_with_metadata(self.response_object.root(), m);
                        self.response_object.root().set_type(DOMResponseType::Default);
                    },
                    FetchMetadata::Filtered { filtered, .. } => match filtered {
                        FilteredMetadata::Basic(m) => {
                            fill_headers_with_metadata(self.response_object.root(), m);
                            self.response_object.root().set_type(DOMResponseType::Basic);
                        },
                        FilteredMetadata::Cors(m) => {
                            fill_headers_with_metadata(self.response_object.root(), m);
                            self.response_object.root().set_type(DOMResponseType::Cors);
                        },
                        FilteredMetadata::Opaque =>
                            self.response_object.root().set_type(DOMResponseType::Opaque),
                        FilteredMetadata::OpaqueRedirect =>
                            self.response_object.root().set_type(DOMResponseType::Opaqueredirect)
                    }
                }
            }
        }
        // Step 4.3
        promise.resolve_native(&self.response_object.root());
        self.fetch_promise = Some(TrustedPromise::new(promise));
    }

    fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
        self.body.append(&mut chunk);
    }

    fn process_response_eof(&mut self, _response: Result<(), NetworkError>) {
        let response = self.response_object.root();
        let global = response.global();
        let cx = global.get_cx();
        let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get());
        response.finish(mem::replace(&mut self.body, vec![]));
        // TODO
        // ... trailerObject is not supported in Servo yet.
    }
}

fn fill_headers_with_metadata(r: DomRoot<Response>, m: Metadata) {
    r.set_headers(m.headers);
    r.set_raw_status(m.status);
    r.set_final_url(m.final_url);
}


text:
package com.xeonlab.redmine.cli.options;

import com.xeonlab.redmine.cli.request.Request;

/**
 * @author Konstantin Simon Maria Moellers
 * @version 2015-01-22
 */
final class ProjectOption extends RedmineOption {
    ProjectOption() throws IllegalArgumentException {
        super("p", "project", true, "Project to load issues from.");
        setType(String.class);
        setArgName("project");
    }

    @Override
    public void applyTo(Request request) {
        request.setProject(getValue());
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<container
    xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
                        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="ekyna_characteristics.metadata.file_locator.class">Metadata\Driver\FileLocator</parameter>
        <parameter key="ekyna_characteristics.metadata.annotation_driver.class">Ekyna\Component\Characteristics\Metadata\Driver\AnnotationDriver</parameter>
        <parameter key="ekyna_characteristics.metadata.chain_driver.class">Metadata\Driver\DriverChain</parameter>
        <!--
        <parameter key="ekyna_characteristics.metadata.yaml_driver.class">Ekyna\Component\Characteristics\Metadata\Driver\YamlDriver</parameter>
        <parameter key="ekyna_characteristics.metadata.xml_driver.class">Ekyna\Component\Characteristics\Metadata\Driver\XmlDriver</parameter>
        <parameter key="ekyna_characteristics.metadata.php_driver.class">Ekyna\Component\Characteristics\Metadata\Driver\PhpDriver</parameter>
        -->
        <parameter key="ekyna_characteristics.metadata.lazy_loading_driver.class">Metadata\Driver\LazyLoadingDriver</parameter>
        <parameter key="ekyna_characteristics.metadata_factory.class">Metadata\MetadataFactory</parameter>
        <parameter key="ekyna_characteristics.metadata.cache.file_cache.class">Metadata\Cache\FileCache</parameter>

        <parameter key="ekyna_characteristics.schema_registry.class">Ekyna\Component\Characteristics\Schema\SchemaRegistry</parameter>

        <parameter key="ekyna_characteristics.manager.class">Ekyna\Component\Characteristics\Manager</parameter>

        <parameter key="ekyna_characteristics.abstract_maps_subscriber.class">Ekyna\Component\Characteristics\Doctrine\Listener\AbstractMapsSubscriber</parameter>

        <parameter key="ekyna_characteristics.characteristics.form_type.class">Ekyna\Component\Characteristics\Form\Type\CharacteristicsType</parameter>
        <parameter key="ekyna_characteristics.text_characteristic.form_type.class">Ekyna\Component\Characteristics\Form\Type\TextCharacteristicType</parameter>
        <parameter key="ekyna_characteristics.html_characteristic.form_type.class">Ekyna\Component\Characteristics\Form\Type\HtmlCharacteristicType</parameter>
        <parameter key="ekyna_characteristics.number_characteristic.form_type.class">Ekyna\Component\Characteristics\Form\Type\NumberCharacteristicType</parameter>
        <parameter key="ekyna_characteristics.boolean_characteristic.form_type.class">Ekyna\Component\Characteristics\Form\Type\BooleanCharacteristicType</parameter>
        <parameter key="ekyna_characteristics.datetime_characteristic.form_type.class">Ekyna\Component\Characteristics\Form\Type\DatetimeCharacteristicType</parameter>
        <parameter key="ekyna_characteristics.choice_characteristic.form_type.class">Ekyna\Bundle\CharacteristicsBundle\Form\Type\ChoiceCharacteristicType</parameter>

        <parameter key="ekyna_characteristics.twig.characteristics_extension.class">Ekyna\Component\Characteristics\Twig\CharacteristicsExtension</parameter>
    </parameters>

    <services>
        <!-- Metadata Drivers -->
        <service id="ekyna_characteristics.metadata.file_locator" class="%ekyna_characteristics.metadata.file_locator.class%" public="false">
            <argument type="collection" /><!-- Namespace Prefixes mapping to Directories -->
        </service>
        <!--
        <service id="ekyna_characteristics.metadata.yaml_driver" class="%ekyna_characteristics.metadata.yaml_driver.class%" public="false">
            <argument type="service" id="ekyna_characteristics.metadata.file_locator" />
        </service>
        <service id="ekyna_characteristics.metadata.xml_driver" class="%ekyna_characteristics.metadata.xml_driver.class%" public="false">
            <argument type="service" id="ekyna_characteristics.metadata.file_locator" />
        </service>
        <service id="ekyna_characteristics.metadata.php_driver" class="%ekyna_characteristics.metadata.php_driver.class%" public="false">
            <argument type="service" id="ekyna_characteristics.metadata.file_locator" />
        </service>
        -->
        <service id="ekyna_characteristics.metadata.annotation_driver" class="%ekyna_characteristics.metadata.annotation_driver.class%" public="false">
            <argument type="service" id="annotation_reader" />
        </service>
        <service id="ekyna_characteristics.metadata.chain_driver" class="%ekyna_characteristics.metadata.chain_driver.class%" public="false">
            <argument type="collection">
                <!--
                <argument type="service" id="ekyna_characteristics.metadata.yaml_driver" />
                <argument type="service" id="ekyna_characteristics.metadata.xml_driver" />
                <argument type="service" id="ekyna_characteristics.metadata.php_driver" />
                -->
                <argument type="service" id="ekyna_characteristics.metadata.annotation_driver" />
            </argument>
        </service>
        <service id="ekyna_characteristics.metadata_driver" alias="ekyna_characteristics.metadata.chain_driver" />

        <service id="ekyna_characteristics.metadata.lazy_loading_driver" class="%ekyna_characteristics.metadata.lazy_loading_driver.class%" public="false">
            <argument type="service" id="service_container" />
            <argument>ekyna_characteristics.metadata_driver</argument>
        </service>

        <!-- Metadata Factory -->
        <service id="ekyna_characteristics.metadata.cache.file_cache" class="%ekyna_characteristics.metadata.cache.file_cache.class%" public="false">
            <argument /><!-- Directory -->
        </service>
        <service id="ekyna_characteristics.metadata.cache" alias="ekyna_characteristics.metadata.cache.file_cache" public="false" />

        <!-- Metadata factory -->
        <service id="ekyna_characteristics.metadata_factory" class="%ekyna_characteristics.metadata_factory.class%" public="false">
            <argument type="service" id="ekyna_characteristics.metadata.lazy_loading_driver" />
            <argument>Metadata\ClassHierarchyMetadata</argument>
            <argument />
            <call method="setCache">
                <argument type="service" id="ekyna_characteristics.metadata.cache" on-invalid="ignore" />
            </call>
        </service>

        <!-- Schema registry -->
        <service id="ekyna_characteristics.schema_registry" class="%ekyna_characteristics.schema_registry.class%">
            <argument type="collection" /><!-- Bundles "config/characteristics" directories -->
        </service>

        <!-- Manager -->
        <service id="ekyna_characteristics.manager" class="%ekyna_characteristics.manager.class%">
            <argument type="service" id="ekyna_characteristics.metadata_factory" />
            <argument type="service" id="ekyna_characteristics.schema_registry" />
        </service>

        <!-- Doctrine subscriber -->
        <service id="ekyna_characteristics.abstract_maps_subscriber" class="%ekyna_characteristics.abstract_maps_subscriber.class%" public="false">
            <argument>%ekyna_characteristics.characteristics_classes_map%</argument>
            <tag name="doctrine.event_subscriber" connection="default" />
        </service>

        <!-- Form types -->
        <service id="ekyna_characteristics.characteristics.form_type" class="%ekyna_characteristics.characteristics.form_type.class%">
            <argument type="service" id="ekyna_characteristics.manager" />
            <argument type="service" id="doctrine.orm.entity_manager" />
            <tag name="form.type" alias="ekyna_characteristics" />
        </service>
        <service id="ekyna_characteristics.text_characteristic.form_type" class="%ekyna_characteristics.text_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_text_characteristic" />
        </service>
        <service id="ekyna_characteristics.html_characteristic.form_type" class="%ekyna_characteristics.html_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_html_characteristic" />
        </service>
        <service id="ekyna_characteristics.number_characteristic.form_type" class="%ekyna_characteristics.number_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_number_characteristic" />
        </service>
        <service id="ekyna_characteristics.boolean_characteristic.form_type" class="%ekyna_characteristics.boolean_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_boolean_characteristic" />
        </service>
        <service id="ekyna_characteristics.datetime_characteristic.form_type" class="%ekyna_characteristics.datetime_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_datetime_characteristic" />
        </service>
        <service id="ekyna_characteristics.choice_characteristic.form_type" class="%ekyna_characteristics.choice_characteristic.form_type.class%">
            <tag name="form.type" alias="ekyna_choice_characteristic" />
        </service>

        <!-- Twig extensions -->
        <service id="ekyna_characteristics.twig.characteristics_extension" class="%ekyna_characteristics.twig.characteristics_extension.class%">
            <argument type="service" id="ekyna_characteristics.manager" />
            <argument type="collection" />
            <tag name="twig.extension" alias="ekyna_characteristics" />
        </service>

        <!-- Admin pool configurations -->
        <service id="ekyna_characteristics.choice.configuration"
                 class="Ekyna\Bundle\AdminBundle\Pool\Configuration"
                 factory-service="ekyna_admin.pool_factory"
                 factory-method="createConfiguration">
            <argument>ekyna_characteristics</argument>
            <argument>choice</argument>
            <argument>Ekyna\Component\Characteristics\Entity\ChoiceCharacteristicValue</argument>
            <argument type="collection" />
            <tag name="ekyna_admin.configuration" alias="ekyna_characteristics_choice" />
        </service>

    </services>

</container>


text:
package org.aeonbits.owner;

import org.aeonbits.owner.Config.Sources;
import org.aeonbits.owner.loaders.Loader;
import org.aeonbits.owner.loaders.PropertiesLoader;
import org.aeonbits.owner.loaders.XMLLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;

import static org.aeonbits.owner.UtilTest.fileFromURI;
import static org.junit.Assert.assertEquals;

/**
 * @author Luigi R. Viggiano
 */
public class LoaderManagerTest implements TestConstants {
    private static final String SPEC = "file:" + RESOURCES_DIR + "/LoaderManagerTest.properties";

    @Mock
    private ScheduledExecutorService scheduler;
    private File target;

    @Sources(SPEC)
    interface MyConfig extends Config {
        String foo();
    }

    interface MyConfigDefaultSpec extends Config {
        String foo();
    }

    @Before
    public void before() throws URISyntaxException, IOException {
        target = fileFromURI(SPEC);
        target.getParentFile().mkdirs();
        target.createNewFile();
    }

    @After
    public void after() {
        target.delete();
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testProxyCreationWhenLoaderCantBeRisolvedForGivenURL() {
        Factory factory = new DefaultFactory(scheduler, new Properties()) {{
            loadersManager.clear();
        }};
        factory.registerLoader(new XMLLoader());
        factory.create(MyConfig.class);
    }

    @Test
    public void testProxyCreationInNormalSituation() {
        Factory factory = new DefaultFactory(scheduler, new Properties());
        MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class);
        assertEquals("bar", cfg.foo());
    }

    @Test
    public void testProxyCreationWhenLoaderReturnsFooBarAsDefaultSpec() {
        Factory factory = new DefaultFactory(scheduler, new Properties()) {{
            loadersManager.clear();
        }};

        factory.registerLoader(new PropertiesLoader());
        factory.registerLoader(new PropertiesLoader() {
            @Override
            public String defaultSpecFor(String uriPrefix) {
                return uriPrefix + ".foobar";
            }
        });

        MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class);
        assertEquals("foobar", cfg.foo());
    }

    @Test
    public void testProxyCreationWhenLoaderReturnsNullAsDefaultSpec() {
        Factory factory = new DefaultFactory(scheduler, new Properties()) {{
            loadersManager.clear();
        }};

        factory.registerLoader(new PropertiesLoader());
        factory.registerLoader(new PropertiesLoader() {
            @Override
            public String defaultSpecFor(String uriPrefix) {
                return null;
            }
        });

        MyConfigDefaultSpec cfg = factory.create(MyConfigDefaultSpec.class);
        assertEquals("bar", cfg.foo());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testRegisterNull() {
        Factory factory = ConfigFactory.newInstance();
        factory.registerLoader(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testRegisterNullOnSingleton() {
        ConfigFactory.registerLoader(null);
    }

    @Test
    public void testRegisterNonNullLoaderOnSingleton() {
        ConfigFactory.registerLoader(new LoaderThatDoesNothing());
    }

    public static class LoaderThatDoesNothing implements Loader {
        public boolean accept(URI uri) {
            return false;
        }

        public void load(Properties result, URI uri) throws IOException {
        }

        public String defaultSpecFor(String urlPrefix) {
            return null;
        }
    }

}