text:
<?php

namespace Statamic\Data\Content;

use Statamic\API\URL;
use Statamic\API\Page;
use Statamic\API\Path;
use Statamic\API\Config;
use Statamic\API\Str;
use Statamic\Contracts\Data\Content\PathBuilder as PathBuilderContract;

class PathBuilder implements PathBuilderContract
{
    protected $type = 'page';
    protected $uri;
    protected $slug;
    protected $parent_path;
    protected $collection;
    protected $published = true;
    protected $defaultPublished;
    protected $order;
    protected $extension = 'md';
    protected $locale;

    public function __construct()
    {
        $this->locale = site_locale();
    }

    public function page()
    {
        $this->type = 'page';

        return $this;
    }

    public function entry()
    {
        $this->type = 'entry';

        return $this;
    }

    public function term()
    {
        $this->type = 'term';

        return $this;
    }

    public function uri($uri)
    {
        $this->uri = Str::ensureLeft($uri, '/');

        return $this;
    }

    public function slug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    public function collection($collection)
    {
        $this->collection = $collection;

        return $this;
    }

    public function taxonomy($taxonomy)
    {
        return $this->collection($taxonomy);
    }

    public function published($published)
    {
        $this->published = $published;

        return $this;
    }

    public function defaultPublished($published)
    {
        $this->defaultPublished = $published;

        return $this;
    }

    public function order($order)
    {
        $this->order = $order;

        return $this;
    }

    public function locale($locale)
    {
        $this->locale = $locale;

        return $this;
    }

    public function extension($extension)
    {
        $this->extension = $extension;

        return $this;
    }

    public function parentPath($path)
    {
        $this->parent_path = $path;

        return $this;
    }

    public function get()
    {
        if (in_array($this->type, ['entry', 'term']) && (! $this->collection || ! $this->slug)) {
            throw new \Exception(sprintf(
                '%s and/or slug have not been specified.',
                $this->type === 'entry' ? 'Collection' : 'Taxonomy'
            ));
        }

        return $this->getFilename();
    }

    private function getFilename()
    {
        if ($this->type == 'page') {
            // pages/_1.slug/index.md
            // pages/_1.slug/fr.index.md
            return URL::tidy(
                $this->getParentPath() . $this->getStatusPrefix() . $this->getOrderPrefix() .
                $this->getSlug() . '/' . $this->getLocalePrefix() . 'index.' . $this->extension
            );
        }

        if ($this->type === 'entry') {
            $path = 'collections/' . $this->collection;

            // collections/blog/_1.slug.md
            // collections/blog/fr/_1.slug.md
            return Path::makeRelative($path) . '/' . $this->getLocalePrefix() .
            $this->getStatusPrefix() . $this->getOrderPrefix() . $this->getSlug() . '.' . $this->extension;
        }

        if ($this->type === 'term') {
            $path = 'taxonomies/'.$this->collection;

            // taxonomies/tags/_1.slug.yaml
            return Path::makeRelative($path) . '/' .
                   $this->getStatusPrefix() . $this->getOrderPrefix() . $this->getSlug() . '.' . $this->extension;
        }

        throw new \Exception('Unexpected type.');
    }

    private function getStatusPrefix()
    {
        if ($this->defaultPublished === false && $this->published) {
            return '_';
        }

        return ($this->published) ? '' : '_';
    }

    private function getOrderPrefix()
    {
        if ($this->order) {
            return $this->order . '.';
        }

        return '';
    }

    private function getLocalePrefix()
    {
        if (! $this->locale || $this->locale == Config::getDefaultLocale()) {
            return '';
        }

        $separator = ($this->type == 'page') ? '.' : '/';

        return $this->locale . $separator;
    }

    private function getSlug()
    {
        if ($this->type == 'page') {
            return URL::slug($this->uri);
        }

        return $this->slug;
    }

    private function getParentPath()
    {
        if ($this->parent_path) {
            $path = Str::ensureRight($this->parent_path, '/');

            $path = preg_replace('/^pages/', '', $path);

            return 'pages/'.$path;
        }

        $path = null;

        if ($this->uri == '/') {
            $path = '';
        }

        if (substr_count($this->uri, '/') > 1) {
            $parent = URL::parent($this->uri);

            if (! $page = Page::whereUri($parent)) {
                throw new \Exception("Parent page [$parent] doesn't exist.");
            }

            $path = $page->path();

            $path = Path::popLastSegment($path) . '/';
        }

        return $path ?: 'pages/'.$path;
    }
}


text:
package org.apache.beam.sdk.io.kudu;

import com.google.common.collect.ImmutableList;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduException;
import org.apache.kudu.client.KuduScanner;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.Operation;
import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.Upsert;

/** Utilities for Kudu tests. */
class KuduTestUtils {
  static final String COL_ID = "id";
  static final String COL_NAME = "name";

  static final Schema SCHEMA =
      new Schema(
          ImmutableList.of(
              new ColumnSchema.ColumnSchemaBuilder(COL_ID, Type.INT64).key(true).build(),
              new ColumnSchema.ColumnSchemaBuilder(COL_NAME, Type.STRING)
                  .nullable(false)
                  .desiredBlockSize(4096)
                  .encoding(ColumnSchema.Encoding.PLAIN_ENCODING)
                  .compressionAlgorithm(ColumnSchema.CompressionAlgorithm.NO_COMPRESSION)
                  .build()));

  static CreateTableOptions createTableOptions() {
    return new CreateTableOptions()
        .setRangePartitionColumns(ImmutableList.of(COL_ID))
        .setNumReplicas(1);
  }

  /** Creates an Upsert Operation that matches the schema for each input. */
  static class GenerateUpsert implements KuduIO.FormatFunction<Long> {
    @Override
    public Operation apply(TableAndRecord<Long> input) {
      Upsert upsert = input.getTable().newUpsert();
      PartialRow row = upsert.getRow();
      row.addLong(COL_ID, input.getRecord());
      row.addString(COL_NAME, input.getRecord() + ": name");
      return upsert;
    }
  }

  /** Returns the count of rows for the given table. */
  static int rowCount(KuduTable table) throws KuduException {
    KuduScanner scanner = table.getAsyncClient().syncClient().newScannerBuilder(table).build();
    try {
      int rowCount = 0;
      while (scanner.hasMoreRows()) {
        rowCount += scanner.nextRows().getNumRows();
      }
      return rowCount;
    } finally {
      scanner.close();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sling.fsprovider.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChange.ChangeType;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.apache.sling.testing.mock.sling.junit.SlingContextBuilder;
import org.apache.sling.testing.mock.sling.junit.SlingContextCallback;
import org.junit.Rule;
import org.junit.Test;

/**
 * Test events when changing filesystem content.
 */
public class FileMonitorTest {

    private final File tempDir;
    private final ResourceListener resourceListener = new ResourceListener();

    public FileMonitorTest() throws Exception {
        tempDir = Files.createTempDirectory(getClass().getName()).toFile();
    }

    @Rule
    public SlingContext context = new SlingContextBuilder(ResourceResolverType.JCR_MOCK)
        .beforeSetUp(new SlingContextCallback() {
            @Override
            public void execute(SlingContext context) throws Exception {
                // copy test content to temp. directory
                tempDir.mkdirs();
                File sourceDir = new File("src/test/resources/fs-test");
                FileUtils.copyDirectory(sourceDir, tempDir);

                // mount temp. directory
                context.registerInjectActivateService(new FsResourceProvider(),
                        "provider.file", tempDir.getPath(),
                        "provider.root", "/fs-test",
                        "provider.checkinterval", 120);

                // register resource change listener
                context.registerService(ResourceChangeListener.class, resourceListener,
                        ResourceChangeListener.PATHS, new String[] { "/fs-test" });
            }
        })
        .afterTearDown(new SlingContextCallback() {
            @Override
            public void execute(SlingContext context) throws Exception {
                // remove temp directory
                tempDir.delete();
            }
        })
        .build();

    @Test
    public void testUpdateFile() throws Exception {
        List<ResourceChange> changes = resourceListener.getChanges();
        assertTrue(changes.isEmpty());

        File file1a = new File(tempDir, "folder1/file1a.txt");
        FileUtils.write(file1a, "newcontent");

        Thread.sleep(250);

        assertEquals(1, changes.size());
        assertChange(changes, 0, "/fs-test/folder1/file1a.txt", ChangeType.CHANGED);
    }

    @Test
    public void testAddFile() throws Exception {
        List<ResourceChange> changes = resourceListener.getChanges();
        assertTrue(changes.isEmpty());

        File file1c = new File(tempDir, "folder1/file1c.txt");
        FileUtils.write(file1c, "newcontent");

        Thread.sleep(250);

        assertEquals(2, changes.size());
        assertChange(changes, 0, "/fs-test/folder1", ChangeType.CHANGED);
        assertChange(changes, 1, "/fs-test/folder1/file1c.txt", ChangeType.ADDED);
    }

    @Test
    public void testRemoveFile() throws Exception {
        List<ResourceChange> changes = resourceListener.getChanges();
        assertTrue(changes.isEmpty());

        File file1a = new File(tempDir, "folder1/file1a.txt");
        file1a.delete();

        Thread.sleep(250);

        assertEquals(2, changes.size());
        assertChange(changes, 0, "/fs-test/folder1", ChangeType.CHANGED);
        assertChange(changes, 1, "/fs-test/folder1/file1a.txt", ChangeType.REMOVED);
    }

    @Test
    public void testAddFolder() throws Exception {
        List<ResourceChange> changes = resourceListener.getChanges();
        assertTrue(changes.isEmpty());

        File folder3 = new File(tempDir, "folder3");
        folder3.mkdir();

        Thread.sleep(250);

        assertEquals(2, changes.size());
        assertChange(changes, 0, "/fs-test", ChangeType.CHANGED);
        assertChange(changes, 1, "/fs-test/folder3", ChangeType.ADDED);
    }

    @Test
    public void testRemoveFolder() throws Exception {
        List<ResourceChange> changes = resourceListener.getChanges();
        assertTrue(changes.isEmpty());

        File folder1 = new File(tempDir, "folder1");
        FileUtils.deleteDirectory(folder1);

        Thread.sleep(250);

        assertEquals(2, changes.size());
        assertChange(changes, 0, "/fs-test", ChangeType.CHANGED);
        assertChange(changes, 1, "/fs-test/folder1", ChangeType.REMOVED);
    }

    private void assertChange(List<ResourceChange> changes, int index, String path, ChangeType changeType) {
        ResourceChange change = changes.get(index);
        assertEquals(path, change.getPath());
        assertEquals(changeType, change.getType());
    }

    static class ResourceListener implements ResourceChangeListener {
        private final List<ResourceChange> allChanges = new ArrayList<>();
        @Override
        public void onChange(List<ResourceChange> changes) {
            allChanges.addAll(changes);
        }
        public List<ResourceChange> getChanges() {
            return allChanges;
        }
    }

}


text:
using System.Collections.Generic;
using System.Diagnostics;

namespace JetBlack.Diagnostics.Test
{
    public delegate bool TryGetValue<TKey, TValue>(TKey key, out TValue value);

    public class Cache<TKey, TValue>
    {
        private readonly IDictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();
        private readonly TryGetValue<TKey, TValue> _tryGetValue;
        private readonly CacheMonitor _monitor;

        public Cache(TryGetValue<TKey, TValue> tryGetValue, CacheMonitor monitor)
        {
            _tryGetValue = tryGetValue;
            _monitor = monitor;
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            if (_cache.TryGetValue(key, out value))
                return true;

            var stopwatch = new Stopwatch();
            try
            {
                stopwatch.Start();
                if (!_tryGetValue(key, out value))
                    return false;
                _cache.Add(key, value);
                return true;
            }
            finally
            {
                stopwatch.Stop();
                _monitor.AverageFetch.Increment(stopwatch.ElapsedTicks);
                _monitor.Count.Increment();
            }
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.servicecontrol.v1.model;

/**
 * Request message for QuotaController.StartReconciliation.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Service Control API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class StartReconciliationRequest extends com.google.api.client.json.GenericJson {

  /**
   * Operation that describes the quota reconciliation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private QuotaOperation reconciliationOperation;

  /**
   * Specifies which version of service configuration should be used to process the request. If
   * unspecified or no matching version can be found, the latest one will be used.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String serviceConfigId;

  /**
   * Operation that describes the quota reconciliation.
   * @return value or {@code null} for none
   */
  public QuotaOperation getReconciliationOperation() {
    return reconciliationOperation;
  }

  /**
   * Operation that describes the quota reconciliation.
   * @param reconciliationOperation reconciliationOperation or {@code null} for none
   */
  public StartReconciliationRequest setReconciliationOperation(QuotaOperation reconciliationOperation) {
    this.reconciliationOperation = reconciliationOperation;
    return this;
  }

  /**
   * Specifies which version of service configuration should be used to process the request. If
   * unspecified or no matching version can be found, the latest one will be used.
   * @return value or {@code null} for none
   */
  public java.lang.String getServiceConfigId() {
    return serviceConfigId;
  }

  /**
   * Specifies which version of service configuration should be used to process the request. If
   * unspecified or no matching version can be found, the latest one will be used.
   * @param serviceConfigId serviceConfigId or {@code null} for none
   */
  public StartReconciliationRequest setServiceConfigId(java.lang.String serviceConfigId) {
    this.serviceConfigId = serviceConfigId;
    return this;
  }

  @Override
  public StartReconciliationRequest set(String fieldName, Object value) {
    return (StartReconciliationRequest) super.set(fieldName, value);
  }

  @Override
  public StartReconciliationRequest clone() {
    return (StartReconciliationRequest) super.clone();
  }

}


text:
@interface ViewController ()

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UIButton *button;

@end

@implementation ViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        self.title = @"LGSideMenuController";

        self.view.backgroundColor = [UIColor whiteColor];

        // -----

        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image3"]];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self.view addSubview:_imageView];

//        _button = [UIButton new];
//        _button.backgroundColor = [UIColor colorWithWhite:1.f alpha:0.5];
//        [_button setTitle:@"Show Choose Controller" forState:UIControlStateNormal];
//        [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [_button setTitleColor:[UIColor colorWithRed:0.f green:0.5 blue:1.f alpha:1.f] forState:UIControlStateHighlighted];
//        [_button addTarget:self action:@selector(showChooseController) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:_button];

        // -----

        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Left" style:UIBarButtonItemStylePlain target:self action:@selector(openLeftView)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(openRightView)];
    }
    return self;
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    _imageView.frame = CGRectMake(0.f, 0.f, self.view.frame.size.width, self.view.frame.size.height);

    _button.frame = CGRectMake(0.f, self.view.frame.size.height-44.f, self.view.frame.size.width, 44.f);
}

#pragma mark -

- (void)openLeftView
{
    [kMainViewController showLeftViewAnimated:YES completionHandler:nil];
}

- (void)openRightView
{
    [kMainViewController showRightViewAnimated:YES completionHandler:nil];
}

//- (void)showChooseController
//{
//    TableViewController *viewController = [TableViewController new];
//    ChooseNavigationController *navigationController = [[ChooseNavigationController alloc] initWithRootViewController:viewController];
//
//    UIWindow *window = [UIApplication sharedApplication].delegate.window;
//
//    window.rootViewController = navigationController;
//
//    [UIView transitionWithView:window
//                      duration:0.3
//                       options:UIViewAnimationOptionTransitionCrossDissolve
//                    animations:nil
//                    completion:nil];
//}

@end


text:
import Target from '../app/model/target.js';

test('constructor', () => {
    // Arrange
    let object_under_test = new Target();

    // Act
    // Empty

    // Assert
    expect(object_under_test.hits()).toBe(0);
    expect(object_under_test.getDoneRound()).toBe(null);
    expect(object_under_test.isDone()).toBe(false);
    expect(object_under_test.getMilestones()).toEqual([]);
});

test('basic increment', () => {
    // Arrange
    let object_under_test = new Target();

    // Act
    object_under_test.markHit({round: 1});

    // Assert
    expect(object_under_test.hits()).toBe(1);
    expect(object_under_test.getDoneRound()).toBe(null);
    expect(object_under_test.isDone()).toBe(false);
    expect(object_under_test.getMilestones()).toEqual([{round: 1}]);
});

test('increment 2x', () => {
    // Arrange
    let object_under_test = new Target();
    object_under_test.markHit({round: 1});

    // Act
    object_under_test.markHit({round: 2});

    // Assert
    expect(object_under_test.hits()).toBe(2);
    expect(object_under_test.getDoneRound()).toBe(null);
    expect(object_under_test.isDone()).toBe(false);
    expect(object_under_test.getMilestones()).toEqual([{round: 1}, {round: 2}]);
});

test('increment 3x', () => {
    // Arrange
    let object_under_test = new Target();
    object_under_test.markHit({round: 1});
    object_under_test.markHit({round: 2});

    // Act
    object_under_test.markHit({round: 3});

    // Assert
    expect(object_under_test.hits()).toBe(3);
    expect(object_under_test.getDoneRound()).toEqual(3);
    expect(object_under_test.isDone()).toBe(true);
    expect(object_under_test.getMilestones()).toEqual([{round: 1}, {round: 2}, {round: 3}]);
});

test('increment 4x', () => {
    // Arrange
    let object_under_test = new Target();
    object_under_test.markHit({round: 1});
    object_under_test.markHit({round: 2});
    object_under_test.markHit({round: 3});

    // Assert
    expect(() => {object_under_test.markHit({round: 4})}).toThrow();
    expect(object_under_test.hits()).toBe(3);
    expect(object_under_test.getDoneRound()).toEqual(3);
    expect(object_under_test.isDone()).toBe(true);
    expect(object_under_test.getMilestones()).toEqual([{round: 1}, {round: 2}, {round: 3}]);

});


text:
package org.apache.jena.fuseki.access;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.apache.jena.graph.Node;
import org.apache.jena.sparql.core.assembler.AssemblerUtils;
import org.apache.jena.sys.JenaSystem;
import org.junit.Test;

/** Test parsing of assemblers with security aspects */
public class TestSecurityRegistry {
    static { JenaSystem.init(); }
    static final String DIR = "testing/SecurityRegistry/";

    @Test public void assemblerFile_1() {
        AuthorizationService authService = (AuthorizationService)AssemblerUtils.build(DIR+"assem-security-registry-1.ttl", VocabSecurity.tSecurityRegistry);
        assertNotNull(authService);
        SecurityRegistry sReg = (SecurityRegistry)authService;
        assertEquals(4, sReg.keys().size());
        assertEquals(3, sReg.get("user1").visibleGraphs().size());
    }

    @Test public void assemblerFile_2() {
        // WIP
        //   user1, all named graphs
        //   user2, all graphs
        //   user3, all named graphs +dft == all graphs
        //   any user, graph1
        AuthorizationService authService = (AuthorizationService)AssemblerUtils.build(DIR+"assem-security-registry-2.ttl", VocabSecurity.tSecurityRegistry);
        assertNotNull(authService);

        {
            SecurityContext sCxt = authService.get("user1");
            assertEquals(1, sCxt.visibleGraphs().size());
            Node x = sCxt.visibleGraphs().stream().findFirst().get();
            assertEquals(SecurityContext.allNamedGraphs, x);
        }

        {
            SecurityContext sCxt = authService.get("user2");
            assertEquals(1, sCxt.visibleGraphs().size());
            Node x = sCxt.visibleGraphs().stream().findFirst().get();
            assertEquals(SecurityContext.allGraphs, x);
        }

        {
            SecurityContext sCxt = authService.get("user3");
            assertEquals(1, sCxt.visibleGraphs().size());
            Node x = sCxt.visibleGraphs().stream().findFirst().get();
            assertEquals(SecurityContext.allGraphs, x);
        }

        {
            SecurityContext sCxt = authService.get("*");
            assertEquals(1, sCxt.visibleGraphs().size());
            String x = sCxt.visibleGraphNames().stream().findFirst().get();
            assertEquals("http://host/graphname1", x);
        }
    }
}


text:
#ifndef _ASM_X86_STAT_H
#define _ASM_X86_STAT_H

#include <asm/posix_types.h>

#define STAT_HAVE_NSEC 1

#ifdef __i386__
struct stat {
	unsigned long  st_dev;
	unsigned long  st_ino;
	unsigned short st_mode;
	unsigned short st_nlink;
	unsigned short st_uid;
	unsigned short st_gid;
	unsigned long  st_rdev;
	unsigned long  st_size;
	unsigned long  st_blksize;
	unsigned long  st_blocks;
	unsigned long  st_atime;
	unsigned long  st_atime_nsec;
	unsigned long  st_mtime;
	unsigned long  st_mtime_nsec;
	unsigned long  st_ctime;
	unsigned long  st_ctime_nsec;
	unsigned long  __unused4;
	unsigned long  __unused5;
};

/* We don't need to memset the whole thing just to initialize the padding */
#define INIT_STRUCT_STAT_PADDING(st) do {	\
	st.__unused4 = 0;			\
	st.__unused5 = 0;			\
} while (0)

#define STAT64_HAS_BROKEN_ST_INO	1

/* This matches struct stat64 in glibc2.1, hence the absolutely
 * insane amounts of padding around dev_t's.
 */
struct stat64 {
	unsigned long long	st_dev;
	unsigned char	__pad0[4];

	unsigned long	__st_ino;

	unsigned int	st_mode;
	unsigned int	st_nlink;

	unsigned long	st_uid;
	unsigned long	st_gid;

	unsigned long long	st_rdev;
	unsigned char	__pad3[4];

	long long	st_size;
	unsigned long	st_blksize;

	/* Number 512-byte blocks allocated. */
	unsigned long long	st_blocks;

	unsigned long	st_atime;
	unsigned long	st_atime_nsec;

	unsigned long	st_mtime;
	unsigned int	st_mtime_nsec;

	unsigned long	st_ctime;
	unsigned long	st_ctime_nsec;

	unsigned long long	st_ino;
};

/* We don't need to memset the whole thing just to initialize the padding */
#define INIT_STRUCT_STAT64_PADDING(st) do {		\
	memset(&st.__pad0, 0, sizeof(st.__pad0));	\
	memset(&st.__pad3, 0, sizeof(st.__pad3));	\
} while (0)

#else /* __i386__ */

struct stat {
	__kernel_ulong_t	st_dev;
	__kernel_ulong_t	st_ino;
	__kernel_ulong_t	st_nlink;

	unsigned int		st_mode;
	unsigned int		st_uid;
	unsigned int		st_gid;
	unsigned int		__pad0;
	__kernel_ulong_t	st_rdev;
	__kernel_long_t		st_size;
	__kernel_long_t		st_blksize;
	__kernel_long_t		st_blocks;	/* Number 512-byte blocks allocated. */

	__kernel_ulong_t	st_atime;
	__kernel_ulong_t	st_atime_nsec;
	__kernel_ulong_t	st_mtime;
	__kernel_ulong_t	st_mtime_nsec;
	__kernel_ulong_t	st_ctime;
	__kernel_ulong_t	st_ctime_nsec;
	__kernel_long_t		__unused[3];
};

/* We don't need to memset the whole thing just to initialize the padding */
#define INIT_STRUCT_STAT_PADDING(st) do {	\
	st.__pad0 = 0;				\
	st.__unused[0] = 0;			\
	st.__unused[1] = 0;			\
	st.__unused[2] = 0;			\
} while (0)

#endif

/* for 32bit emulation and 32 bit kernels */
struct __old_kernel_stat {
	unsigned short st_dev;
	unsigned short st_ino;
	unsigned short st_mode;
	unsigned short st_nlink;
	unsigned short st_uid;
	unsigned short st_gid;
	unsigned short st_rdev;
#ifdef __i386__
	unsigned long  st_size;
	unsigned long  st_atime;
	unsigned long  st_mtime;
	unsigned long  st_ctime;
#else
	unsigned int  st_size;
	unsigned int  st_atime;
	unsigned int  st_mtime;
	unsigned int  st_ctime;
#endif
};

#endif /* _ASM_X86_STAT_H */


text:
Various dockerfiles for microservices.

  - [HAProxy-confd](haproxy-confd/README.md): haproxy load balancer with etcd configuration


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Helpers.WinHttp;
using Titanium.Web.Proxy.Models;

namespace Titanium.Web.Proxy.UnitTests
{
    [TestClass]
    public class SystemProxyTest
    {
        [TestMethod]
        public void CompareProxyAddressReturnedByWebProxyAndWinHttpProxyResolver()
        {
            var proxyManager = new SystemProxyManager();

            try
            {
                compareUrls();

                proxyManager.SetProxy("127.0.0.1", 8000, ProxyProtocolType.Http);
                compareUrls();

                proxyManager.SetProxy("127.0.0.1", 8000, ProxyProtocolType.Https);
                compareUrls();

                proxyManager.SetProxy("127.0.0.1", 8000, ProxyProtocolType.AllHttp);
                compareUrls();

                // for this test you need to add a proxy.pac file to a local webserver
                //function FindProxyForURL(url, host)
                //{
                //    if (shExpMatch(host, "google.com"))
                //    {
                //        return "PROXY 127.0.0.1:8888";
                //    }

                //    return "DIRECT";
                //}

                //proxyManager.SetAutoProxyUrl("http://localhost/proxy.pac");
                //CompareUrls();

                proxyManager.SetProxyOverride("<-loopback>");
                compareUrls();

                proxyManager.SetProxyOverride("<local>");
                compareUrls();

                proxyManager.SetProxyOverride("yahoo.com");
                compareUrls();

                proxyManager.SetProxyOverride("*.local");
                compareUrls();

                proxyManager.SetProxyOverride("http://*.local");
                compareUrls();

                proxyManager.SetProxyOverride("<-loopback>;*.local");
                compareUrls();

                proxyManager.SetProxyOverride("<-loopback>;*.local;<local>");
                compareUrls();
            }
            finally
            {
                proxyManager.RestoreOriginalSettings();
            }
        }

        private void compareUrls()
        {
            var webProxy = WebRequest.GetSystemWebProxy();

            var resolver = new WinHttpWebProxyFinder();
            resolver.LoadFromIE();

            CompareProxy(webProxy, resolver, "http://127.0.0.1");
            CompareProxy(webProxy, resolver, "https://127.0.0.1");
            CompareProxy(webProxy, resolver, "http://localhost");
            CompareProxy(webProxy, resolver, "https://localhost");

            string hostName = null;
            try
            {
                hostName = Dns.GetHostName();
            }
            catch
            {
            }

            if (hostName != null)
            {
                CompareProxy(webProxy, resolver, "http://" + hostName);
                CompareProxy(webProxy, resolver, "https://" + hostName);
            }

            CompareProxy(webProxy, resolver, "http://google.com");
            CompareProxy(webProxy, resolver, "https://google.com");
            CompareProxy(webProxy, resolver, "http://bing.com");
            CompareProxy(webProxy, resolver, "https://bing.com");
            CompareProxy(webProxy, resolver, "http://yahoo.com");
            CompareProxy(webProxy, resolver, "https://yahoo.com");
            CompareProxy(webProxy, resolver, "http://test.local");
            CompareProxy(webProxy, resolver, "https://test.local");
        }

        private void CompareProxy(IWebProxy webProxy, WinHttpWebProxyFinder resolver, string url)
        {
            var uri = new Uri(url);

            var expectedProxyUri = webProxy.GetProxy(uri);

            var proxy = resolver.GetProxy(uri);

            if (expectedProxyUri == uri)
            {
                // no proxy
                Assert.AreEqual(proxy, null);
                return;
            }

            Assert.AreEqual(expectedProxyUri.ToString(), $"http://{proxy.HostName}:{proxy.Port}/");
        }
    }
}


text:
#include <aws/kinesisanalyticsv2/model/RunConfigurationDescription.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace KinesisAnalyticsV2
{
namespace Model
{

RunConfigurationDescription::RunConfigurationDescription() :
    m_applicationRestoreConfigurationDescriptionHasBeenSet(false),
    m_flinkRunConfigurationDescriptionHasBeenSet(false)
{
}

RunConfigurationDescription::RunConfigurationDescription(JsonView jsonValue) :
    m_applicationRestoreConfigurationDescriptionHasBeenSet(false),
    m_flinkRunConfigurationDescriptionHasBeenSet(false)
{
  *this = jsonValue;
}

RunConfigurationDescription& RunConfigurationDescription::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ApplicationRestoreConfigurationDescription"))
  {
    m_applicationRestoreConfigurationDescription = jsonValue.GetObject("ApplicationRestoreConfigurationDescription");

    m_applicationRestoreConfigurationDescriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FlinkRunConfigurationDescription"))
  {
    m_flinkRunConfigurationDescription = jsonValue.GetObject("FlinkRunConfigurationDescription");

    m_flinkRunConfigurationDescriptionHasBeenSet = true;
  }

  return *this;
}

JsonValue RunConfigurationDescription::Jsonize() const
{
  JsonValue payload;

  if(m_applicationRestoreConfigurationDescriptionHasBeenSet)
  {
   payload.WithObject("ApplicationRestoreConfigurationDescription", m_applicationRestoreConfigurationDescription.Jsonize());

  }

  if(m_flinkRunConfigurationDescriptionHasBeenSet)
  {
   payload.WithObject("FlinkRunConfigurationDescription", m_flinkRunConfigurationDescription.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws


text:
TABLE OF INTERACTIONS WITH

CABAZITAXEL

See also: cytotoxics

See also: substrates at risk of CYP3A4

From the French ANSM drug interactions document of September 2016, p. 48

CABAZITAXEL

RxNorm: 996051

ATC: L01CD04

ENZYMATIC INDUCERS

CLASS CODE:

N03-J05-001

Decrease of the concentrations of the cytotoxic by increase of its metabolism by the inducer, with risk of lower effectiveness

Take into account

CABAZITAXEL

RxNorm: 996051

ATC: L01CD04

STRONG INHIBITORS OF CYP3A4

CLASS CODE:

J02-J05

Risk of increase of the undesirable dose dependent effects of the cabazitaxel due to inhibition of its metabolism by the enzymatic inducer

Precaution for use

Clinical monitoring and possible adjustment of the dosage of the cabazitaxel during the treatment with the enzymatic inhibitor.


text:
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2
from google.cloud.apigeeregistry.v1.scoring import score_pb2 as google_dot_cloud_dot_apigeeregistry_dot_v1_dot_scoring_dot_score__pb2

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n7google/cloud/apigeeregistry/v1/scoring/score_card.proto\x12&google.cloud.apigeeregistry.v1.scoring\x1a\x1fgoogle/api/field_behavior.proto\x1a\x32google/cloud/apigeeregistry/v1/scoring/score.proto\"\xb7\x01\n\tScoreCard\x12\x0f\n\x02id\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x03 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\x12\x1c\n\x0f\x64\x65\x66inition_name\x18\x05 \x01(\tB\x03\xe0\x41\x02\x12\x42\n\x06scores\x18\x06 \x03(\x0b\x32-.google.cloud.apigeeregistry.v1.scoring.ScoreB\x03\xe0\x41\x02\x42i\n*com.google.cloud.apigeeregistry.v1.scoringB\x15ScoringScoreCardProtoP\x01Z\"github.com/apigee/registry/rpc;rpcb\x06proto3')

_SCORECARD = DESCRIPTOR.message_types_by_name['ScoreCard']
ScoreCard = _reflection.GeneratedProtocolMessageType('ScoreCard', (_message.Message,), {
  'DESCRIPTOR' : _SCORECARD,
  '__module__' : 'google.cloud.apigeeregistry.v1.scoring.score_card_pb2'
  # @@protoc_insertion_point(class_scope:google.cloud.apigeeregistry.v1.scoring.ScoreCard)
  })
_sym_db.RegisterMessage(ScoreCard)

if _descriptor._USE_C_DESCRIPTORS == False:

  DESCRIPTOR._options = None
  DESCRIPTOR._serialized_options = b'\n*com.google.cloud.apigeeregistry.v1.scoringB\025ScoringScoreCardProtoP\001Z\"github.com/apigee/registry/rpc;rpc'
  _SCORECARD.fields_by_name['id']._options = None
  _SCORECARD.fields_by_name['id']._serialized_options = b'\340A\002'
  _SCORECARD.fields_by_name['definition_name']._options = None
  _SCORECARD.fields_by_name['definition_name']._serialized_options = b'\340A\002'
  _SCORECARD.fields_by_name['scores']._options = None
  _SCORECARD.fields_by_name['scores']._serialized_options = b'\340A\002'
  _SCORECARD._serialized_start=185
  _SCORECARD._serialized_end=368
# @@protoc_insertion_point(module_scope)


text:
package com.aitusoftware.transport.buffer;

public enum WriteResult
{
    SUCCESS,
    FAILURE,
    NOT_ENOUGH_SPACE,
    MESSAGE_TOO_LARGE
}


text:
Settings::Settings(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Settings)
{
    ui->setupUi(this);

    saveFile.setFileName("settings.dat");

    ui->pushButtonCancel->setFocusPolicy(Qt::NoFocus);
    ui->pushButtonSave->setFocusPolicy(Qt::NoFocus);
    ui->pushButtonFont->setFocusPolicy(Qt::NoFocus);
}

void Settings::showEvent(QShowEvent *)
{
    if(!saveFile.open(QIODevice::ReadOnly))
    {
        if(saveFile.exists())
            QMessageBox::critical(NULL,"Napaka pri branju","Datoteke settings.dat ni bilo mogoče odpreti za branje.");

        return;
    }
    else
    {
        QDataStream in(&saveFile);

        bool status,lineWrap;

        in >> textColor >> textFont >> status >> lineWrap;

        ui->checkBoxLineWrap->setChecked(lineWrap);
        ui->checkBoxStatusBar->setChecked(status);
        ui->toolButtonColor->setStyleSheet("background-color: " + textColor.name() + ";");
    }

    saveFile.close();
}

Settings::~Settings()
{
    delete ui;
}

void Settings::on_pushButtonSave_clicked()
{

    if(!saveFile.open(QIODevice::WriteOnly))
    {
        if(saveFile.exists())
            QMessageBox::critical(NULL,"Napaka pri shranjevanju","Datoteke settings.dat ni bilo mogoče odpreti za pisanje.");

        return;
    }
    QDataStream out(&saveFile);

    out << textColor << textFont << ui->checkBoxStatusBar->isChecked() << ui->checkBoxLineWrap->isChecked();

    saveFile.close();

    this->close();
}

void Settings::on_pushButtonFont_clicked()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok,textFont);

    if(ok)
        textFont = font;
}

void Settings::on_toolButtonColor_clicked()
{
    QColor color = QColorDialog::getColor(textColor);

    if(color.isValid())
    {
        textColor = color;
        ui->toolButtonColor->setStyleSheet("background-color: " + textColor.name() + ";");
    }
}

void Settings::on_pushButtonCancel_clicked()
{
    this->close();
}


text:
$(function () {

    $('.module').eq(0).show().siblings('.module').hide();

    remove_or_show_nav_buttons();

    $('#Slide').slider({});
});

$("#next_module").click(function () {
    $next_module_tab =  $("li.active").next();
    $("li.active").removeClass("active");
    $next_module_tab.attr("class", "active");

    var index = $next_module_tab.index();
    $('.module').eq(index).show().siblings('.module').hide();

    remove_or_show_nav_buttons()

});

$("#previous_module").click(function () {
    $prev_module =  $("li.active").prev();
    $("li.active").removeClass("active");
    $prev_module.attr("class", "active");

    var index = $prev_module.index();
    $('.module').eq(index).show().siblings('.module').hide();

    remove_or_show_nav_buttons()

});

//Checks to see if at beginning or end of modules, if so, hides the appropriate buttons.
function  remove_or_show_nav_buttons() {

    if( !$("li.active").prev('li')[0] ) {
        console.log("doesnt exist");
        $("#previous_module").hide();
    }
    else{
        $("#previous_module").show()
    }
    if(! $("li.active").next('li')[0] ) {
        $("#next_module").hide();
    }
    else{
        $("#next_module").show();
    }

}


text:
Article 670
----
Les arbres qui se trouvent dans la haie mitoyenne sont mitoyens comme la haie.
Les arbres plantés sur la ligne séparative de deux héritages sont aussi réputés
mitoyens. Lorsqu'ils meurent ou lorsqu'ils sont coupés ou arrachés, ces arbres
sont partagés par moitié. Les fruits sont recueillis à frais communs et partagés
aussi par moitié, soit qu'ils tombent naturellement, soit que la chute en ait
été provoquée, soit qu'ils aient été cueillis.

Chaque propriétaire a le droit d'exiger que les arbres mitoyens soient arrachés.


text:
app.directive('commentGroup', ['$http', '$rootScope', function($http, $rootScope) {
        return {
            templateUrl: '/templates/comment/comment_group.tpl.html',
            scope: {
                threadObjType: '@',
                threadObjId: '=',
                showNewCommentBox: '=?',
                txtNoComment: '@',
                commentCount: '=?',
                onLoaded: '&?'
            },
            link: function(scope, element, attr) {
                scope.loaded = false;
                if (!angular.isDefined(scope.showNewCommentBox)) scope.showNewCommentBox = true;
                if (!angular.isDefined(scope.txtNoComment)) scope.txtNoComment = 'Không có bình luận.';
                var threadCode = null;

                scope.load = function() {
                    if (!threadCode) return;
                    scope.loading = true;
                    $http({
                        method: 'GET',
                        url: Routing.generate('api_comment_list', {code: threadCode})
                    }).then(function(response) {
                        scope.comments = response.data.data;
                        scope.commentCount = scope.comments.length;
                        scope.loading = false;
                        scope.loaded = true;
                        if (angular.isDefined(scope.onLoaded)) scope.onLoaded();
                    });
                }

                scope.$watch('threadObjId', function(newValue, oldValue) {
                    if (isNaN(newValue)) return;
                    threadCode = scope.threadObjType + '-' + scope.threadObjId;
                    scope.load();
                });

                scope.send = function() {
                    if (!threadCode) return;
                    scope.sending = true;
                    $http({
                        method: 'POST',
                        url: Routing.generate('api_comment_post', {objType: scope.threadObjType, objId: scope.threadObjId}),
                        data: { content: scope.commentContent },
                    }).then(function(response) {
                        if (response.data.status == 'success') {
                            scope.load(threadCode);
                            scope.commentContent = '';
                        } else {
                            scope.errorMessage = response.data.message;
                        }
                        scope.showReply = false;
                        scope.sending = false;
                    });
                }
            },
        };
    }])
    .directive('comment', ['$http', '$rootScope', function($http, $rootScope) {
        return {
            templateUrl: '/templates/comment/comment.tpl.html',
            scope: {
                comment: '=ngData',
                noReply: '@',
                noRootComment: '@?',
                alwaysShowReplyBox: '@?',
                commentCount: '=?',
                onLoaded: '&?',
            },
            link: function(scope, element, attr) {
                scope.noRootComment = angular.isDefined(scope.noRootComment);
                scope.alwaysShowReplyBox = angular.isDefined(scope.alwaysShowReplyBox);

                $http.get(Routing.generate('api_comment_permission', {id: scope.comment.id})).then(function(response) {
                    scope.permission = response.data.data;
                });

                scope.load = function() {
                    scope.loading = true;
                    $http({
                        method: 'GET',
                        url: Routing.generate('api_comment_list', {code: scope.comment.threadCode}) + '?parent=' + scope.comment.id
                    }).then(function(response) {
                        scope.comments = response.data.data;
                        scope.commentCount = scope.comments.length;
                        scope.loading = false;
                        if (angular.isDefined(scope.onLoaded)) scope.onLoaded();
                    });
                }

                scope.delete = function() {
                    if (!confirm("Bạn muốn xoá?")) return;
                    $http({
                        method: 'DELETE',
                        url: Routing.generate('api_comment', {id: scope.comment.id})
                    }).then(function(response) {
                        scope.comment = null;
                    })
                }

                scope.send = function() {
                    scope.sending = true;
                    $http({
                        method: 'POST',
                        url: Routing.generate('api_comment_post', {objType: scope.comment.threadObjType, objId: scope.comment.threadObjId}),
                        data: { content: scope.commentContent, parent: scope.comment.id },
                    }).then(function(response) {
                        if (response.data.status == 'success') {
                            scope.load();
                            scope.commentContent = '';
                        } else {
                            scope.errorMessage = response.data.message;
                        }
                        scope.showReply = false;
                        scope.sending = false;
                    });
                }

                scope.load();
            },
        };
    }])


text:
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
Rails.application.config.assets.precompile += %w(propublica_base/base.css propublica_base/master.css propublica_base/print.css propublica_base/woland.css)


text:
Rails.application.routes.draw do
  namespace :ckeditor, :only => [:index, :create, :destroy] do
    resources :pictures
    resources :attachment_files
  end
end


text:
package v1beta1

// This file contains a collection of methods that can be used from go-restful to
// generate Swagger API documentation for its models. Please read this PR for more
// information on the implementation: https://github.com/emicklei/go-restful/pull/215
//
// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
// they are on one line! For multiple line or blocks that you want to ignore use ---.
// Any context after a --- is ignored.
//
// Those methods can be generated by using hack/update-generated-swagger-docs.sh

// AUTO-GENERATED FUNCTIONS START HERE
var map_LocalSubjectAccessReview = map[string]string{
	"":       "LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking.",
	"spec":   "Spec holds information about the request being evaluated.  spec.namespace must be equal to the namespace you made the request against.  If empty, it is defaulted.",
	"status": "Status is filled in by the server and indicates whether the request is allowed or not",
}

func (LocalSubjectAccessReview) SwaggerDoc() map[string]string {
	return map_LocalSubjectAccessReview
}

var map_NonResourceAttributes = map[string]string{
	"":     "NonResourceAttributes includes the authorization attributes available for non-resource requests to the Authorizer interface",
	"path": "Path is the URL path of the request",
	"verb": "Verb is the standard HTTP verb",
}

func (NonResourceAttributes) SwaggerDoc() map[string]string {
	return map_NonResourceAttributes
}

var map_NonResourceRule = map[string]string{
	"":                "NonResourceRule holds information that describes a rule for the non-resource",
	"verbs":           "Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options.  \"*\" means all.",
	"nonResourceURLs": "NonResourceURLs is a set of partial urls that a user should have access to.  *s are allowed, but only as the full, final step in the path.  \"*\" means all.",
}

func (NonResourceRule) SwaggerDoc() map[string]string {
	return map_NonResourceRule
}

var map_ResourceAttributes = map[string]string{
	"":            "ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface",
	"namespace":   "Namespace is the namespace of the action being requested.  Currently, there is no distinction between no namespace and all namespaces \"\" (empty) is defaulted for LocalSubjectAccessReviews \"\" (empty) is empty for cluster-scoped resources \"\" (empty) means \"all\" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview",
	"verb":        "Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy.  \"*\" means all.",
	"group":       "Group is the API Group of the Resource.  \"*\" means all.",
	"version":     "Version is the API Version of the Resource.  \"*\" means all.",
	"resource":    "Resource is one of the existing resource types.  \"*\" means all.",
	"subresource": "Subresource is one of the existing resource types.  \"\" means none.",
	"name":        "Name is the name of the resource being requested for a \"get\" or deleted for a \"delete\". \"\" (empty) means all.",
}

func (ResourceAttributes) SwaggerDoc() map[string]string {
	return map_ResourceAttributes
}

var map_ResourceRule = map[string]string{
	"":              "ResourceRule is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.",
	"verbs":         "Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy.  \"*\" means all.",
	"apiGroups":     "APIGroups is the name of the APIGroup that contains the resources.  If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed.  \"*\" means all.",
	"resources":     "Resources is a list of resources this rule applies to.  ResourceAll represents all resources.  \"*\" means all.",
	"resourceNames": "ResourceNames is an optional white list of names that the rule applies to.  An empty set means that everything is allowed.  \"*\" means all.",
}

func (ResourceRule) SwaggerDoc() map[string]string {
	return map_ResourceRule
}

var map_SelfSubjectAccessReview = map[string]string{
	"":       "SelfSubjectAccessReview checks whether or the current user can perform an action.  Not filling in a spec.namespace means \"in all namespaces\".  Self is a special case, because users should always be able to check whether they can perform an action",
	"spec":   "Spec holds information about the request being evaluated.  user and groups must be empty",
	"status": "Status is filled in by the server and indicates whether the request is allowed or not",
}

func (SelfSubjectAccessReview) SwaggerDoc() map[string]string {
	return map_SelfSubjectAccessReview
}

var map_SelfSubjectAccessReviewSpec = map[string]string{
	"":                      "SelfSubjectAccessReviewSpec is a description of the access request.  Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set",
	"resourceAttributes":    "ResourceAuthorizationAttributes describes information for a resource access request",
	"nonResourceAttributes": "NonResourceAttributes describes information for a non-resource access request",
}

func (SelfSubjectAccessReviewSpec) SwaggerDoc() map[string]string {
	return map_SelfSubjectAccessReviewSpec
}

var map_SelfSubjectRulesReview = map[string]string{
	"":       "SelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace. The returned list of actions may be incomplete depending on the server's authorization mode, and any errors experienced during the evaluation. SelfSubjectRulesReview should be used by UIs to show/hide actions, or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server.",
	"spec":   "Spec holds information about the request being evaluated.",
	"status": "Status is filled in by the server and indicates the set of actions a user can perform.",
}

func (SelfSubjectRulesReview) SwaggerDoc() map[string]string {
	return map_SelfSubjectRulesReview
}

var map_SelfSubjectRulesReviewSpec = map[string]string{
	"namespace": "Namespace to evaluate rules for. Required.",
}

func (SelfSubjectRulesReviewSpec) SwaggerDoc() map[string]string {
	return map_SelfSubjectRulesReviewSpec
}

var map_SubjectAccessReview = map[string]string{
	"":       "SubjectAccessReview checks whether or not a user or group can perform an action.",
	"spec":   "Spec holds information about the request being evaluated",
	"status": "Status is filled in by the server and indicates whether the request is allowed or not",
}

func (SubjectAccessReview) SwaggerDoc() map[string]string {
	return map_SubjectAccessReview
}

var map_SubjectAccessReviewSpec = map[string]string{
	"":                      "SubjectAccessReviewSpec is a description of the access request.  Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set",
	"resourceAttributes":    "ResourceAuthorizationAttributes describes information for a resource access request",
	"nonResourceAttributes": "NonResourceAttributes describes information for a non-resource access request",
	"user":                  "User is the user you're testing for. If you specify \"User\" but not \"Group\", then is it interpreted as \"What if User were not a member of any groups",
	"group":                 "Groups is the groups you're testing for.",
	"extra":                 "Extra corresponds to the user.Info.GetExtra() method from the authenticator.  Since that is input to the authorizer it needs a reflection here.",
	"uid":                   "UID information about the requesting user.",
}

func (SubjectAccessReviewSpec) SwaggerDoc() map[string]string {
	return map_SubjectAccessReviewSpec
}

var map_SubjectAccessReviewStatus = map[string]string{
	"":                "SubjectAccessReviewStatus",
	"allowed":         "Allowed is required.  True if the action would be allowed, false otherwise.",
	"reason":          "Reason is optional.  It indicates why a request was allowed or denied.",
	"evaluationError": "EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request.",
}

func (SubjectAccessReviewStatus) SwaggerDoc() map[string]string {
	return map_SubjectAccessReviewStatus
}

var map_SubjectRulesReviewStatus = map[string]string{
	"":                 "SubjectRulesReviewStatus contains the result of a rules check. This check can be incomplete depending on the set of authorizers the server is configured with and any errors experienced during evaluation. Because authorization rules are additive, if a rule appears in a list it's safe to assume the subject has that permission, even if that list is incomplete.",
	"resourceRules":    "ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.",
	"nonResourceRules": "NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete.",
	"incomplete":       "Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation.",
	"evaluationError":  "EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete.",
}

func (SubjectRulesReviewStatus) SwaggerDoc() map[string]string {
	return map_SubjectRulesReviewStatus
}

// AUTO-GENERATED FUNCTIONS END HERE


text:
echo [chatrello package] Package target directory to publish in store.
zip chatrello-`git log -1 --format="%H"` target/*


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Node Affinity: the configuration of desired nodes onto which this Instance could be scheduled.
 *
 * Generated from protobuf message google.cloud.compute.v1.SchedulingNodeAffinity
 */
class SchedulingNodeAffinity extends \Google\Protobuf\Internal\Message
{
    /**
     * Corresponds to the label key of Node resource.
     *
     * Generated from protobuf field optional string key = 106079;
     */
    private $key = null;
    /**
     * Defines the operation of node selection. Valid operators are IN for affinity and NOT_IN for anti-affinity.
     * Check the Operator enum for the list of possible values.
     *
     * Generated from protobuf field optional string operator = 36317348;
     */
    private $operator = null;
    /**
     * Corresponds to the label values of Node resource.
     *
     * Generated from protobuf field repeated string values = 249928994;
     */
    private $values;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $key
     *           Corresponds to the label key of Node resource.
     *     @type string $operator
     *           Defines the operation of node selection. Valid operators are IN for affinity and NOT_IN for anti-affinity.
     *           Check the Operator enum for the list of possible values.
     *     @type string[]|\Google\Protobuf\Internal\RepeatedField $values
     *           Corresponds to the label values of Node resource.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Corresponds to the label key of Node resource.
     *
     * Generated from protobuf field optional string key = 106079;
     * @return string
     */
    public function getKey()
    {
        return isset($this->key) ? $this->key : '';
    }

    public function hasKey()
    {
        return isset($this->key);
    }

    public function clearKey()
    {
        unset($this->key);
    }

    /**
     * Corresponds to the label key of Node resource.
     *
     * Generated from protobuf field optional string key = 106079;
     * @param string $var
     * @return $this
     */
    public function setKey($var)
    {
        GPBUtil::checkString($var, True);
        $this->key = $var;

        return $this;
    }

    /**
     * Defines the operation of node selection. Valid operators are IN for affinity and NOT_IN for anti-affinity.
     * Check the Operator enum for the list of possible values.
     *
     * Generated from protobuf field optional string operator = 36317348;
     * @return string
     */
    public function getOperator()
    {
        return isset($this->operator) ? $this->operator : '';
    }

    public function hasOperator()
    {
        return isset($this->operator);
    }

    public function clearOperator()
    {
        unset($this->operator);
    }

    /**
     * Defines the operation of node selection. Valid operators are IN for affinity and NOT_IN for anti-affinity.
     * Check the Operator enum for the list of possible values.
     *
     * Generated from protobuf field optional string operator = 36317348;
     * @param string $var
     * @return $this
     */
    public function setOperator($var)
    {
        GPBUtil::checkString($var, True);
        $this->operator = $var;

        return $this;
    }

    /**
     * Corresponds to the label values of Node resource.
     *
     * Generated from protobuf field repeated string values = 249928994;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getValues()
    {
        return $this->values;
    }

    /**
     * Corresponds to the label values of Node resource.
     *
     * Generated from protobuf field repeated string values = 249928994;
     * @param string[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setValues($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
        $this->values = $arr;

        return $this;
    }

}


text:
"""
Restore a backup of one service
"""
import time
from enum import Enum
from typing import List, Optional

import typer

from controller import BACKUP_DIR, log, print_and_exit
from controller.app import Application
from controller.commands import RESTORE_MODULES
from controller.deploy.builds import verify_available_images
from controller.deploy.docker import Docker

# Enum() expects a string, tuple, list or dict literal as the second argument
# https://github.com/python/mypy/issues/5317
SupportedServices = Enum(  # type: ignore
    "SupportedServices", {name: name for name in sorted(RESTORE_MODULES.keys())}
)

# Also duplicated in backup.py. A wrapper is needed (to be also used in reload.py)
def reload(docker: Docker, services: List[str]) -> None:
    for service in services:
        containers = docker.get_containers(service)
        docker.exec_command(containers, user="root", command="/usr/local/bin/reload")

@Application.app.command(help="Restore a backup of one service")
def restore(
    service: SupportedServices = typer.Argument(..., help="Service name"),
    backup_file: Optional[str] = typer.Argument(
        None,
        help="Specify the backup to be restored",
        show_default=False,
    ),
    force: bool = typer.Option(
        False,
        "--force",
        help="Force the backup procedure",
        show_default=False,
    ),
    restart: List[str] = typer.Option(
        [],
        "--restart",
        help="Service to be restarted once completed the restore (multiple allowed)",
        shell_complete=Application.autocomplete_service,
    ),
) -> None:

    Application.print_command(
        Application.serialize_parameter("--force", force, IF=force),
        Application.serialize_parameter("--restart", restart, IF=restart),
        Application.serialize_parameter("", service.value),
        Application.serialize_parameter("", backup_file),
    )
    Application.get_controller().controller_init()

    service_name = service.value

    verify_available_images(
        [service_name],
        Application.data.compose_config,
        Application.data.base_services,
    )

    docker = Docker()

    container = docker.get_container(service_name)

    backup_dir = BACKUP_DIR.joinpath(service_name)
    if not backup_dir.exists():
        print_and_exit(
            "No backup found, the following folder does not exist: {}", backup_dir
        )

    module = RESTORE_MODULES.get(service.value)

    if not module:  # pragma: no cover
        print_and_exit(f"{service.value} misconfiguration, module not found")

    expected_ext = module.EXPECTED_EXT

    if backup_file is None:
        files = backup_dir.iterdir()

        filtered_files = [d.name for d in files if d.name.endswith(expected_ext)]
        filtered_files.sort()

        if not len(filtered_files):
            print_and_exit("No backup found, {} is empty", backup_dir)

        log.info("Please specify one of the following backup:")
        for f in filtered_files:
            print(f"- {f}")

        return

    backup_host_path = backup_dir.joinpath(backup_file)
    if not backup_host_path.exists():
        print_and_exit("Invalid backup file, {} does not exist", backup_host_path)

    module.restore(container=container, backup_file=backup_file, force=force)

    if restart:
        log.info("Restarting services in 20 seconds...")
        time.sleep(10)
        log.info("Restarting services in 10 seconds...")
        time.sleep(10)
        reload(docker, restart)


text:
function fresh = isfresh(outfile,prevfile)
% checks if prevfile is newer than outfile, if it is, returns true
fresh = false;
if exist(outfile,'file')
    prev_time = get_timestamp(prevfile);
    out_time = get_timestamp(outfile);
    if prev_time > out_time
        fresh = true;
    end
end
end


text:
package fitsio

import (
	"fmt"
	"math/big"
	"reflect"
	"strconv"
)

// Header describes a Header-Data Unit of a FITS file
type Header struct {
	htype  HDUType // type of the HDU
	bitpix int     // character information
	axes   []int   // dimensions of image data array
	cards  []Card  // content of the Header
}

// newHeader creates a new Header.
// no test on the content of the cards is performed.
func newHeader(cards []Card, htype HDUType, bitpix int, axes []int) *Header {
	hdr := &Header{
		htype:  htype,
		bitpix: bitpix,
		axes:   make([]int, len(axes)),
		cards:  make([]Card, 0, len(cards)),
	}
	copy(hdr.axes, axes)
	err := hdr.Append(cards...)
	if err != nil {
		panic(err)
	}
	return hdr
}

// NewHeader creates a new Header from a set of Cards, HDU Type, bitpix and axes.
func NewHeader(cards []Card, htype HDUType, bitpix int, axes []int) *Header {
	// short circuit: too many axes violates the FITS standard
	if len(axes) > 999 {
		panic(fmt.Errorf("fitsio: too many axes (got=%d > 999)", len(axes)))
	}
	hdr := newHeader(cards, htype, bitpix, axes)

	// add (some) mandatory cards (BITPIX, NAXES, AXIS1, AXIS2)
	keys := make(map[string]struct{}, len(cards))
	for i := range hdr.cards {
		card := &hdr.cards[i]
		k := card.Name
		keys[k] = struct{}{}
	}

	dcards := make([]Card, 0, 3)
	if _, ok := keys["BITPIX"]; !ok {
		dcards = append(dcards, Card{
			Name:    "BITPIX",
			Value:   hdr.Bitpix(),
			Comment: "number of bits per data pixel",
		})
	}

	if _, ok := keys["NAXIS"]; !ok {
		dcards = append(dcards, Card{
			Name:    "NAXIS",
			Value:   len(hdr.Axes()),
			Comment: "number of data axes",
		})
		nax := len(hdr.Axes())
		for i := 0; i < nax; i++ {
			axis := strconv.Itoa(i + 1) // index from 0, hdu starts at NAXIS1
			key := "NAXIS" + axis
			if _, ok := keys[key]; !ok {
				dcards = append(dcards, Card{
					Name:    key,
					Value:   hdr.Axes()[i],
					Comment: "length of data axis " + axis,
				})
			}
		}
	}

	err := hdr.prepend(dcards...)
	if err != nil {
		panic(err)
	}
	return hdr
}

// NewDefaultHeader creates a Header with CFITSIO default Cards, of type IMAGE_HDU and
// bitpix=8, no axes.
func NewDefaultHeader() *Header {
	return NewHeader(
		[]Card{
			{
				Name:    "SIMPLE",
				Value:   true,
				Comment: "file does conform to FITS standard",
			},
			{
				Name:    "BITPIX",
				Value:   8,
				Comment: "number of bits per data pixel",
			},
			{
				Name:    "NAXIS",
				Value:   0,
				Comment: "number of data axes",
			},
			{
				Name:    "NAXIS1",
				Value:   0,
				Comment: "length of data axis 1",
			},
			{
				Name:    "NAXIS2",
				Value:   0,
				Comment: "length of data axis 2",
			},
		},
		IMAGE_HDU,
		8,
		[]int{},
	)
}

// Type returns the Type of this Header
func (hdr *Header) Type() HDUType {
	return hdr.htype
}

// Text returns the header's cards content as 80-byte lines
func (hdr *Header) Text() string {
	const kLINE = 80
	buf := make([]byte, 0, kLINE*len(hdr.cards))
	for i := range hdr.cards {
		card := &hdr.cards[i]
		line, err := makeHeaderLine(card)
		if err != nil {
			panic(fmt.Errorf("fitsio: %v", err))
		}
		buf = append(buf, line...)
	}
	return string(buf)
}

// Append appends a set of Cards to this Header
func (hdr *Header) Append(cards ...Card) error {
	var err error
	keys := make(map[string]struct{}, len(hdr.cards))
	for i := range hdr.cards {
		card := &hdr.cards[i]
		k := card.Name
		keys[k] = struct{}{}
	}

	for _, card := range cards {
		_, dup := keys[card.Name]
		if dup {
			switch card.Name {
			case "COMMENT", "HISTORY", "":
				hdr.cards = append(hdr.cards, card)
				continue
			case "END":
				continue
			default:
				return fmt.Errorf("fitsio: duplicate Card [%s] (value=%v)", card.Name, card.Value)
			}
		}
		rv := reflect.ValueOf(card.Value)
		if rv.IsValid() {
			switch rv.Type().Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				card.Value = int(rv.Int())
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				card.Value = int(rv.Uint())
			case reflect.Float32, reflect.Float64:
				card.Value = rv.Float()
			case reflect.Complex64, reflect.Complex128:
				card.Value = rv.Complex()
			case reflect.String:
				card.Value = card.Value.(string)
			case reflect.Bool:
				card.Value = card.Value.(bool)
			case reflect.Struct:
				switch card.Value.(type) {
				case big.Int:
					// ok
				default:
					return fmt.Errorf(
						"fitsio: invalid value type (%T) for card [%s] (kind=%v)",
						card.Value, card.Name, rv.Type().Kind(),
					)
				}
			default:
				return fmt.Errorf(
					"fitsio: invalid value type (%T) for card [%s] (kind=%v)",
					card.Value, card.Name, rv.Type().Kind(),
				)
			}
		}
		hdr.cards = append(hdr.cards, card)
	}
	return err
}

// prepend prepends a (set of) cards to this Header
func (hdr *Header) prepend(cards ...Card) error {
	var err error
	keys := make(map[string]struct{}, len(hdr.cards))
	for i := range hdr.cards {
		card := &hdr.cards[i]
		k := card.Name
		keys[k] = struct{}{}
	}

	hcards := make([]Card, 0, len(cards))
	for _, card := range cards {
		_, dup := keys[card.Name]
		if dup {
			switch card.Name {
			case "COMMENT", "HISTORY", "":
				hdr.cards = append(hdr.cards, card)
				continue
			case "END":
				continue
			default:
				return fmt.Errorf("fitsio: duplicate Card [%s] (value=%v)", card.Name, card.Value)
			}
		}
		rv := reflect.ValueOf(card.Value)
		if rv.IsValid() {
			switch rv.Type().Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				card.Value = int(rv.Int())
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				card.Value = int(rv.Uint())
			case reflect.Float32, reflect.Float64:
				card.Value = rv.Float()
			case reflect.Complex64, reflect.Complex128:
				card.Value = rv.Complex()
			case reflect.String:
				card.Value = card.Value.(string)
			case reflect.Bool:
				card.Value = card.Value.(bool)
			default:
				return fmt.Errorf(
					"fitsio: invalid value type (%T) for card [%s]",
					card.Value, card.Name,
				)
			}
		}
		hcards = append(hcards, card)
	}

	hdr.cards = append(hcards, hdr.cards...)
	return err
}

// Clear resets the Header to the default state.
func (hdr *Header) Clear() {
	hdr.cards = make([]Card, 0)
	hdr.bitpix = 0
	hdr.axes = make([]int, 0)
}

// get returns the Card (and its index) with name n if it exists.
func (hdr *Header) get(n string) (int, *Card) {
	for i := range hdr.cards {
		c := &hdr.cards[i]
		if n == c.Name {
			return i, c
		}
	}
	return -1, nil
}

// Get returns the Card with name n or nil if it doesn't exist.
// If multiple cards with the same name exist, the first one is returned.
func (hdr *Header) Get(n string) *Card {
	_, card := hdr.get(n)
	return card
}

// Card returns the i-th card.
// Card panics if the index is out of range.
func (hdr *Header) Card(i int) *Card {
	return &hdr.cards[i]
}

// Comment returns the whole comment string for this Header.
func (hdr *Header) Comment() string {
	card := hdr.Get("COMMENT")
	if card != nil {
		return card.Value.(string)
	}
	return ""
}

// History returns the whole history string for this Header.
func (hdr *Header) History() string {
	card := hdr.Get("HISTORY")
	if card != nil {
		return card.Value.(string)
	}
	return ""
}

// Bitpix returns the bitpix value.
func (hdr *Header) Bitpix() int {
	return hdr.bitpix
}

// Axes returns the axes for this Header.
func (hdr *Header) Axes() []int {
	return hdr.axes
}

// Index returns the index of the Card with name n, or -1 if it doesn't exist
func (hdr *Header) Index(n string) int {
	idx, _ := hdr.get(n)
	return idx
}

// Keys returns the name of all the Cards of this Header.
func (hdr *Header) Keys() []string {
	keys := make([]string, 0, len(hdr.cards))
	for i := range hdr.cards {
		key := hdr.cards[i].Name
		switch key {
		case "END", "COMMENT", "HISTORY", "":
			continue
		default:
			keys = append(keys, key)
		}
	}
	return keys
}

// Set modifies the value and comment of a Card with name n.
func (hdr *Header) Set(n string, v interface{}, comment string) {
	card := hdr.Get(n)
	if card == nil {
		hdr.Append(Card{
			Name:    n,
			Value:   v,
			Comment: comment,
		})
	} else {
		card.Value = v
		card.Comment = comment
	}
}


text:
#!/bin/sh
FILES=(
	./test_transforms/**/*.js
	./index.js
)
TRANSFORMS=(
	./test_transforms/objectify.js
	./test_transforms/tabTo2Spaces.js
	./test_transforms/trimSpacesBeforeNewLine.js
	./test_transforms/ensureFilesEndInNewLine.js
)
AFTER_ALL=(
	./test_transforms/applyChanges.js
)
./reshape -p $FILES -e $TRANSFORMS -aa $AFTER_ALL


text:
package reporters

import (
	"github.com/onsi/ginkgo/config"
	"github.com/onsi/ginkgo/types"
)

type Reporter interface {
	SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary)
	BeforeSuiteDidRun(setupSummary *types.SetupSummary)
	SpecWillRun(specSummary *types.SpecSummary)
	SpecDidComplete(specSummary *types.SpecSummary)
	AfterSuiteDidRun(setupSummary *types.SetupSummary)
	SpecSuiteDidEnd(summary *types.SuiteSummary)
}


text:
"use strict";

var options = require("./options");

module.exports = {
  show: function() {
    console.log(options.generateHelp());
  }
};


text:
import {WobserverApiFallback} from './wobserver_api_fallback';

class WobserverClient {
  constructor(host) {
    this.host = host;
    this.socket = null;
    this.node = 'local';
    this.promises = {}
    this.state = 0;
    this.url = (location.protocol == 'https:' ? 'wss' : 'ws') + '://' + this.host + '/ws'
  }

  connect(node_change, fallback_callback, connected_callback) {
    this.node_change = node_change;

    this.socket = new WebSocket(this.url);

    this.socket.onerror = (error) => {
      if( this.socket.readyState == 3 ){
        if( this.state == 0 ){
          console.log('Socket can not connect, falling back to json api.')
          fallback_callback(new WobserverApiFallback(this.host, this.node));
          connected_callback();
        }
      }
    }

    this.socket.onopen = () => {
      this.state = 1;

      connected_callback();

      this.command('hello');
      setInterval(_ => this.command('ping'), 55 * 1000 ); // Every 55 seconds
    }

    this.add_handlers();
  }

  disconnected() {
    if( this.state == 1 ){
      this.state = -1;

      this.reconnect();
    }

    if( this.on_disconnect ){
      this.on_disconnect();
    }
  }

  reconnect() {
    let new_socket = new WebSocket(this.url);

    new_socket.onerror = (error) => {
      if( this.socket.readyState == 3 ){
        console.log('Reconnect failed, trying again in 5 seconds.')
        setTimeout(_ => this.reconnect(), 5000);
      }
    }

    new_socket.onopen = () => {
      this.socket = new_socket;
      this.state = 1;

      this.add_handlers();

      this.command('hello');

      if( this.on_reconnect ){
        this.on_reconnect();
      }
    }
  }

  add_handlers() {
    this.socket.onmessage = (msg) => {
      let data = JSON.parse(msg.data);

      if( data.type == 'ehlo' ) {
        this.node = data.data.name;
        this.node_change(this.node);
      } else if( data.type == 'setup_proxy' && data.data.node) {
        this.node = data.data.node;
        this.node_change(this.node);
      } else {
        if( this.promises[data.type] ){
          let promise = this.promises[data.type].pop();
          if( promise ) {
            promise(data);
          }
        }
      }
    }
  }

  command(command, data = null) {
    if( this.socket.readyState == 3 ){
      this.disconnected();

      return;
    }

    let payload = JSON.stringify({
      command: command,
      data: data
    })

    this.socket.send(payload);
  }

  command_promise(command, data = null) {
    if( this.socket.readyState == 3 ){
      this.disconnected();

      return new Promise((s) => {});
    }

    return new Promise((resolve) => {
      if( this.promises[command] ){
        this.promises[command].push(resolve);
      } else {
        this.promises[command] = [resolve];
      }

      this.command(command, data);
    });
  }

  set_node(node) {
    if( this.node != node ) {
      this.command('setup_proxy', node)
    }
  }
}

export{ WobserverClient }


text:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import PlPage from './containers/PlPage/';
import NewPlPage from './containers/NewPlPage';
import App from './containers/App';
import HomePage from './containers/HomePage';
import NotFoundPage from './containers/NotFoundPage';
const routes = (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage}/>
    <Route path="/playlist/:PlId" component={PlPage} />
    <Route path="/new" component={NewPlPage} />

    <Route path="*" component={NotFoundPage}/>
  </Route>
);
export default routes;


text:
{{ parent.name }}

{{ transcriptArea.ace.currentTag.name }}

                         Mode plein écran
                         Quitter le plein écran
                         Quitter la transcription


text:
'use strict';

module.exports = {
    attributes: require('./attributes'),
    supplyDefaults: require('./defaults'),
    colorbar: require('../scatter/marker_colorbar'),
    formatLabels: require('./format_labels'),
    calc: require('../scattergeo/calc'),
    plot: require('./plot'),
    hoverPoints: require('./hover'),
    eventData: require('./event_data'),
    selectPoints: require('./select'),

    styleOnSelect: function(_, cd) {
        if(cd) {
            var trace = cd[0].trace;
            trace._glTrace.update(cd);
        }
    },

    moduleType: 'trace',
    name: 'scattermapbox',
    basePlotModule: require('../../plots/mapbox'),
    categories: ['mapbox', 'gl', 'symbols', 'showLegend', 'scatter-like'],
    meta: {
        hrName: 'scatter_mapbox',
        description: [
            'The data visualized as scatter point, lines or marker symbols',
            'on a Mapbox GL geographic map',
            'is provided by longitude/latitude pairs in `lon` and `lat`.'
        ].join(' ')
    }
};


text:
<!DOCTYPE html>
<meta name="author" title="Xiaocheng Hu" href="mailto:xiaochengh@chromium.org">
<meta name="assert" content="The same constructor can be registered to multiple registries">
<link rel="help" href="https://wicg.github.io/webcomponents/proposals/Scoped-Custom-Element-Registries">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
class MyCustom extends HTMLElement {};

test(() => {
  let registry1 = new CustomElementRegistry();
  let registry2 = new CustomElementRegistry();
  window.customElements.define('my-custom', MyCustom);
  registry1.define('my-custom', MyCustom);
  registry2.define('my-custom', MyCustom);

  assert_equals(window.customElements.get('my-custom'), MyCustom);
  assert_equals(registry1.get('my-custom'), MyCustom);
  assert_equals(registry2.get('my-custom'), MyCustom);
}, 'Same constructor can be registered to different registries');

test(() => {
  let registry = new CustomElementRegistry();
  registry.define('custom-a', MyCustom);
  assert_throws_dom('NotSupportedError', () => registry.define('custom-b', MyCustom));
}, 'Non-global registries still reject duplicate registrations of the same constructor');
</script>


text:
set -e -o pipefail

cd "$CURR_DIR"/describe-project

temp_file=`mktemp`

function cleanup {
    rm $temp_file
}

trap cleanup EXIT

if ! $DUB describe --compiler=$COMPILER > "$temp_file"; then
    die 'Printing describe JSON failed!'
fi


text:
mysql = require('../lib/mysql-native');

module.exports.createConnection = function()
{
    var db = mysql.createTCPClient();
    //db.verbose = true;
    db.set('auto_prepare', true)
      .set('row_as_hash', false)
      .auth('test', 'tester', 'testpass');
    return db;
}


text:
<Type Name="EllipsizeLabel" FullName="Banshee.Widgets.EllipsizeLabel">
  <TypeSignature Language="C#" Value="public class EllipsizeLabel : Gtk.Label" />
  <AssemblyInfo>
    <AssemblyName>Banshee.Widgets</AssemblyName>
    <AssemblyVersion>0.90.1.25405</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Gtk.Label</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public EllipsizeLabel ();" />
      <MemberType>Constructor</MemberType>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public EllipsizeLabel (string label);" />
      <MemberType>Constructor</MemberType>
      <Parameters>
        <Parameter Name="label" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="label">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
<?php

abstract class opBaseSendMailTask extends sfDoctrineBaseTask
{
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', null),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'prod'),
    ));
  }

  public function initialize(sfEventDispatcher $dispatcher, sfFormatter $formatter)
  {
    parent::initialize($dispatcher, $formatter);

    // This is just a hack to make OpenPNE generate a valid url in some helper function
    $_SERVER['SCRIPT_NAME'] = '/index.php';
  }

  protected function execute($arguments = array(), $options = array())
  {
    $this->openDatabaseConnection();

    // opMailSend requires Zend
    opApplicationConfiguration::registerZend();

    opDoctrineRecord::setDefaultCulture(sfConfig::get('default_culture', 'ja_JP'));
  }

  protected function openDatabaseConnection()
  {
    new sfDatabaseManager($this->configuration);
  }

  protected function getContextByEmailAddress($address)
  {
    $application = 'pc_frontend';
    if (opToolkit::isMobileEmailAddress($address))
    {
      $application = 'mobile_frontend';
    }

    if (!sfContext::hasInstance($application))
    {
      $context = sfContext::createInstance($this->createConfiguration($application, 'prod'), $application);
    }
    else
    {
      $context = sfContext::getInstance($application);
    }

    return $context;
  }
}


text:
/* global JSSluz */

;
(function (window, document, dependencies) {
  if (typeof window.JSSluz !== 'undefined') {
    return;
  }

  window.JSSluz = {
    name: 'JSSluz',
    version: '1.0.0',
    event: document.createElement('div')
  };

  window.addEventListener("load", function (event) {
    var root = null;
    var regex = new RegExp('JSSluz/main\.js');
    var scripts = document.getElementsByTagName('script');
    var length = scripts.length;
    for (var i = 0; i < length; ++i) {
      var src = scripts[i].getAttribute('src');
      if (regex.test(src)) {
        root = scripts[i].getAttribute('root-site');
        break;
      }
    }

    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', root + 'JSSluz/data/dependencies.js');
    script.setAttribute('async', true);

    script.onerror = function (evt) {
      throw new Error('Script from "JSSluz/data/dependencies.js" cannot be loaded.');
    };

    script.onload = script.onreadystatechange = function (evt) {
      if (root == null) {
        root = "";
      }

      var loader = new JSSluz.Dependencies([
        root + 'JSSluz/data/http.js',
        root + 'JSSluz/data/data.js',
        root + 'JSSluz/data/json.js',
        root + 'JSSluz/data/xml.js',
        root + 'JSSluz/util/geolocation.js',
        root + 'JSSluz/util/helper.js',
        root + 'JSSluz/view/controller.js',
        root + 'JSSluz/view/event.js'
      ]);
      loader.loadDependencies();
    };

    var element = document.body || document.head;
    element.appendChild(script);
  });
})(window, document);


text:
package com.mercadopago.android.px.model;

public class Interaction {

    private InstructionAction action;
    private String title;
    private String content;

    public InstructionAction getAction() {
        return action;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('pharmacy', '0001_initial'),
        ('items', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='sells',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('quantity', models.IntegerField()),
                ('price_per_item', models.FloatField()),
                ('item_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='items.item')),
                ('pharmacy_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pharmacy.pharmacy')),
            ],
        ),
    ]


text:
r"""
Runs shock-bubble interaction problem with SSPLMMs to generate solution data.
Checks if PETSC is installed in order to run in parallel.
"""

def create_data(problems,methods,cfl_nums,lim_type):
    import pickle
    import ssp_lmm_vss
    try:
        import pkgutil
        pkgutil.find_loader("clawpack.petclaw")
        use_petsc = True
    except ImportError:
        use_petsc = False
        print 'Unable to import petclaw, is PETSC/petsc4py installed?'
        raise

    for problem in problems:
        paramtrs = ssp_lmm_vss.default_parameters(problem)
        paramtrs.num_output_times = 1
        paramtrs.max_steps = 200000
        paramtrs.use_petsc = use_petsc
        paramtrs.N = [640,160]

        for method in methods:
            data = ssp_lmm_vss.run(problem,N=paramtrs.N,method=method,cfl_nums=cfl_nums[method],\
                    lim_type=lim_type[method],limiter=4,paramtrs=paramtrs,iplot=False)
            if data is not None:
                solution_data = {}
                solution_data[method] = data
                output = open('data/'+problem+'_'+method+'.pkl', "wb")
                pickle.dump(solution_data, output, -1)
                output.close()

if __name__=="__main__":
    methods=['SSPLMM32','SSPLMM43']
    cfl_nums = {'SSPLMM32': [0.24,0.25],'SSPLMM43': [0.15,1/6.]}
    lim_type = {'SSPLMM32': 1,'SSPLMM43': 2}

    problems=['shock_bubble_interaction_2d']
    create_data(problems,methods,cfl_nums,lim_type)


text:
package org.red5.codec;

/**
 * Video codecs that Red5 supports.
 *
 * @author Art Clarke
 * @author Paul Gregoire (mondain@gmail.com)
 */
public enum VideoCodec {

	JPEG((byte) 0x01), H263((byte) 0x02), SCREEN_VIDEO((byte) 0x03), VP6((byte) 0x04),
	VP6a((byte) 0x05), SCREEN_VIDEO2((byte) 0x06), AVC((byte) 0x07);

	private byte id;

	private VideoCodec(byte id) {
		this.id = id;
	}

	/**
	 * Returns back a numeric id for this codec,
	 * that happens to correspond to the numeric
	 * identifier that FLV will use for this codec.
	 *
	 * @return the codec id
	 */
	public byte getId() {
		return id;
	}

}


text:
<?php

namespace Xsolve\SalesforceClient\Storage;

use PHPUnit\Framework\TestCase;

class RequestTokenStorageTest extends TestCase
{
    /**
     * @var RequestTokenStorage
     */
    private $storage;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->storage = new RequestTokenStorage();
    }

    public function testTheFlow()
    {
        $token = new DummyToken();
        $this->assertFalse($this->storage->has());
        $this->storage->save($token);
        $this->assertTrue($this->storage->has());
        $this->assertSame($token, $this->storage->get());
    }

    /**
     * @expectedException \LogicException
     */
    public function testGetNoEntry()
    {
        $this->storage->get();
    }
}


text:
namespace Rees.UserInteraction.Contracts
{
    /// <summary>
    ///     Shows an input box to get one string of text from the user.
    /// </summary>
    public interface IUserInputBox
    {
        /// <summary>
        ///     Show an input box with a heading and a question.
        /// </summary>
        /// <param name="heading">The window title</param>
        /// <param name="question">The main question text</param>
        /// <param name="defaultInput">An optional default value for the input box</param>
        /// <returns>User response to the question, or null if the user cancelled.  The user cannot return null if 'Ok' is clicked.</returns>
        string Show(string heading, string question, string defaultInput = "");
    }
}


text:
<?php

namespace PboApi\Models;

use PboApi\Support\AbstractResource;
use PboApi\Support\ResourceInterface;
use PboApi\Support\ResourceMetaTrait;

class Machine extends AbstractResource implements ResourceInterface {

    use ResourceMetaTrait;

    protected $resource = 'machines';

}


text:
struct WebAppInstallInfo;

class CroshSystemAppDelegate : public ash::SystemWebAppDelegate {
 public:
  explicit CroshSystemAppDelegate(Profile* profile);

  // ash::SystemWebAppDelegate overrides:
  std::unique_ptr<WebAppInstallInfo> GetWebAppInfo() const override;
  bool ShouldShowInLauncher() const override;
  bool ShouldReuseExistingWindow() const override;
  bool ShouldShowInSearch() const override;
  bool ShouldHaveTabStrip() const override;
};

// Returns a WebAppInstallInfo used to install the app.
std::unique_ptr<WebAppInstallInfo> CreateWebAppInfoForCroshSystemWebApp();

#endif  // CHROME_BROWSER_ASH_WEB_APPLICATIONS_CROSH_SYSTEM_WEB_APP_INFO_H_


text:
#region Copyright

#endregion

/// -----------------------------------------------------------------------------------------------------------
/// Module      :  ScheduleAdapterBindingCollectionElement.cs
/// Description :  Binding Collection Element class which implements the StandardBindingCollectionElement
/// -----------------------------------------------------------------------------------------------------------

#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Configuration;

using Microsoft.ServiceModel.Channels.Common;
#endregion

namespace Reply.Cluster.Mercury.Adapters.Schedule
{
    /// <summary>
    /// Initializes a new instance of the ScheduleAdapterBindingCollectionElement class
    /// </summary>
    public class ScheduleAdapterBindingCollectionElement : StandardBindingCollectionElement<ScheduleAdapterBinding,
        ScheduleAdapterBindingElement>
    {
    }
}


text:
namespace IIEP
{
  /// @brief ÎļþÊäÈë½Ó¿ÚÀà

  class CFileIn
  {
    public:

    CFileIn(void);
    ~CFileIn(void);

    bool Open(const char *pcszFileName);
    bool Open(const WORD *pcwsFileName);

    void Close(void);

    DWORD GetFileSize(void) const;
    DWORD GetReadPosition(void) const;

    bool Seek(long nOffset, long nOrigin = 0);  // SEEK_SET = 0     SEEK_CUR = 1     SEEK_END = 2

    bool Skip(long nOffset) { return Seek(nOffset, 1); }

    DWORD Read(PVOID pDataBuffer, DWORD dwReadSize);

    bool ReadB(BYTE &ucData)
    {
      return (1 == Read(&ucData, 1));
    }

    bool ReadW(WORD &wData)
    {
      return (2 == Read(&wData, 2));
    }

    bool ReadDW(DWORD &dwData)
    {
      return (4 == Read(&dwData, 4));
    }

    bool ReadInverseW(WORD &wData)
    {
      if (2 == Read(&wData, 2))
      {
        _asm
        {
          MOV       ECX, wData
          MOV       AX, [ECX]
          XCHG      AH, AL
          MOV       [ECX], AX
        }

        return true;
      }

      return false;
    }

    bool ReadInverseDW(DWORD &dwData)
    {
      if (4 == Read(&dwData, 4))
      {
        _asm
        {
          MOV       ECX, dwData
          MOV       EAX, [ECX]
          BSWAP     EAX
          MOV       [ECX], EAX
        }

        return true;
      }

      return false;
    }

    // --------------------------------------------------------------------------------------------

    bool ReadAnsiLine(std::string &strLine);
    bool ReadUnicodeLine(std::wstring &wstrLine, bool bBigEndian);

    bool ReadAnsiString   (char *pszBuffer, DWORD dwBufferLength);
    bool ReadUnicodeString(WORD *pwzBuffer, DWORD dwBufferLength);

    // --------------------------------------------------------------------------------------------

    private:

    CFileIn(const CFileIn &);				        // forbidden
    CFileIn & operator = (const CFileIn &);	// forbidden

    #include <CORE/CORE_FileIn.H>
  };
}

// ______ CFileIn _________________________________________________________________________________
//
//      _______________
// ____/  Memory File  \___________________________________________________________________________

namespace IIEP
{
  bool CreateMemoryFile(PVOID pMemory, DWORD dwLength, const char *pcszFileName);
  bool CreateMemoryFile(PVOID pMemory, DWORD dwLength, const WORD *pcwsFileName);
  bool RemoveMemoryFile(const char *pcszFileName);
  bool RemoveMemoryFile(const WORD *pcwsFileName);
  void RemoveMemoryFile(void);
}

// ______ Memory File _____________________________________________________________________________
//
// ____________________________________________ DEFINE ____________________________________________
//
// ____________________________________________________________________________________ DATA ______
//
// ___________________________________________ FILE END ___________________________________________


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactIconBase = require('react-icon-base');

var _reactIconBase2 = _interopRequireDefault(_reactIconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var IoStop = function IoStop(props) {
    return _react2.default.createElement(
        _reactIconBase2.default,
        _extends({ viewBox: '0 0 40 40' }, props),
        _react2.default.createElement(
            'g',
            null,
            _react2.default.createElement('path', { d: 'm34.1 5c0.5 0 0.9 0.4 0.9 0.9v28.2c0 0.5-0.4 0.9-0.9 0.9h-28.2c-0.5 0-0.9-0.4-0.9-0.9v-28.2c0-0.5 0.4-0.9 0.9-0.9h28.2z' })
        )
    );
};

exports.default = IoStop;
module.exports = exports['default'];


text:
var SocketPlugin = function() {};

SocketPlugin.prototype.echo = function(msg) {
	var error = function(args) {
		alert('FEHLER');
		console.log(args);
	};

	var res = cordova.exec(console.log, error, "SocketPlugin", "echo", [msg]);

	console.log("RES", res);
};

window.plugins = window.plugins || {};
window.plugins.socketPlugin = window.plugins.socketPlugin || new SocketPlugin();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phomopsis thalictri H.C. Greene

### Remarks
null


text:
package org.scaladebugger.api.lowlevel.events

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSpec, Matchers, ParallelTestExecution}
import org.scaladebugger.api.lowlevel.events.EventManager.EventHandler
import org.scaladebugger.api.lowlevel.events.EventType.EventType
import org.scaladebugger.test.helpers.ParallelMockFunSpec

class DummyEventManagerSpec extends ParallelMockFunSpec
{
  private val TestHandlerId = java.util.UUID.randomUUID().toString
  private val eventManager = new DummyEventManager

  describe("DummyEventManager") {
    describe("#addEventHandlerWithId") {
      it("should return the provided id") {
        val expected = TestHandlerId

        val actual = eventManager.addEventHandlerWithId(
          expected,
          mock[EventType],
          mock[EventHandler]
        )

        actual should be (expected)
      }
    }

    describe("#getHandlersForEventType") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getHandlersForEventType(mock[EventType])

        actual should be (expected)
      }
    }

    describe("#getHandlerIdsForEventType") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getHandlerIdsForEventType(mock[EventType])

        actual should be (expected)
      }
    }

    describe("#getEventHandler") {
      it("should return None") {
        val expected = None

        val actual = eventManager.getEventHandler(TestHandlerId)

        actual should be (expected)
      }
    }

    describe("#getAllEventHandlerInfo") {
      it("should return an empty list") {
        val expected = Nil

        val actual = eventManager.getAllEventHandlerInfo

        actual should be (expected)
      }
    }

    describe("#removeEventHandler") {
      it("should return None") {
        val expected = None

        val actual = eventManager.removeEventHandler(TestHandlerId)

        actual should be (expected)
      }
    }

    describe("#start") {
      it("should do nothing") {
        eventManager.start()
      }
    }

    describe("#stop") {
      it("should do nothing") {
        eventManager.stop()
      }
    }
  }
}