text:
layout: post
date: '2015-09-26'
title: "Halter Allure Bridals Long Chiffon Bridesmaids Dress 1364"
category: Halter
tags: [Halter]
---
### Halter Allure Bridals Long Chiffon Bridesmaids Dress 1364
Just **$217.99**
###

Buy it: [https://www.eudances.com/en/halter/1766-allure-bridals-long-chiffon-bridesmaids-dress-1364.html](https://www.eudances.com/en/halter/1766-allure-bridals-long-chiffon-bridesmaids-dress-1364.html)

redpajama_set_name: RedPajamaGithub


text:
import re

def get_email_domain_from_username(username):
    """
    A quick utility for getting an Email Domain from a username
    (the last part of the email after the '@' sign)
    :param username: String
    :return: Domain name string. `None` if there is no domain name (or username is otherwise invalid).
    """
    split_username = username.split('@')
    if len(split_username) != 2:
        # Not a real email address with an expected email domain.
        return
    if not re.match(r"^[a-z0-9!#$%&'*+=?^_'{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_'{|}~-]+)*$", split_username[0]):
        # not a real email address as the username contains invalid characters
        return
    return split_username[-1]


text:
//---------------------------------------------------------------------
// <copyright file="Error.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Service
{
    using System;

    /// <summary>
    /// Strongly-typed and parameterized exception factory.
    /// </summary>
    internal static partial class Error
    {
        /// <summary>
        /// create and trace a HttpHeaderFailure
        /// </summary>
        /// <param name="errorCode">error code</param>
        /// <param name="message">error message</param>
        /// <returns>DataServiceException</returns>
        internal static DataServiceException HttpHeaderFailure(int errorCode, string message)
        {
            return Trace(new DataServiceException(errorCode, message));
        }

        /// <summary>
        /// Trace the exception
        /// </summary>
        /// <typeparam name="T">type of the exception</typeparam>
        /// <param name="exception">exception object to trace</param>
        /// <returns>the exception parameter</returns>
        private static T Trace<T>(T exception) where T : Exception
        {
            return exception;
        }
    }
}


text:
package org.apache.tinkerpop.gremlin.hadoop.process.computer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.tinkerpop.gremlin.hadoop.Constants;
import org.apache.tinkerpop.gremlin.hadoop.structure.io.GraphFilterAware;
import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable;
import org.apache.tinkerpop.gremlin.hadoop.structure.util.ConfUtil;
import org.apache.tinkerpop.gremlin.process.computer.GraphFilter;
import org.apache.tinkerpop.gremlin.process.computer.util.VertexProgramHelper;
import org.apache.tinkerpop.gremlin.structure.util.star.StarGraph;

import java.io.IOException;
import java.util.Optional;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public final class GraphFilterRecordReader extends RecordReader<NullWritable, VertexWritable> {

    private GraphFilter graphFilter = null;
    private RecordReader<NullWritable, VertexWritable> recordReader;

    public GraphFilterRecordReader() {
    }

    @Override
    public void initialize(final InputSplit inputSplit, final TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
        final Configuration configuration = taskAttemptContext.getConfiguration();
        final InputFormat<NullWritable, VertexWritable> inputFormat = ReflectionUtils.newInstance(configuration.getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class, InputFormat.class), configuration);
        if (!(inputFormat instanceof GraphFilterAware) && configuration.get(Constants.GREMLIN_HADOOP_GRAPH_FILTER, null) != null)
            this.graphFilter = VertexProgramHelper.deserialize(ConfUtil.makeApacheConfiguration(configuration), Constants.GREMLIN_HADOOP_GRAPH_FILTER);
        this.recordReader = inputFormat.createRecordReader(inputSplit, taskAttemptContext);
        this.recordReader.initialize(inputSplit, taskAttemptContext);
    }

    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
        if (null == this.graphFilter) {
            return this.recordReader.nextKeyValue();
        } else {
            while (true) {
                if (this.recordReader.nextKeyValue()) {
                    final VertexWritable vertexWritable = this.recordReader.getCurrentValue();
                    final Optional<StarGraph.StarVertex> vertex = vertexWritable.get().applyGraphFilter(this.graphFilter);
                    if (vertex.isPresent()) {
                        vertexWritable.set(vertex.get());
                        return true;
                    }
                } else {
                    return false;
                }
            }
        }
    }

    @Override
    public NullWritable getCurrentKey() throws IOException, InterruptedException {
        return NullWritable.get();
    }

    @Override
    public VertexWritable getCurrentValue() throws IOException, InterruptedException {
        return this.recordReader.getCurrentValue();
    }

    @Override
    public float getProgress() throws IOException, InterruptedException {
        return this.recordReader.getProgress();
    }

    @Override
    public void close() throws IOException {
        this.recordReader.close();
    }
}


text:
name: On Windows
sort: 6
---

## Binary install Gogs on Windows 7

> Contributed by [@victorsegall](https://github.com/victorsegall)

### Prerequisites

Check the main [installation page](http://gogs.io/docs/installation/) to confirm before you go on. You need [git for Windows](http://git-scm.com/download/win).

An SSH server is not needed on your Windows machine, if this Gogs instance will be for you alone, or if you only need the HTTP(S) service that Gogs provides.

To run Gogs as a service, you will need one of:

* Iain Patterson's [nssm.exe](http://nssm.cc/)
* Nick Rozanski's [SRVSTART.EXE](http://rozanski.org.uk/software)
* Microsoft's [Srvany.exe](https://support.microsoft.com/kb/137890)

This guide covers nssm.exe, which is [open source](https://git.nssm.cc/?p=nssm.git) and [public domain](https://git.nssm.cc/?p=nssm.git;a=blob_plain;f=README.txt;hb=HEAD).

During setup, you will run Gogs as current local user, and then reconfigure to run as a service.

When configuring Gogs through app.ini and web UI, use UNIX directory separators (forward slash `/`) where possible. If you are needing to use a UNC path to a network share, try [the Cygwin way](https://cygwin.com/cygwin-ug-net/using.html#unc-paths), or [map the path as a local drive](http://www.sevenforums.com/tutorials/49517-map-network-drive.html).

### Run as current local user

Gogs is able to run as local user immediately, with no configuration. Simply unpack the [Windows binary](http://gogs.io/docs/installation/install_from_binary.html) zip file somewhere, go to command line, and do:

```
C:>cd C:\path\to\gogs

C:\path\to\gogs>gogs web
```

We'll assume you chose `C:\gogs`

At this point, Gogs should be available at `http://127.0.0.1:3000`, and the first-run installer will guide you through completing a basic and functional setup.

### First run

By default, Gogs will be using both `C:\Users\your_username` and `C:\gogs` for file operations.

In `C:\gogs`, Gogs will need write access to:

```
C:\gogs\custom\conf
C:\gogs\data
C:\gogs\log
```

Those are made during its first run, which assumes it then had write access to `C:\gogs`. Create them before first run if that is not true.

See [Configuration and Run](http://gogs.io/docs/installation/configuration_and_run.html) to learn about `C:\gogs\custom\conf\app.ini`. It will be written during first run.

Gogs will create `C:\Users\your_username\.gitconfig` with the following:

```
[user]
	name = Gogs
	email = gogitservice@gmail.com
```

That [can be changed to whatever you like](http://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup), and it should be. It is the user to which all of your git operations will be attributed to. It can also be overridden per-repository, through `C:\path\to\repo\.git\config`.

### Database

If you're using a remote database server, the [Ubuntu](http://gogs.io/docs/installation/install_gogs_on_ubuntu.html) and [Mac OS](http://gogs.io/docs/installation/install_gogs_on_mac.html) guides cover the SQL needed to create your tables.

For a local single-user Gogs instance, you may simply allow Gogs to create an SQLite database, by configuring nothing else before doing first run. The result of that in `C:\Gogs\custom\conf\app.ini` will look like this:

```
[database]
DB_TYPE = sqlite3
HOST = 127.0.0.1:3306
NAME = gogs
USER = root
PASSWD =
SSL_MODE = disable
PATH = data/gogs.db
```

This is where all Gogs data will be stored, but not git data. Git data (repository files, history, et. al.) lives outside of Gogs, on the file system, while Gogs provides a middleware layer for creating an issue queue, viewing the history, configuring the repository, etc.

Therefore, user authentication and authorization that you configure in Gogs will have no effect upon git operations done through the file system.

### Working locally

By default, Gogs managed repositories are in `C:\Users\your_username\gogs-repositories`

This is set in `C:\Gogs\custom\conf\app.ini` with:

```
[repository]
ROOT = C:/path/to/repositories
```

These will be bare repositories, with no working directory. You can clone them locally through the file system, with git.exe (which was required in [installation](http://gogs.io/docs/installation/), or with [TortoiseGit](https://code.google.com/p/tortoisegit/) if you prefer working through Windows Explorer.

On the command line, you might do:

```
C:>cd C:\Users\your_username\Documents\repos

C:\Users\your_username\Documents\repos>md repo_name

C:\Users\your_username\Documents\repos>cd repo_name

C:\Users\your_username\Documents\repos\repo_name>git.exe clone --progress -v "C:\Users\your_username\gogs-repositories\your_gogs_username\repo_name.git" "C:\Users\your_username\Documents\repos\repo_name"

Cloning into 'C:\Users\your_username\Documents\repos\repo_name'...

done.
```

When working locally, it's not necessary to pass git operations through the Gogs service. Gogs will update when you `git push` your working directory clone from `C:\Users\your_username\Documents\repos\repo_name` back to its origin at `C:\Users\your_username\gogs-repositories`. Do clone the repository when you need a working directory—even when flying solo. It allows you to very easily move Gogs and your origin repositories later, without that process touching your working directories.

### Run Gogs as a service

At this point, you may choose to lock down file and directory permissions. Just keep in mind the paths to which Gogs requires write access, which includes the Gogs repository `ROOT`.

The following changes are made in `C:\Gogs\custom\conf\app.ini`:

```
RUN_USER = COMPUTERNAME$
```

Sets Gogs to run as the local system user.

`COMPUTERNAME` is whatever the response is from `echo %COMPUTERNAME%` on the command line. If the response is `USER-PC` then `RUN_USER = USER-PC$`

```
[server]
DOMAIN = gogs
PROTOCOL = http
HTTP_ADDR = 127.0.1.1
HTTP_PORT = 80
OFFLINE_MODE = true
ROOT_URL = http://gogs/
```

Moves Gogs' listen port to 80 on the local interface subnet, and tells the Gogs HTTPd that its virtual host is the "gogs" domain. This lets you forgo including a port number when browsing, and prevents collision with other localhost services. The IP address can be anything in the range 127.0.0.2 - 127.254.254.254, so long as it's unique to Gogs.

To complete that network route, open Notepad.exe as administrator and include the following in `C:\Windows\System32\drivers\etc\hosts`:

```
# Go Git Service local HTTPd
127.0.1.1        gogs
```

The hosts file entry will guarantee that all requests to the "gogs" domain are captured by your localhost interface. In a web browser, generally, `gogs/` in the address bar is sufficient to trigger that route.

Get the [nssm.exe](http://nssm.cc/download) needed for your machine (32 or 64 bit; they're packaged together in Iain's zip file), and place it in a directory that is in (or will be added to) your %PATH% environment variable.

Open a command line as administrator and do `nssm install gogs` to configure Gogs as a service.

```
C:\>nssm install gogs
```

"NSSM service installer" will appear. Configure it as follows:

Application tab:

* Path: C:\gogs\gogs.exe
* Startup directory: C:\gogs
* Arguments: web

![](/docs/images/install_gogs_on_windows_nssm_1.png)

Details tab:

* Display name: Go Gits Service
* Description: Gogs (Go Git Service) is a painless self-hosted Git service written in Go.
* Startup type: Automatic (Delayed Start)

Note that we've chosen [delayed start](http://stackoverflow.com/a/11015576), so that the service will not impact the early boot time. Gogs will start two minutes after the non-delayed services.

![](/docs/images/install_gogs_on_windows_nssm_2.png)

I/O tab:

* Output (stdout): C:\gogs\log\gogs-nssm.txt
* Error (stderr): C:\gogs\log\gogs-nssm.txt

That will capture all text output that you would normally receive from Gogs on the command line console, and log it to that file instead.

![](/docs/images/install_gogs_on_windows_nssm_3.png)

File rotation tab:

* Check: Rotate files
* Restrict rotation to files bigger than: 1000000 bytes

![](/docs/images/install_gogs_on_windows_nssm_4.png)

Environment tab:

* Environment variables: PATH=%PATH%;C:\gogs;C:\Program Files (x86)\Git\bin

That is a guarantee that both gogs.exe and git.exe will be on the Gogs service's path variable during runtime.

![](/docs/images/install_gogs_on_windows_nssm_5.png)

Click "Install service", and you should be confirmed that it succeeded. If it failed, refer back to the command line console you started, for the error message. When it succeeds, go to command line and do:

```
nssm start gogs
```

You should see:

```
gogs: START: The operation completed successfully.
```

Check that this is true by opening `C:\gogs\log\gogs-nssm.txt`. You should see Gogs' start up procedures, ending with:

```
timestamp [I] SQLite3 Enabled
timestamp [I] Run Mode: Production
timestamp [I] Listen: http://127.0.1.1:80
```

Now point your web browser at `http://gogs/` and log in.

Gogs is running as a service, and will not need to be run manually, unless something goes wrong. NSSM will attempt to restart the service for you, if the Gogs server crashes.

When you need to restart it after `app.ini` changes, go to an administrator command line after the changes, and do:

```
nssm restart gogs
```

See the [configuration cheat sheet](http://gogs.io/docs/advanced/configuration_cheat_sheet.html) for reference of the `custom\conf\app.ini` settings.

An example of the logging and error handling in action:

```
[log]
ROOT_PATH = C:\gogs\log
```

At the time of writing this line, for Go Git Service 0.5.13.0212 Beta, it will cause the following to print in `C:\gogs\log\gogs-nssm.txt`:

```
timestamp [T] Custom path: C:/gogs/custom
timestamp [T] Log path: C:\gogs\log
timestamp [I] Gogs: Go Git Service 0.5.13.0212 Beta
timestamp [log.go:294 Error()] [E] Fail to set logger(file): invalid character 'g' in string escape code
```

This is what was expected in `C:\custom\conf\app.ini`:

```
ROOT_PATH = C:/gogs/log
```

And this was the `nssm` interaction while solving it:

```
C:\>nssm restart gogs
gogs: STOP: The operation completed successfully.
gogs: Unexpected status SERVICE_PAUSED in response to START control.

C:\>nssm start gogs
gogs: START: An instance of the service is already running.

C:\>nssm stop gogs
gogs: STOP: The operation completed successfully.

C:\>nssm start gogs
gogs: Unexpected status SERVICE_PAUSED in response to START control.

C:\>nssm restart gogs
gogs: STOP: The operation completed successfully.
gogs: START: The operation completed successfully.
```


text:
using namespace libconfig;

class ConfigIO
{
public:
	Config * open(const char *file);
	Config * open(const std::string &file);
	void write(Config *config, const char *file);
	void write(Config *config, const std::string &file);
	Setting & addSetting(Setting &setting, const char *str, Setting::Type type);
	template<typename T>
	void lookup(Config *cfg, T &val, const char* str)
	{
		try {
			const Setting &tmp = cfg->lookup(str);
			val = tmp;
		} catch (const SettingNotFoundException) {
			// setting doesn't exist, we'll fall back to the hardcoded value
		}
	}
private:
};

template<>
void ConfigIO::lookup(Config *cfg, std::string &val, const char *str);


text:
#import "SCWebAppZipLoader.h"

@implementation SCWebAppZipLoader

+ (NSString *)unzipFile:(NSString *)zipFilePath {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask, YES);
  NSURL *path = [[NSURL fileURLWithPath:[paths objectAtIndex:0]]
      URLByAppendingPathComponent:@"webapps"];
  [fileManager createDirectoryAtURL:path
        withIntermediateDirectories:YES
                         attributes:nil
                              error:nil];
  NSError *error;
  ZZArchive *archive =
      [ZZArchive archiveWithURL:[NSURL fileURLWithPath:zipFilePath]
                          error:&error];
  if (error) {
    DDLogError(@"%@", error.debugDescription);
  }
  NSString *indexHTMLPath = nil;
  for (ZZArchiveEntry *entry in archive.entries) {
    NSURL *targetPath = [path URLByAppendingPathComponent:entry.fileName];

    if (entry.fileMode & S_IFDIR)
      // check if directory bit is set
      [fileManager createDirectoryAtURL:targetPath
            withIntermediateDirectories:YES
                             attributes:nil
                                  error:nil];
    else {
      // Some archives don't have a separate entry for each directory
      // and just include the directory's name in the filename.
      // Make sure that directory exists before writing a file into it.
      [fileManager createDirectoryAtURL:[targetPath
                                            URLByDeletingLastPathComponent]
            withIntermediateDirectories:YES
                             attributes:nil
                                  error:nil];

      if ([[targetPath path] containsString:@"index.html"]) {
        indexHTMLPath = [targetPath path];
      }

      [[entry newDataWithError:nil] writeToURL:targetPath atomically:YES];
    }
  }
  return indexHTMLPath;
}
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/item_one"
            android:icon="@mipmap/ic_launcher"
            android:title="One"/>
        <item
            android:id="@+id/item_two"
            android:icon="@mipmap/ic_launcher"
            android:title="Two"/>
        <item
            android:id="@+id/item_three"
            android:icon="@mipmap/ic_launcher"
            android:title="Three"/>
    </group>
</menu>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `SDL_Palette` struct in crate `sdl2_sys`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, SDL_Palette">

    <title>sdl2_sys::pixels::SDL_Palette - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

sdl2_sys::<wbr>pixels

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Struct sdl2_sys::<wbr>pixels::<wbr>SDL_Palette

                       [−]

               [src]

#[repr(C)]

pub struct SDL_Palette {
    pub ncolors: c_int,
    pub colors: *mut SDL_Color,
    pub version: uint32_t,
    pub refcount: c_int,
}

Fields

                           ncolors: c_int

                           colors: *mut SDL_Color

                           version: uint32_t

                           refcount: c_int

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
package com.sqlprocessor.sqlplan;

import com.sqlprocessor.table.SqlField;
import java.util.List;

/**
 * @author sad
 */
public class ExecutionPlan {

    private List<AbstractPlanItem> stage1LoopPlanItems;
    private List<AbstractPlanItem> stage2GroupByPlanItems;
    private List<AbstractPlanItem> stage3SortPlanItems;

    private List<SqlField> groupingFields;

    public void setGroupingFields(List<SqlField> groupingFields) {
        this.groupingFields = groupingFields;
    }

    public List<AbstractPlanItem> getStage1LoopPlanItems() {
        return stage1LoopPlanItems;
    }

    public List<AbstractPlanItem> getStage2GroupByPlanItems() {
        return stage2GroupByPlanItems;
    }

    public List<AbstractPlanItem> getStage3SortPlanItems() {
        return stage3SortPlanItems;
    }

    public void setStage1LoopPlanItems(List<AbstractPlanItem> stage1LoopPlanItems) {
        this.stage1LoopPlanItems = stage1LoopPlanItems;
    }

    public void setStage2GroupByPlanItems(List<AbstractPlanItem> stage2GroupByPlanItems) {
        this.stage2GroupByPlanItems = stage2GroupByPlanItems;
    }

    public void setStage3SortPlanItems(List<AbstractPlanItem> stage3SortPlanItems) {
        this.stage3SortPlanItems = stage3SortPlanItems;
    }

    public List<SqlField> getGroupingFields() {
        return groupingFields;
    }

}


text:
from rally.plugins.openstack import scenario
from rally.plugins.openstack.scenarios.fuel import utils
from rally.task import validation

class FuelEnvironments(utils.FuelScenario):
    """Benchmark scenarios for Fuel environments."""

    @validation.required_clients("fuel", admin=True)
    @validation.required_openstack(admin=True)
    @scenario.configure()
    def list_environments(self):
        """List Fuel environments."""
        self._list_environments()


text:
package org.fastcatsearch.db.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.fastcatsearch.db.vo.IndexingStatusVO;
import org.fastcatsearch.ir.common.IndexingType;

/*
 * IndexingHistoryMapper 와 테이블명만 다르고 동일하다.
 * */
public interface IndexingResultMapper extends ManagedMapper {

	public static enum ResultStatus { SUCCESS, FAIL, CANCEL, RUNNING, STOP };

	public IndexingStatusVO getEntry(@Param("id") int id) throws Exception;

	public List<IndexingStatusVO> getEntryList(@Param("collectionId") String collectionId) throws Exception;

	public int getCount(@Param("collectionId") String collectionId) throws Exception;

	public void putEntry(IndexingStatusVO vo) throws Exception;

	public void deleteEntry(@Param("collectionId") String collectionId, @Param("type") IndexingType type);

	public List<IndexingStatusVO> getRecentEntryList(@Param("collectionId")String collectionId, @Param("num")int num);

}


text:
package kong

// NodeInformationResponse Node info response object
type NodeInformationResponse struct {
	Hostname   string `json:"hostname"`
	LuaVersion string `json:"lua_version"`
	Version    string `json:"version"`
}

// UpstreamRequest Upstream request object
type UpstreamRequest struct {
	Name string `json:"name"`
}

// UpstreamResponse Upstream response object
type UpstreamResponse struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Slots     uint   `json:"slots"`
	CreatedAt uint   `json:"created_at"`
}

// TargetRequest Target request object
type TargetRequest struct {
	Target string `json:"target"`
	Weight uint   `json:"weight"`
}

// TargetResponse Target response object
type TargetResponse struct {
	ID         string `json:"id"`
	Target     string `json:"target"`
	Weight     uint   `json:"weight"`
	UpstreamID string `json:"upstream_id"`
	CreatedAt  uint   `json:"created_at"`
}

// TargetListResponse Target response object
type TargetListResponse struct {
	Total uint             `json:"total"`
	Data  []TargetResponse `json:"data"`
}

// LightTargetListResponse Target light response object
type LightTargetListResponse struct {
	Total uint `json:"total"`
}


text:
package com.claudiodegio.dbsync.sample.db4;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;

import com.claudiodegio.dbsync.provider.CloudProvider;
import com.claudiodegio.dbsync.DBSync;
import com.claudiodegio.dbsync.provider.GDriveCloudProvider;
import com.claudiodegio.dbsync.TableToSync;
import com.claudiodegio.dbsync.sample.BaseMainDbActivity;
import com.claudiodegio.dbsync.sample.R;

import butterknife.OnClick;

public class MainDb4Activity extends BaseMainDbActivity  {

    private final static String TAG = "MainDb4Activity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_main_db4);
        super.onCreate(savedInstanceState);
   }

    @Override
    public void onPostSync() {
    }

    @Override
    public void onPostSelectFile() {

        CloudProvider gDriveProvider = new GDriveCloudProvider.Builder(this.getBaseContext())
                .setDriveID(driveId)
                .setDriveService(googleDriveService)
                .build();

        TableToSync tableCategory = new TableToSync.Builder("CATEGORY")
                .build();

        TableToSync tableArticle = new TableToSync.Builder("ARTICLE")
                .addJoinTable(tableCategory, "CATEGORY_ID")
                .build();

        dbSync = new DBSync.Builder(this.getBaseContext())
                .setCloudProvider(gDriveProvider)
                .setSQLiteDatabase(app.db4OpenHelper.getWritableDatabase())
                .setDataBaseName(app.db4OpenHelper.getDatabaseName())
                .addTable(tableCategory)
                .addTable(tableArticle)
                .setSchemaVersion(1)
                .build();

    }

    @OnClick(R.id.btArticle)
    public void goToNames(){
        startActivity(new Intent(this, ArticlesActivity.class));
    }

    @OnClick(R.id.btCat)
    public void goToCats(){
        startActivity(new Intent(this, CategoriesActivity.class));
    }
}


text:
package org.apache.hadoop.hbase.ipc;

import org.apache.hadoop.hbase.CompatibilityFactory;
import org.apache.hadoop.hbase.NotServingRegionException;
import org.apache.hadoop.hbase.RegionTooBusyException;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.exceptions.OutOfOrderScannerNextException;
import org.apache.hadoop.hbase.exceptions.RegionMovedException;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.test.MetricsAssertHelper;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.*;

@Category(SmallTests.class)
public class TestRpcMetrics {
  public MetricsAssertHelper HELPER = CompatibilityFactory.getInstance(MetricsAssertHelper.class);

  @Test
  public void testFactory() {
    MetricsHBaseServer masterMetrics = new MetricsHBaseServer("HMaster", new MetricsHBaseServerWrapperStub());
    MetricsHBaseServerSource masterSource = masterMetrics.getMetricsSource();

    MetricsHBaseServer rsMetrics = new MetricsHBaseServer("HRegionServer", new MetricsHBaseServerWrapperStub());
    MetricsHBaseServerSource rsSource = rsMetrics.getMetricsSource();

    assertEquals("master", masterSource.getMetricsContext());
    assertEquals("regionserver", rsSource.getMetricsContext());

    assertEquals("Master,sub=IPC", masterSource.getMetricsJmxContext());
    assertEquals("RegionServer,sub=IPC", rsSource.getMetricsJmxContext());

    assertEquals("Master", masterSource.getMetricsName());
    assertEquals("RegionServer", rsSource.getMetricsName());
  }

  /**
   * This test makes sure that the numbers from a MetricsHBaseServerWrapper are correctly exported
   * to hadoop metrics 2 system.
   */
  @Test
  public void testWrapperSource() {
    MetricsHBaseServer mrpc = new MetricsHBaseServer("HMaster", new MetricsHBaseServerWrapperStub());
    MetricsHBaseServerSource serverSource = mrpc.getMetricsSource();
    HELPER.assertGauge("queueSize", 101, serverSource);
    HELPER.assertGauge("numCallsInGeneralQueue", 102, serverSource);
    HELPER.assertGauge("numCallsInReplicationQueue", 103, serverSource);
    HELPER.assertGauge("numCallsInPriorityQueue", 104, serverSource);
    HELPER.assertGauge("numOpenConnections", 105, serverSource);
    HELPER.assertGauge("numActiveHandler", 106, serverSource);
  }

  /**
   * Test to make sure that all the actively called method on MetricsHBaseServer work.
   */
  @Test
  public void testSourceMethods() {
    MetricsHBaseServer mrpc = new MetricsHBaseServer("HMaster", new MetricsHBaseServerWrapperStub());
    MetricsHBaseServerSource serverSource = mrpc.getMetricsSource();

    for (int i=0; i < 12; i++) {
      mrpc.authenticationFailure();
    }
    for (int i=0; i < 13; i++) {
      mrpc.authenticationSuccess();
    }
    HELPER.assertCounter("authenticationFailures", 12, serverSource);
    HELPER.assertCounter("authenticationSuccesses", 13, serverSource);

    for (int i=0; i < 14; i++) {
      mrpc.authorizationSuccess();
    }
    for (int i=0; i < 15; i++) {
      mrpc.authorizationFailure();
    }
    HELPER.assertCounter("authorizationSuccesses", 14, serverSource);
    HELPER.assertCounter("authorizationFailures", 15, serverSource);

    mrpc.dequeuedCall(100);
    mrpc.processedCall(101);
    mrpc.totalCall(102);
    HELPER.assertCounter("queueCallTime_NumOps", 1, serverSource);
    HELPER.assertCounter("processCallTime_NumOps", 1, serverSource);
    HELPER.assertCounter("totalCallTime_NumOps", 1, serverSource);

    mrpc.sentBytes(103);
    mrpc.sentBytes(103);
    mrpc.sentBytes(103);

    mrpc.receivedBytes(104);
    mrpc.receivedBytes(104);

    HELPER.assertCounter("sentBytes", 309, serverSource);
    HELPER.assertCounter("receivedBytes", 208, serverSource);

    mrpc.exception(null);
    HELPER.assertCounter("exceptions", 1, serverSource);

    mrpc.exception(new RegionMovedException(ServerName.parseServerName("localhost:60020"), 100));
    mrpc.exception(new RegionTooBusyException());
    mrpc.exception(new OutOfOrderScannerNextException());
    mrpc.exception(new NotServingRegionException());
    HELPER.assertCounter("exceptions.RegionMovedException", 1, serverSource);
    HELPER.assertCounter("exceptions.RegionTooBusyException", 1, serverSource);
    HELPER.assertCounter("exceptions.OutOfOrderScannerNextException", 1, serverSource);
    HELPER.assertCounter("exceptions.NotServingRegionException", 1, serverSource);
    HELPER.assertCounter("exceptions", 5, serverSource);
  }

}


text:
{-# LANGUAGE TemplateHaskell #-}
module Game.Render.Walls
(
)
where

import Debug.Trace
import qualified Data.Map as Map
import Control.Lens
import System.Random
import Game.Render.World
import qualified Game.Render.World as R
import Control.Monad.State.Strict

--data WallTile = WallTile
--	{ _wtPrefabName :: String
--	, _wtPossibleRightTiles :: [(String, Int, Int)] -- x, y offsets
--	, _wtPossibleBottomTiles :: [(String, Int, Int)]
--	}

--data WallTileManager = WallTileManager
--	{ _wtmWallTiles :: Map.Map String WallTile
--	}

--makeLenses ''WallTile
--makeLenses ''WallTileManager
--wallBaseData =
--	[("Wall2", 90, 0), ("Wall2_2", 90, 0), ("Wall4", 90, 0), ("Wall4_2", 90, 0)
--	, ("Wall5", 90, 0), ("Wall5_2", 90, 0), ("Wall6", 80, 0), ("Wall6_2", 80, 0)]

--wallBaseData2 =
--	[("Wall1", 0, 60), ("Wall1_2", 0, 60), ("Wall3", 0, 60), ("Wall3_2", 0, 60)
--	, ("Wall4", 0, 40), ("Wall4_2", 0, 60)
--	]

--wallTileManager = WallTileManager Map.empty
--	& wtmWallTiles . at "Wall1" .~ (Just $ newWallTile "Wall1"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall1_2" .~ (Just $ newWallTile "Wall1_2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall2" .~ (Just $ newWallTile "Wall2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall2_2" .~ (Just $ newWallTile "Wall2_2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall3" .~ (Just $ newWallTile "Wall3"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall3_2" .~ (Just $ newWallTile "Wall3_2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall4" .~ (Just $ newWallTile "Wall4"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall4_2" .~ (Just $ newWallTile "Wall4_2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall5" .~ (Just $ newWallTile "Wall5"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall5_2" .~ (Just $ newWallTile "Wall5_2"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall6" .~ (Just $ newWallTile "Wall6"
--		wallBaseData wallBaseData2
--		)
--	& wtmWallTiles . at "Wall6_2" .~ (Just $ newWallTile "Wall6_2"
--		wallBaseData wallBaseData2
--		)

--newWallTile name right bottom = WallTile name right bottom

--initWalls = do
--	--let wr' = wUpdate (
--	wAddComplexTile "background" "b1" (500, 500) (470, 470) (0, 0)
--	objId <- R.wObjectFromPrefab "b1" ("b0")
--	R.wLayerObject "BackgroundLayer" "b0" .= (Just $ R.newRenderObject objId (40, 30) 0)

--	objId1 <- R.wObjectFromPrefab "Flower1" "flower"
--	objId2 <- R.wObjectFromPrefab "Plant3" "plant"
--	objId3 <- R.wObjectFromPrefab "Flower2" "flower2"
--	R.wLayerObject "BottomLayer" "flower" .= (Just $ R.newRenderObject objId1 (250, 150) 0)
--	R.wLayerObject "BottomLayer" "flower2" .= (Just $ R.newRenderObject objId2 (250, 200) 0)
--	R.wLayerObject "BottomLayer" "plant" .= (Just $ R.newRenderObject objId3(200, 150) 0)
--	--return wr'

--generateWalls :: Int -> Int -> StdGen -> State World ()
--generateWalls width height stdGen = do
--	let wtm = wallTileManager

--	let (first, g') = selectOne (Map.keys $ wtm^.wtmWallTiles) stdGen
--	objId <- R.wObjectFromPrefab first (show g')
--	R.wLayerObject "BottomLayer" (show g') .= (Just $ R.newRenderObject objId (0, 0) 0)

--	(ox', oy', g2, topRightName) <- selectRight 0 0 g' first
--	(ox2', oy2', g3, bottomLeftName) <- selectBottom 0 0 g2 first
--	(_, _, g4, _) <- selectRight 0 oy2' g3 bottomLeftName
--	(_, _, g5, _) <- selectBottom ox' 0 g4 topRightName
--	return ()

--	where
--		selectOne names gen = let (index, gen') = randomR (0, length names - 1) gen
--			in (names !! index, gen')

--		choicesRight name = let wtm = wallTileManager
--			in (wtm^.wtmWallTiles.at name._Just.wtPossibleRightTiles)

--		choicesBottom name = let wtm = wallTileManager
--			in (wtm^.wtmWallTiles.at name._Just.wtPossibleBottomTiles)

--		selectRight offsetX offsetY gen lastName
--			| offsetX + ox > width = return (offsetX, offsetY, g', lastName)
--			| offsetY + oy > height = return (offsetX, offsetY, g', lastName)
--			| otherwise = do
--				objId <- R.wObjectFromPrefab newName (show g')
--				R.wLayerObject "BottomLayer" (show g') .= (Just $ R.newRenderObject objId (fromIntegral $ offsetX + ox, fromIntegral $ offsetY + oy) 0)
--				(ox', oy', g'', lastName) <- selectRight (offsetX + ox) (offsetY + oy) g' newName
--				return $ traceShow (ox', oy') (ox', oy', g'', lastName)

--				where ((newName, ox, oy), g') = selectOne (choicesRight lastName) gen

--		selectBottom offsetX offsetY gen lastName
--			| offsetX + ox > width = return (offsetX, offsetY, g', lastName)
--			| offsetY + oy > height = return (offsetX, offsetY, g', lastName)
--			| otherwise = do
--				objId <- R.wObjectFromPrefab newName (show g')
--				R.wLayerObject "BottomLayer" (show g') .= (Just $ R.newRenderObject objId (fromIntegral $ offsetX + ox, fromIntegral $ offsetY + oy) 0)
--				(ox', oy', g'', lastName) <- selectBottom (offsetX + ox) (offsetY + oy) g' newName
--				return $ traceShow (ox', oy') (ox', oy', g'', lastName)

--				where ((newName, ox, oy), g') = selectOne (choicesBottom lastName) gen
--


text:
package com.dpanayotov.simpleweather.navigation;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dpanayotov.simpleweather.R;

import butterknife.Bind;
import butterknife.ButterKnife;

public class NavigationDrawerArrayAdapter extends
		ArrayAdapter<NavigationDrawerItem> {
	Context mContext;

	public NavigationDrawerArrayAdapter(Context context,
			List<NavigationDrawerItem> objects) {
		super(context, R.layout.layout_navigation_drawer_item, objects);
		mContext = context;
	}

	static class ViewHolder {
		@Bind(R.id.text) TextView title;
        @Bind(R.id.image) ImageView image;

        public ViewHolder(View view){
            ButterKnife.bind(this, view);
        }

	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		NavigationDrawerItem rowItem = getItem(position);

		if (convertView == null) {
			convertView = ((LayoutInflater) mContext.
                    getSystemService(Activity.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.layout_navigation_drawer_item, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.title.setText(rowItem.getTextResourceId());
		holder.image.setImageResource(rowItem.getImageResourceId());

		return convertView;
	}

}


text:
<?php

namespace Twig\Error;

class_exists('Twig_Error_Loader');

if (\false) {
    class LoaderError extends \Twig_Error_Loader
    {
    }
}


text:
layout: post
title: 6 action shoes
authors: Edward de Bono

---

- **Book Title**: 6 action shoes
- **Author**: Edward de Bono
- **Year written/published**: 1991
- **Some extracts**:

6 pairs of action shoes:

1. Navy Formal Shoes – Routines and Formality
2. Grey Sneakers – Thinking, Ideas and Investigation
3. Brown Brogues – Pragmatism, Effectiveness and Initiative
4. Orange Gumboots – Emergency, Courage, Risk
5. Pink Slippers - Caring
6. Purple Riding Boots - authority and role


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls Sci. Nat. , Bot. , sér. 3 15: 381 (1851)

#### Original name
Microsphaera friesii var. friesii

### Remarks
null


text:
using LNF.Ordering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LNF.Impl.Ordering
{
    public class Tracking : ITracking
    {
        public int TrackingID { get; set; }
        public int TrackingCheckpointID { get; set; }
        public int POID { get; set; }
        public int ClientID { get; set; }
        public string TrackingData { get; set; }
        public DateTime TrackingDateTime { get; set; }
        public string CheckpointName { get; set; }
        public string LName { get; set; }
        public string FName { get; set; }
    }
}


text:
@echo off
haxelib run openfl %*


text:
from unittest import TestCase

from pyproteome import pathways

class PathwaysTest(TestCase):
    def test_gskb_pathways(self):
        for species in ['Mus musculus']:
            gene_sets = pathways.gskb.get_gskb_pathways(
                species,
            )

            for col in ['name', 'set']:
                self.assertIn(col, gene_sets.columns)

            self.assertGreater(gene_sets.shape[0], 0)

    def test_pathway_common(self):
        for species in ['Homo sapiens']:
            gene_sets = pathways.pathwayscommon.get_pathway_common(
                species,
            )

            for col in ['name', 'set']:
                self.assertIn(col, gene_sets.columns)

            self.assertGreater(gene_sets.shape[0], 0)

    def test_wikipathways(self):
        for species in ['Homo sapiens', 'Mus musculus']:
            gene_sets = pathways.wikipathways.get_wikipathways(
                species,
            )

            for col in ['name', 'set']:
                self.assertIn(col, gene_sets.columns)

            self.assertGreater(gene_sets.shape[0], 0)

    def test_phosphomap_data(self):
        mapping = pathways.psp.get_phosphomap_data()

        for col in ['SITE_GRP_ID', 'ACC_ID', 'MOD_RSD', 'ORGANISM']:
            self.assertIn(col, mapping.columns)

    def test_phosphosite(self):
        for species in ['Homo sapiens', 'Mus musculus']:
            for remap in [False, True]:
                gene_sets = pathways.psp.get_phosphosite(
                    species,
                    remap=remap,
                )

                for col in ['name', 'up_set']:
                    self.assertIn(col, gene_sets.columns)

                self.assertGreater(gene_sets.shape[0], 0)

    def test_phosphosite_regulation(self):
        for species in ['Homo sapiens', 'Mus musculus']:
            for remap in [False, True]:
                gene_sets = pathways.psp.get_phosphosite_regulation(
                    species,
                    remap=remap,
                )

                for col in ['name', 'up_set', 'down_set']:
                    self.assertIn(col, gene_sets.columns)

                self.assertGreater(gene_sets.shape[0], 0)

    def test_pathways(self):
        for p_sites in [True, False]:
            for species in ['Homo sapiens', 'Mus musculus']:
                for remap in [False, True]:
                    if not p_sites and remap:
                        continue

                    gene_sets = pathways.get_pathways(
                        species,
                        p_sites=p_sites,
                        remap=remap,
                    )

                    for col in ['name'] + (
                        ['up_set', 'down_set'] if p_sites else ['set']
                    ):
                        self.assertIn(col, gene_sets.columns)

                    self.assertGreater(gene_sets.shape[0], 0)

    def test_PrPDF(self):
        pdf = pathways.enrichments.PrPDF(range(1, 11))
        self.assertEqual(
            pdf.cdf(1),
            0,
        )
        self.assertEqual(
            pdf.cdf(2),
            .1,
        )
        self.assertEqual(
            pdf.cdf(10),
            .9,
        )
        self.assertEqual(
            pdf.sf(2),
            .8,
        )
        self.assertEqual(
            pdf.sf(10),
            0,
        )
        self.assertEqual(
            pdf.pdf(2),
            .1,
        )
        self.assertEqual(
            pdf.cdf(2) + pdf.pdf(2) + pdf.sf(2),
            1,
        )


text:
"""Start and stop Web Page Replay."""

from telemetry.internal.util import atexit_with_log
import logging
import os
import re
import signal
import subprocess
import sys
import tempfile
import urllib

from telemetry.core import util
from telemetry.internal import forwarders
from telemetry.internal.util import binary_manager

import py_utils

_WPR_DIR = os.path.abspath(os.path.join(
    util.GetCatapultDir(), 'web_page_replay_go'))

class ReplayError(Exception):
  """Catch-all exception for the module."""
  pass

class ReplayNotFoundError(ReplayError):
  def __init__(self, label, path):
    super(ReplayNotFoundError, self).__init__()
    self.args = (label, path)

  def __str__(self):
    label, path = self.args
    return 'Path does not exist for %s: %s' % (label, path)

class ReplayNotStartedError(ReplayError):
  pass

class ReplayServer(object):
  """Start and Stop Web Page Replay.

  Web Page Replay is a proxy that can record and "replay" web pages with
  simulated network characteristics -- without having to edit the pages
  by hand. With WPR, tests can use "real" web content, and catch
  performance issues that may result from introducing network delays and
  bandwidth throttling.

  Example:
     with ReplayServer(archive_path):
       self.NavigateToURL(start_url)
       self.WaitUntil(...)
  """

  def __init__(self, archive_path, replay_host, http_port, https_port,
               replay_options):
    """Initialize ReplayServer.

    Args:
      archive_path: a path to a specific WPR archive (required).
      replay_host: the hostname to serve traffic.
      http_port: an integer port on which to serve HTTP traffic. May be zero
          to let the OS choose an available port.
      https_port: an integer port on which to serve HTTPS traffic. May be zero
          to let the OS choose an available port.
      replay_options: an iterable of options strings to forward to replay.py.
    """
    self.archive_path = archive_path
    self._replay_host = replay_host
    self._started_ports = {}  # a dict such as {'http': 80, 'https': 443}

    # A temporary path for storing stdout & stderr of the webpagereplay
    # subprocess.
    self._temp_log_file_path = None

    go_binary_path = binary_manager.FetchPath('wpr_go',
                                              py_utils.GetHostArchName(),
                                              py_utils.GetHostOsName())

    self._cmd_line = self._GetCommandLine(
        go_binary_path, http_port, https_port, replay_options, archive_path)

    if 'record' in replay_options:
      self._CheckPath('archive directory', os.path.dirname(self.archive_path))
    elif not os.path.exists(self.archive_path):
      self._CheckPath('archive file', self.archive_path)

    self.replay_process = None

  @property
  def http_port(self):
    if not self._IsStarted():
      return None
    return self._started_ports['http']

  @property
  def https_port(self):
    if not self._IsStarted():
      return None
    return self._started_ports['https']

  @staticmethod
  def _GetCommandLine(go_binary_path, http_port, https_port,
                      replay_options, archive_path):
    """Set WPR command-line options. Can be overridden if needed."""
    for option in replay_options:
      if option not in ['--record', '--replay', '--inject_scripts=']:
        raise ValueError("Invalid replay options %s" % replay_options)
    cmd_line = [go_binary_path]
    if '--record' in replay_options:
      cmd_line.append('record')
    else:
      cmd_line.append('replay')
    key_file = os.path.join(_WPR_DIR, 'wpr_key.pem')
    cert_file = os.path.join(_WPR_DIR, 'wpr_cert.pem')
    inject_script = os.path.join(_WPR_DIR, 'deterministic.js')
    cmd_line.extend([
        '--http_port=%s' % http_port,
        '--https_port=%s' % https_port,
        '--https_key_file=%s' % key_file,
        '--https_cert_file=%s' % cert_file])
    if '--inject_scripts=' in replay_options:
      cmd_line.append('--inject_scripts=')
    else:
      cmd_line.append('--inject_scripts=%s' % inject_script)
    cmd_line.append(archive_path)
    return cmd_line

  def _CheckPath(self, label, path):
    if not os.path.exists(path):
      raise ReplayNotFoundError(label, path)

  def _OpenLogFile(self):
    """Opens the log file for writing."""
    log_dir = os.path.dirname(self._temp_log_file_path)
    if not os.path.exists(log_dir):
      os.makedirs(log_dir)
    return open(self._temp_log_file_path, 'w')

  def _LogLines(self):
    """Yields the log lines."""
    if not os.path.isfile(self._temp_log_file_path):
      return
    with open(self._temp_log_file_path) as f:
      for line in f:
        yield line

  def _IsStarted(self):
    """Returns true if the server is up and running."""
    if self.replay_process.poll() is not None:
      # The process terminated.
      return False

    def HasIncompleteStartedPorts():
      return ('http' not in self._started_ports or
              'https' not in self._started_ports)

    if HasIncompleteStartedPorts():
      self._started_ports = self._ParseLogFilePorts(self._LogLines())
    if HasIncompleteStartedPorts():
      return False

    try:
      # HTTPS may require SNI (which urllib does not speak), so only check
      # that HTTP responds.
      return 200 == self._UrlOpen('web-page-replay-generate-200').getcode()
    except IOError:
      return False

  @staticmethod
  def _ParseLogFilePorts(log_lines):
    """Returns the ports on which replay listens as reported in its log file.

    Only matches HTTP, HTTPS, and DNS. One call may return only some
    of the ports depending on what has been written to the log file.

    Example log lines:
      2014-09-03 17:04:27,978 Starting server on http://:51673
      2014-09-03 17:04:27,978 Starting server on https://:35270

    Returns:
      a dict with ports available in log_lines. For example,
         {}  # no ports found
         {'http': 1234, 'https': 2345, 'dns': 3456}
    """
    ports = {}
    port_re = re.compile(
        r'.*Starting server on '
        r'(?P<protocol>http|https)://'
        r'(?P<host>[^:]*):'
        r'(?P<port>\d+)')
    for line in log_lines:
      m = port_re.match(line.strip())
      if m:
        protocol = m.group('protocol').lower()
        ports[protocol] = int(m.group('port'))
    return ports

  def StartServer(self):
    """Start Web Page Replay and verify that it started.

    Returns:
      A forwarders.PortSet(http, https, dns) tuple; with dns None if unused.
    Raises:
      ReplayNotStartedError: if Replay start-up fails.
    """
    is_posix = sys.platform.startswith('linux') or sys.platform == 'darwin'
    logging.info('Starting Web-Page-Replay: %s', self._cmd_line)
    self._CreateTempLogFilePath()
    with open(self._temp_log_file_path, 'w') as log_fh:
      self.replay_process = subprocess.Popen(
          self._cmd_line, stdout=log_fh, stderr=subprocess.STDOUT,
          preexec_fn=(_ResetInterruptHandler if is_posix else None))
    try:
      py_utils.WaitFor(self._IsStarted, 30)
      logging.info('WPR ports: %s' % self._started_ports)
      atexit_with_log.Register(self.StopServer)
      return forwarders.PortSet(
          self._started_ports['http'],
          self._started_ports['https'],
          self._started_ports.get('dns'),  # None if unused
          )
    except py_utils.TimeoutException:
      raise ReplayNotStartedError(
          'Web Page Replay failed to start. Log output:\n%s' %
          ''.join(self._LogLines()))

  def StopServer(self):
    """Stop Web Page Replay."""
    if self._IsStarted():
      try:
        self._StopReplayProcess()
      finally:
        # TODO(rnephew): Upload logs to google storage. crbug.com/525787
        self._CleanUpTempLogFilePath()

  def _StopReplayProcess(self):
    if not self.replay_process:
      return
    logging.debug('Trying to stop Web-Page-Replay gracefully')
    try:
      if self._started_ports:
        self._UrlOpen('web-page-replay-command-exit').close()
    except IOError:
      # IOError is possible because the server might exit without response.
      pass
    try:
      py_utils.WaitFor(lambda: self.replay_process.poll() is not None, 10)
    except py_utils.TimeoutException:
      try:
        # Use a SIGINT so that it can do graceful cleanup.
        self.replay_process.send_signal(signal.SIGINT)
      except:  # pylint: disable=bare-except
        # On Windows, we are left with no other option than terminate().
        is_primary_nameserver_changed_by_replay = (
            self._use_dns_server and self._replay_host == '127.0.0.1')
        if is_primary_nameserver_changed_by_replay:
          # Replay changes the DNS nameserver configuration so that DNS
          # requests are resolved by replay's own DNS server. It resolves
          # all DNS requests to it own IP address to it can server the
          # HTTP and HTTPS requests.
          # If the replay host is not '127.0.0.1', then replay skips the
          # nameserver change because it assumes a different mechanism
          # will be used to route DNS requests to replay's DNS server.
          logging.warning(
              'Unable to stop Web-Page-Replay gracefully.\n'
              'Replay changed the DNS nameserver configuration to make replay '
              'the primary nameserver. That might not be restored!')
        try:
          self.replay_process.terminate()
        except:  # pylint: disable=bare-except
          pass
      self.replay_process.wait()

  def _CreateTempLogFilePath(self):
    assert self._temp_log_file_path is None
    handle, self._temp_log_file_path = tempfile.mkstemp()
    os.close(handle)

  def _CleanUpTempLogFilePath(self):
    assert self._temp_log_file_path
    if logging.getLogger('').isEnabledFor(logging.DEBUG):
      with open(self._temp_log_file_path, 'r') as f:
        wpr_log_content = '\n'.join([
            '************************** WPR LOG *****************************',
            f.read(),
            '************************** END OF WPR LOG **********************'])
      logging.debug(wpr_log_content)
    os.remove(self._temp_log_file_path)
    self._temp_log_file_path = None

  def __enter__(self):
    """Add support for with-statement."""
    self.StartServer()
    return self

  def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb):
    """Add support for with-statement."""
    self.StopServer()

  def _UrlOpen(self, url_path, protocol='http'):
    """Open a Replay URL.

    For matching requests in the archive, Replay relies on the "Host:" header.
    For Replay command URLs, the "Host:" header is not needed.

    Args:
      url_path: WPR server request path.
      protocol: 'http' or 'https'
    Returns:
      a file-like object from urllib.urlopen
    """
    url = '%s://%s:%s/%s' % (
        protocol, self._replay_host, self._started_ports[protocol], url_path)
    return urllib.urlopen(url, proxies={})

def _ResetInterruptHandler():
  """Reset the interrupt handler back to the default.

  The replay process is stopped gracefully by making an HTTP request
  ('web-page-replay-command-exit'). The graceful exit is important for
  restoring the DNS configuration. If the HTTP request fails, the fallback
  is to send SIGINT to the process.

  On posix system, running this function before starting replay fixes a
  bug that shows up when Telemetry is run as a background command from a
  script. https://crbug.com/254572.

  Background: Signal masks on Linux are inherited from parent
  processes. If anything invoking us accidentally masks SIGINT
  (e.g. by putting a process in the background from a shell script),
  sending a SIGINT to the child will fail to terminate it.
  """
  signal.signal(signal.SIGINT, signal.SIG_DFL)


text:
package org.apache.geode.internal.cache.partitioned;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.test.junit.categories.UnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category(UnitTest.class)
public class FetchPartitionDetailsMessageTest {

  @Test
  public void shouldBeMockable() throws Exception {
    FetchPartitionDetailsMessage mockFetchPartitionDetailsMessage =
        mock(FetchPartitionDetailsMessage.class);
    DistributionManager mockDistributionManager = mock(DistributionManager.class);
    PartitionedRegion mockPartitionedRegion = mock(PartitionedRegion.class);
    long startTime = System.currentTimeMillis();
    Object key = new Object();

    when(mockFetchPartitionDetailsMessage.operateOnPartitionedRegion(eq(mockDistributionManager),
        eq(mockPartitionedRegion), eq(startTime))).thenReturn(true);

    assertThat(mockFetchPartitionDetailsMessage.operateOnPartitionedRegion(mockDistributionManager,
        mockPartitionedRegion, startTime)).isTrue();
  }
}


text:
<?php

/**
 * @namespace
 */
namespace ShiftContentNew\Type;

use ShiftCommon\Model\Entity\EntityValidator;

use Zend\Filter\StripTags;
use Zend\Filter\StringTrim;

use Zend\Validator\Alnum;
use Zend\Validator\StringLength;
use Zend\Validator\NotEmpty;

/**
 * Content type validator
 * This encapsulates rules for validating content types before persistence.
 *
 * @category    Projectshift
 * @package     ShiftContentNew
 * @subpackage  Type
 */
class TypeValidator extends EntityValidator
{

    /**
     * Init
     * Initializes validator and defines rules for validating entity
     * properties.
     *
     * @return EntityValidator|void
     */
    public function init()
    {
        //name
        $this->addProperty('name');
        $this->name->addFilter(new StripTags);
        $this->name->addFilter(new StringTrim);
        $this->name->addValidator(new NotEmpty);
        $this->name->addValidator(new Alnum(array('allowWhiteSpace' => true)));
        $this->name->addValidator(new StringLength(
            array('min' => '3', 'max' => 250)
        ));
        $this->name->addValidator(
            'ShiftContentNew\Type\Validator\UniqueNameValidator'
        );

        //description
        $this->addProperty('description');
        $this->description->addFilter(new StripTags);
        $this->description->addFilter(new StringTrim);
        $this->description->addValidator(new StringLength(array('max' => 250)));

        //fields validator
        $this->addCollection('fields');
        $this->fields->setElementValidator(
            'ShiftContentNew\Type\Field\FieldValidator'
        );
    }

} //class ends here


text:
#ifndef SIT_REST_HPP
#define SIT_REST_HPP

// System
#include <cmath>

// ROS
#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>

// Messages
#include <std_srvs/Empty.h>
#include <std_msgs/Bool.h>
#include <motion_planning_msgs/SitRestAction.h>

class SitRestAction {
 protected:

  ros::NodeHandle nh_;
  // NodeHandle instance must be created before this line.
  // Otherwise strange error may occur.
  actionlib::SimpleActionServer<motion_planning_msgs::SitRestAction> as_;
  std::string action_name_;
  motion_planning_msgs::SitRestFeedback feedback_;
  motion_planning_msgs::SitRestResult result_;

 public:
  SitRestAction(ros::NodeHandle nh, std::string name);

  ~SitRestAction(void);

  void init();

  void goalCB();

  void preemptCB();

  void awakeCB(const std_msgs::Bool::ConstPtr& msg);

  void executeCB();

 private:
  // Flags
  bool is_awake_;

  // ROS
  ros::Subscriber awake_sub_;
  std_srvs::Empty rest_srv_;
  ros::ServiceClient rest_client_;
  std_srvs::Empty stop_move_srv_;
  ros::ServiceClient stop_move_client_;
};

#endif /* SIT_REST_HPP */


text:
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>An exploration of N.C. House Bill 2</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <link href="style.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder">Toggle navigation
          </button>

In short

On social media

In our schools

Close to home

Across the country

People are speaking out.</h2

Across the state, people have spoken out against HB2. In this video, protestors shut down the main streets in downtown Chapel Hill during rush hour. The demonstration lasted from 6 p.m. to nearly 10:30 p.m. No arrests were made.


text:
package com.anttoolkit.general.tasks.collections.array;

import com.anttoolkit.general.tasks.collections.array.util.ArrayManager;
import com.anttoolkit.general.tasks.GenericTask;
import org.apache.tools.ant.*;

public class CheckArrayContainsValueTask
		extends GenericTask
{
	private String arrayName = null;
	private String value = null;
	private String property = null;

	public void setArray(String name)
	{
		arrayName = name;
	}

	public void setValue(String val)
	{
		value = val;
	}

	public void setProperty(String property)
	{
		this.property = property;
	}

	public void doWork() throws BuildException
	{
		boolean contains = ArrayManager.contains(arrayName, value);
		setPropertyThreadSafe(property, Boolean.toString(contains));
	}

	protected void validate()
	{
		if (arrayName == null)
		{
			throw new BuildException("Array name should be specified");
		}

		if (value == null)
		{
			throw new BuildException("Value to search for should be specified");
		}

		if (property == null)
		{
			throw new BuildException("Ant property name should be specified");
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Collaborative Research: BPC-DP: African-American Researchers in Computing Sciences (AARCS)</AwardTitle>
    <AwardEffectiveDate>12/01/2008</AwardEffectiveDate>
    <AwardExpirationDate>09/30/2010</AwardExpirationDate>
    <AwardAmount>107001</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      05050000
      <Directorate>
        <LongName>Direct For Computer & Info Scie & Enginr</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Computer and Network Systems</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Janice E. Cuny</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>Auburn University proposes the African American Researchers in Computing Sciences (AARCS) program to broaden African American participation in tenure track faculty and research scientist positions within the education pipeline. African American undergraduate students across the nation will be exposed to role models, research, and graduate school opportunities that are specifically designed to address disbeliefs, concerns, and misunderstandings about computing sciences faculty and research. This will be accomplished through targeted presentations by African American computing science faculty and graduate students, a Future Faculty/Research Scientist Mentoring program, and an annual AARCS mini-conference. The AARCS program will serve as an empirically-based and tested model that can be incorporated into larger Alliance projects. In addition, it will serve as a model that can be used to target other underrepresented groups.</AbstractNarration>
    <MinAmdLetterDate>11/25/2008</MinAmdLetterDate>
    <MaxAmdLetterDate>07/14/2009</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0837781</AwardID>
    <Investigator>
      <FirstName>Jerlando</FirstName>
      <LastName>Jackson</LastName>
      <EmailAddress>jjackson@education.wisc.edu</EmailAddress>
      <StartDate>11/25/2008</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>University of Wisconsin-Madison</Name>
      <CityName>MADISON</CityName>
      <ZipCode>537151218</ZipCode>
      <PhoneNumber>6082623822</PhoneNumber>
      <StreetAddress>21 North Park Street</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Wisconsin</StateName>
      <StateCode>WI</StateCode>
    </Institution>
    <FoaInformation>
      0000912
      <Name>Computer Science</Name>
    </FoaInformation>
  </Award>
</rootTag>


text:
export default class AircraftTypes {
    constructor($resource, GLOBALS) {
        return $resource(GLOBALS.BASE_URL + '/api/v1/aircrafttypes', null, {
            query: {
                method: 'GET',
                isArray: true,
                cache: true
            }
        });
    }
}


text:
<?php

namespace ZF2rapid\Task\Install;

use Zend\Console\ColorInterface as Color;
use ZFrapidCore\Console\Console;
use ZFrapidCore\Task\AbstractTask;

/**
 * Class ChooseSkeletonApplication
 *
 * @package ZF2rapid\Task\Install
 */
class ChooseSkeletonApplication extends AbstractTask
{
    /**
     * URL to Zend Framework 2 Skeleton Application
     */
    const ZF2_SKELETON_URL = 'https://github.com/zendframework/ZendSkeletonApplication/archive/release-2.5.0.zip';

    /**
     * URL to ZF2rapid Skeleton Application
     */
    const ZF2RAPID_SKELETON_URL = 'https://github.com/ZFrapid/zf2rapid-skeleton/archive/master.zip';

    /**
     * Process the command
     *
     * @return integer
     */
    public function processCommandTask()
    {
        // set indention
        $spaces = Console::INDENTION_PROMPT_OPTIONS;

        // define options for select prompt
        $options = [
            $spaces . 'a' => 'task_install_choose_skeleton_official',
            $spaces . 'b' => 'task_install_choose_skeleton_zf2rapid',
            $spaces . 'c' => 'task_install_choose_skeleton_custom',
        ];

        $skeletonAnswer = $this->console->writeSelectPrompt(
            'task_install_choose_skeleton_prompt',
            $options
        );

        // set url depending on select prompt answer
        switch ($skeletonAnswer) {
            case 'b':
                $this->params->skeletonUrl = self::ZF2RAPID_SKELETON_URL;
                break;

            case 'c':
                $this->params->skeletonUrl = $this->console->writeLinePrompt(
                    'task_install_choose_skeleton_enter_url'
                );
                break;

            default:
                $this->params->skeletonUrl = self::ZF2_SKELETON_URL;
        }

        // set skeleton application name
        $this->params->skeletonName = $options[$spaces . $skeletonAnswer];

        // write which skeleton application was chosen
        $this->console->writeTaskLine(
            'task_install_choose_skeleton_installation',
            [
                $this->console->colorize(
                    $this->params->skeletonName, Color::GREEN
                )
            ]
        );

        return 0;
    }

}


text:
import os

import mock

from nova.tests.unit.virt.hyperv import test_base
from nova.virt.hyperv import constants
from nova.virt.hyperv import pathutils
from nova.virt.hyperv import vmutils

class PathUtilsTestCase(test_base.HyperVBaseTestCase):
    """Unit tests for the Hyper-V PathUtils class."""

    def setUp(self):
        super(PathUtilsTestCase, self).setUp()
        self.fake_instance_dir = os.path.join('C:', 'fake_instance_dir')
        self.fake_instance_name = 'fake_instance_name'

        self._pathutils = pathutils.PathUtils()

    @mock.patch.object(pathutils.PathUtils, 'rename')
    @mock.patch.object(os.path, 'isfile')
    @mock.patch.object(os, 'listdir')
    def test_move_folder_files(self, mock_listdir, mock_isfile, mock_rename):
        src_dir = 'src'
        dest_dir = 'dest'
        fname = 'tmp_file.txt'
        subdir = 'tmp_folder'
        src_fname = os.path.join(src_dir, fname)
        dest_fname = os.path.join(dest_dir, fname)

        # making sure src_subdir is not moved.
        mock_listdir.return_value = [fname, subdir]
        mock_isfile.side_effect = [True, False]

        self._pathutils.move_folder_files(src_dir, dest_dir)
        mock_rename.assert_called_once_with(src_fname, dest_fname)

    def _mock_lookup_configdrive_path(self, ext):
        self._pathutils.get_instance_dir = mock.MagicMock(
            return_value=self.fake_instance_dir)

        def mock_exists(*args, **kwargs):
            path = args[0]
            return True if path[(path.rfind('.') + 1):] == ext else False
        self._pathutils.exists = mock_exists
        configdrive_path = self._pathutils.lookup_configdrive_path(
            self.fake_instance_name)
        return configdrive_path

    def test_lookup_configdrive_path(self):
        for format_ext in constants.DISK_FORMAT_MAP:
            configdrive_path = self._mock_lookup_configdrive_path(format_ext)
            fake_path = os.path.join(self.fake_instance_dir,
                                     'configdrive.' + format_ext)
            self.assertEqual(configdrive_path, fake_path)

    def test_lookup_configdrive_path_non_exist(self):
        self._pathutils.get_instance_dir = mock.MagicMock(
            return_value=self.fake_instance_dir)
        self._pathutils.exists = mock.MagicMock(return_value=False)
        configdrive_path = self._pathutils.lookup_configdrive_path(
            self.fake_instance_name)
        self.assertIsNone(configdrive_path)

    @mock.patch.object(pathutils.PathUtils, 'unmount_smb_share')
    @mock.patch('os.path.exists')
    def _test_check_smb_mapping(self, mock_exists, mock_unmount_smb_share,
                                existing_mappings=True, share_available=False):
        mock_exists.return_value = share_available

        fake_mappings = (
            [mock.sentinel.smb_mapping] if existing_mappings else [])

        self._pathutils._smb_conn.Msft_SmbMapping.return_value = (
            fake_mappings)

        ret_val = self._pathutils.check_smb_mapping(
            mock.sentinel.share_path)

        self.assertEqual(existing_mappings and share_available, ret_val)
        if existing_mappings and not share_available:
            mock_unmount_smb_share.assert_called_once_with(
                mock.sentinel.share_path, force=True)

    def test_check_mapping(self):
        self._test_check_smb_mapping()

    def test_remake_unavailable_mapping(self):
        self._test_check_smb_mapping(existing_mappings=True,
                                     share_available=False)

    def test_available_mapping(self):
        self._test_check_smb_mapping(existing_mappings=True,
                                     share_available=True)

    def test_mount_smb_share(self):
        fake_create = self._pathutils._smb_conn.Msft_SmbMapping.Create
        self._pathutils.mount_smb_share(mock.sentinel.share_path,
                                        mock.sentinel.username,
                                        mock.sentinel.password)
        fake_create.assert_called_once_with(
            RemotePath=mock.sentinel.share_path,
            UserName=mock.sentinel.username,
            Password=mock.sentinel.password)

    def _test_unmount_smb_share(self, force=False):
        fake_mapping = mock.Mock()
        smb_mapping_class = self._pathutils._smb_conn.Msft_SmbMapping
        smb_mapping_class.return_value = [fake_mapping]

        self._pathutils.unmount_smb_share(mock.sentinel.share_path,
                                          force)

        smb_mapping_class.assert_called_once_with(
            RemotePath=mock.sentinel.share_path)
        fake_mapping.Remove.assert_called_once_with(Force=force)

    def test_soft_unmount_smb_share(self):
        self._test_unmount_smb_share()

    def test_force_unmount_smb_share(self):
        self._test_unmount_smb_share(force=True)

    @mock.patch('os.path.join')
    def test_get_instances_sub_dir(self, fake_path_join):

        class WindowsError(Exception):
            def __init__(self, winerror=None):
                self.winerror = winerror

        fake_dir_name = "fake_dir_name"
        fake_windows_error = WindowsError
        self._pathutils._check_create_dir = mock.MagicMock(
            side_effect=WindowsError(pathutils.ERROR_INVALID_NAME))
        with mock.patch('__builtin__.WindowsError',
                        fake_windows_error, create=True):
            self.assertRaises(vmutils.HyperVException,
                              self._pathutils._get_instances_sub_dir,
                              fake_dir_name)


text:
                <button class="uk-button uk-button-small" type="button" ng-click="updateTitle($index)"></button>
                <button class="uk-button uk-button-small uk-button-danger" type="button" ng-click="removeImage($index)"></button>

        No images in gallery.

    <button class="uk-button uk-margin-small-right js-gallery-import" type="button" ng-click="pickImage()"></button>
     Empty


text:
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { BehaviorSubject } from 'rxjs';

import { ChartData } from 'app/shared/components/charts/charts.component';
import {
    AssignmentPoll,
    AssignmentPollMethod,
    AssignmentPollPercentBase
} from 'app/shared/models/assignments/assignment-poll';
import { BaseViewModel } from 'app/site/base/base-view-model';
import { ProjectorElementBuildDeskriptor } from 'app/site/base/projectable';
import { PollClassType, ViewBasePoll } from 'app/site/polls/models/view-base-poll';
import { ViewAssignment } from './view-assignment';
import { ViewAssignmentOption } from './view-assignment-option';

export interface AssignmentPollTitleInformation {
    title: string;
}

export const AssignmentPollMethodVerbose = {
    Y: _('Yes per candidate'),
    N: _('No per candidate'),
    YN: _('Yes/No per candidate'),
    YNA: _('Yes/No/Abstain per candidate')
};

export const AssignmentPollPercentBaseVerbose = {
    Y: _('Sum of votes including general No/Abstain'),
    YN: _('Yes/No per candidate'),
    YNA: _('Yes/No/Abstain per candidate'),
    valid: _('All valid ballots'),
    cast: _('All casted ballots'),
    entitled: _('All entitled users'),
    disabled: _('Disabled (no percents)')
};

export class ViewAssignmentPoll
    extends ViewBasePoll<AssignmentPoll, AssignmentPollMethod, AssignmentPollPercentBase>
    implements AssignmentPollTitleInformation
{
    public static COLLECTIONSTRING = AssignmentPoll.COLLECTIONSTRING;
    protected _collectionString = AssignmentPoll.COLLECTIONSTRING;

    public readonly tableChartData: Map<string, BehaviorSubject<ChartData>> = new Map();
    public readonly pollClassType = PollClassType.Assignment;

    public get pollmethodVerbose(): string {
        return AssignmentPollMethodVerbose[this.pollmethod];
    }

    public get percentBaseVerbose(): string {
        return AssignmentPollPercentBaseVerbose[this.onehundred_percent_base];
    }

    public getContentObject(): BaseViewModel {
        return this.assignment;
    }

    public getSlide(): ProjectorElementBuildDeskriptor {
        return {
            getBasicProjectorElement: options => ({
                name: AssignmentPoll.COLLECTIONSTRING,
                id: this.id,
                getIdentifiers: () => ['name', 'id']
            }),
            slideOptions: [],
            projectionDefaultName: 'assignment_poll',
            getDialogTitle: this.getTitle
        };
    }

    protected getDecimalFields(): string[] {
        return AssignmentPoll.DECIMAL_FIELDS;
    }
}

export interface ViewAssignmentPoll extends AssignmentPoll {
    options: ViewAssignmentOption[];
    assignment: ViewAssignment;
}


text:
Page Banner

Isolated mode: not recommended. Read more on the Path to SharePoint blog.


text:
$(document).ready(function(){
  $(".quote").hover(function(){
    $(this).find(".actions").fadeIn();
  }, function(){
    $(this).find(".actions").fadeOut();
  });

  $("input#author").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "/authors",
        method: "GET",
        data: { q: request.term },
        success: function(data) {
          response(eval(data));
        }
      });
    }
  });

  $("input#source").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "/sources",
        method: "GET",
        data: { q: request.term },
        success: function(data) {
          response(eval(data));
        }
      });
    }
  });
})


text:
<!DOCTYPE html>

<title>TODO supply a title</title>

		<form
			id="syncScriptForm"
			action="syncFiles"
			method="post">

			Sync to other hosts

					[[ ${ host } ]] folder:
					<input
						name="location"
						th:value="${ defaultLocation}"
						style="width: 80%;" />

					Sync to:
					<input
						name="extractDir"
						th:value="${ sameLocation }"
						style="width: 80%" />

					Target Hosts:

					<button
						id="syncSubmitButton"
						class="csap-button">Copy File(s)</button>

			Optional settings

					Chown User:
					<select
						id="syncUserid"
						name="chownUserid">
						<option
							th:each="optionUser : ${osUsers}"
							th:selected="${ optionUser == csapUser }"
							th:value="${ optionUser }"
							th:text="${ optionUser }">will be replaced</option>

					</select>

					Delete Existing:
					<input
						type="checkbox"
						name="deleteExisting"
						style=""
						title="If destination exists, it will be renamed to .old. By default - content is merged with exisiting files overwritten" />

					Time Out (seconds):
					<input
						type="number"
						name="timeoutSeconds"
						style="width: 4em"
						value="30"
						title="Commands will be aborted if not completed in specified interval" />

		</form>

Regardless of destination set above - files are ALWAYS forced to same location


text:
<?php

namespace tests\Tests\io;

use PHPUnit\Framework\TestCase;
use wulaphp\util\CurlClient;

class CookieTest extends TestCase {
    public function testCookie() {
        $curlient = CurlClient::getClient(5);

        $cookie             = new \stdClass();
        $cookie->value      = '123';
        $cookies['ocookie'] = $cookie;

        $content = $curlient->withCookies($cookies)->get('http://127.0.0.1:9090/testm/test/scookie');

        self::assertEquals('cookie set', $content);
        self::assertNotEmpty($cookies);
        self::assertArrayHasKey('test-sc', $cookies);
        self::assertEquals('123', $cookies['test-sc']->value);
        self::assertContains('HttpOnly', $cookies['test-sc']->option);

        $curlient->reset();
        $cookie->value      = '789';
        $cookies['ocookie'] = $cookie;

        $content = $curlient->withCookies($cookies)->get('http://127.0.0.1:9090/testm/test/scookie?ok=okk');

        self::assertEquals('cookie set:okk', $content);
        self::assertNotEmpty($cookies);
        self::assertArrayHasKey('test-sc', $cookies);
        self::assertEquals('789', $cookies['test-sc']->value);
        self::assertContains('HttpOnly', $cookies['test-sc']->option);
    }

    public function testMultiExecute() {
        $cookie             = new \stdClass();
        $cookie->value      = '123';
        $cookies['ocookie'] = $cookie;
        $g                  = CurlClient::getClient()->withCookies($cookies)->prepareGet('http://127.0.0.1:9090/testm/test/scookie');

        $cookie              = new \stdClass();
        $cookie->value       = 'abc=321;,测试';
        $cookies2['ocookie'] = $cookie;
        $p                   = CurlClient::getClient()->withCookies($cookies2);
        $p->useJsonBody()->preparePost('http://127.0.0.1:9090/testm/test/scookie', ['testT' => '测试']);

        $rts = CurlClient::execute([$g, $p]);

        self::assertTrue(count($rts[0]) == 2, var_export($rts, true));

        self::assertEquals('cookie set', $rts[0][0]);
        self::assertEquals('cookie post:测试', $rts[0][1]);

        self::assertArrayHasKey('test-sc', $cookies);
        self::assertEquals('123', $cookies['test-sc']->value);
        self::assertContains('HttpOnly', $cookies['test-sc']->option);

        self::assertArrayHasKey('test-sc', $cookies2);
        self::assertEquals('abc=321;,测试', $cookies2['test-sc']->value);
        self::assertContains('HttpOnly', $cookies2['test-sc']->option);
    }
}


text:
package com.christiangp.rxfacebook.sample;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.christiangp.rxfacebook.RxFacebook;
import com.facebook.AccessToken;
import com.facebook.HttpMethod;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MeRequestActivity
    extends AppCompatActivity {

    @BindView(R.id.rawResponseView)
    TextView rawResponseView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_request);
        ButterKnife.bind(this);

        final Bundle params = new Bundle();
        params.putString("fields", "id, birthday, first_name, gender, last_name, link, location, locale, name, timezone, updated_time, email");

        RxFacebook.graphRequest(AccessToken.getCurrentAccessToken(), "me", params, HttpMethod.GET)
                  .subscribe(graphResponse -> {
                      if (graphResponse.getError() != null) {
                          rawResponseView.setText(graphResponse.getError()
                                                               .getErrorMessage());
                      } else {
                          rawResponseView.setText(graphResponse.getRawResponse());
                      }
                  });
    }
}


text:
  Sanvensa est
       un village
       localisé dans le département de l'Aveyron en Midi-Pyrénées. Elle totalisait 599 habitants en 2008.

Le nombre de logements, à Sanvensa, était réparti en 2011 en 19 appartements et 346 maisons soit
 un marché plutôt équilibré.

À Sanvensa, la valorisation moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 251 € du m². À la location la valeur moyenne se situe à 3,94 € du m² par mois.

Si vous envisagez de demenager à Sanvensa, vous pourrez aisément trouver une maison à acheter.

La ville offre quelques  équipements, elle propose entre autres un terrain de tennis, un terrain de sport et une boucle de randonnée.

À proximité de Sanvensa sont localisées les villes de
Lacalm située à 5 km, 204 habitants,
Saint-Salvadou située à 4 km, 410 habitants,
La Rouquette située à 5 km, 698 habitants,
La Bastide-l'Évêque localisée à 8 km, 834 habitants,
Morlhon-le-Haut localisée à 3 km, 547 habitants,
La Fouillade à 6 km, 1 110 habitants,
 entre autres. De plus, Sanvensa est située à seulement six km de Villefranche-de-Rouergue.


text:
namespace blink {
class WebFrame;
class WebURLLoader;
}

namespace content {

class RendererPpapiHostImpl;

class PepperURLLoaderHost
    : public ppapi::host::ResourceHost,
      public blink::WebURLLoaderClient {
 public:
  // If main_document_loader is true, PP_Resource must be 0 since it will be
  // pending until the plugin resource attaches to it.
  PepperURLLoaderHost(RendererPpapiHostImpl* host,
                      bool main_document_loader,
                      PP_Instance instance,
                      PP_Resource resource);
  virtual ~PepperURLLoaderHost();

  // ResourceHost implementation.
  virtual int32_t OnResourceMessageReceived(
      const IPC::Message& msg,
      ppapi::host::HostMessageContext* context) OVERRIDE;

  // blink::WebURLLoaderClient implementation.
  virtual void willSendRequest(blink::WebURLLoader* loader,
                               blink::WebURLRequest& new_request,
                               const blink::WebURLResponse& redir_response);
  virtual void didSendData(blink::WebURLLoader* loader,
                           unsigned long long bytes_sent,
                           unsigned long long total_bytes_to_be_sent);
  virtual void didReceiveResponse(blink::WebURLLoader* loader,
                                  const blink::WebURLResponse& response);
  virtual void didDownloadData(blink::WebURLLoader* loader,
                               int data_length,
                               int encoded_data_length);
  virtual void didReceiveData(blink::WebURLLoader* loader,
                              const char* data,
                              int data_length,
                              int encoded_data_length);
  virtual void didFinishLoading(blink::WebURLLoader* loader,
                                double finish_time,
                                int64_t total_encoded_data_length);
  virtual void didFail(blink::WebURLLoader* loader,
                       const blink::WebURLError& error);

 private:
  // ResourceHost protected overrides.
  virtual void DidConnectPendingHostToResource() OVERRIDE;

  // IPC messages
  int32_t OnHostMsgOpen(ppapi::host::HostMessageContext* context,
                        const ppapi::URLRequestInfoData& request_data);
  int32_t InternalOnHostMsgOpen(ppapi::host::HostMessageContext* context,
                                const ppapi::URLRequestInfoData& request_data);
  int32_t OnHostMsgSetDeferLoading(ppapi::host::HostMessageContext* context,
                                   bool defers_loading);
  int32_t OnHostMsgClose(ppapi::host::HostMessageContext* context);
  int32_t OnHostMsgGrantUniversalAccess(
      ppapi::host::HostMessageContext* context);

  // Sends or queues an unsolicited message to the plugin resource. This
  // handles cases where messages must be reordered for the plugin and
  // the case where we have created a pending host resource and the
  // plugin has not connected to us yet.
  //
  // Takes ownership of the given pointer.
  void SendUpdateToPlugin(IPC::Message* msg);

  // Sends or queues an unsolicited message to the plugin resource. This is
  // used inside SendUpdateToPlugin for messages that are already ordered
  // properly.
  //
  // Takes ownership of the given pointer.
  void SendOrderedUpdateToPlugin(IPC::Message* msg);

  void Close();

  // Returns the frame for the current request.
  blink::WebFrame* GetFrame();

  // Calls SetDefersLoading on the current load. This encapsulates the logic
  // differences between document loads and regular ones.
  void SetDefersLoading(bool defers_loading);

  // Converts a WebURLResponse to a URLResponseInfo and saves it.
  void SaveResponse(const blink::WebURLResponse& response);
  void DidDataFromWebURLResponse(const ppapi::URLResponseInfoData& data);

  // Sends the UpdateProgress message (if necessary) to the plugin.
  void UpdateProgress();

  // Non-owning pointer.
  RendererPpapiHostImpl* renderer_ppapi_host_;

  // If true, then the plugin instance is a full-frame plugin and we're just
  // wrapping the main document's loader (i.e. loader_ is null).
  bool main_document_loader_;

  // The data that generated the request.
  ppapi::URLRequestInfoData request_data_;

  // Set to true when this loader can ignore same originl policy.
  bool has_universal_access_;

  // The loader associated with this request. MAY BE NULL.
  //
  // This will be NULL if the load hasn't been opened yet, or if this is a main
  // document loader (when registered as a mime type). Therefore, you should
  // always NULL check this value before using it. In the case of a main
  // document load, you would call the functions on the document to cancel the
  // load, etc. since there is no loader.
  scoped_ptr<blink::WebURLLoader> loader_;

  int64_t bytes_sent_;
  int64_t total_bytes_to_be_sent_;
  int64_t bytes_received_;
  int64_t total_bytes_to_be_received_;

  // Messages sent while the resource host is pending. These will be forwarded
  // to the plugin when the plugin side connects. The pointers are owned by
  // this object and must be deleted.
  ScopedVector<IPC::Message> pending_replies_;
  ScopedVector<IPC::Message> out_of_order_replies_;

  // True when there's a pending DataFromURLResponse call which will send a
  // PpapiPluginMsg_URLLoader_ReceivedResponse to the plugin, which introduces
  // ordering constraints on following messages to the plugin.
  bool pending_response_;

  base::WeakPtrFactory<PepperURLLoaderHost> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(PepperURLLoaderHost);
};

}  // namespace content

#endif  // CONTENT_RENDERER_PEPPER_PEPPER_URL_LOADER_HOST_H_


text:
Get-Tweets
==========

Practice code for getting Twitter results


text:
package egoscale

import (
	"encoding/json"
	"net/url"
)

func (exo *Client) CreateKeypair(name string) (*CreateSSHKeyPairResponse, error) {
	params := url.Values{}
	params.Set("name", name)

	resp, err := exo.Request("createSSHKeyPair", params)
	if err != nil {
		return nil, err
	}

	var r CreateSSHKeyPairWrappedResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r.Wrapped, nil
}


text:
require 'iana'

# lookup protocol 22
result = IANA::Protocol[22]
puts "protocol 22 => #{result.name} \"#{result.description}\""

exit 0


text:
#ifndef NODEINDEXSCAN_H
#define NODEINDEXSCAN_H

#include "nodes/execnodes.h"

extern int	ExecCountSlotsIndexScan(IndexScan *node);
extern IndexScanState *ExecInitIndexScan(IndexScan *node, EState *estate, int eflags);
extern IndexScanState *ExecInitIndexScanForPartition(IndexScan *node, EState *estate, int eflags,
							  Relation currentRelation, Oid indexid);
extern TupleTableSlot *ExecIndexScan(IndexScanState *node);
extern void ExecEndIndexScan(IndexScanState *node);
extern void ExecIndexMarkPos(IndexScanState *node);
extern void ExecIndexRestrPos(IndexScanState *node);
extern void ExecIndexReScan(IndexScanState *node, ExprContext *exprCtxt);
extern void ExecEagerFreeIndexScan(IndexScanState *node);

/* routines exported to share code with nodeBitmapIndexscan.c */
extern void ExecIndexBuildScanKeys(PlanState *planstate, Relation index,
					   Index scanrelid,
					   List *quals, ScanKey *scanKeys, int *numScanKeys,
					   IndexRuntimeKeyInfo **runtimeKeys, int *numRuntimeKeys,
					   IndexArrayKeyInfo **arrayKeys, int *numArrayKeys);
extern void ExecIndexEvalRuntimeKeys(ExprContext *econtext,
					   IndexRuntimeKeyInfo *runtimeKeys, int numRuntimeKeys);
extern bool ExecIndexEvalArrayKeys(ExprContext *econtext,
					   IndexArrayKeyInfo *arrayKeys, int numArrayKeys);
extern bool ExecIndexAdvanceArrayKeys(IndexArrayKeyInfo *arrayKeys, int numArrayKeys);

extern TupleTableSlot *IndexNext(IndexScanState *node);

#endif   /* NODEINDEXSCAN_H */


text:
package org.apache.camel.itest.springboot.arquillian.container.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.jboss.arquillian.container.se.api.ClassPathDirectory;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.shrinkwrap.api.Node;
import org.jboss.shrinkwrap.api.asset.ClassAsset;

public final class FileDeploymentUtils {

    private static final char DELIMITER_RESOURCE_PATH = '/';
    private static final char DELIMITER_CLASS_NAME_PATH = '.';
    private static final String EXTENSION_CLASS = ".class";

    private FileDeploymentUtils() {
    }

    public static void materializeClass(File entryDirectory, ClassAsset classAsset) throws DeploymentException, IOException {
        File classDirectory;
        if (classAsset.getSource().getPackage() != null) {
            classDirectory = new File(entryDirectory, classAsset.getSource().getPackage().getName().replace(DELIMITER_CLASS_NAME_PATH, File.separatorChar));
            if (!classDirectory.mkdirs()) {
                throw new DeploymentException("Could not create class package directory: " + classDirectory);
            }
        } else {
            classDirectory = entryDirectory;
        }
        File classFile = new File(classDirectory, classAsset.getSource().getSimpleName().concat(EXTENSION_CLASS));
        classFile.createNewFile();
        try (InputStream in = classAsset.openStream(); OutputStream out = new FileOutputStream(classFile)) {
            copy(in, out);
        }
    }

    public static void materializeSubdirectories(File entryDirectory, Node node) throws DeploymentException, IOException {
        for (Node child : node.getChildren()) {
            if (child.getAsset() == null) {
                materializeSubdirectories(entryDirectory, child);
            } else {
                if (ClassPathDirectory.isMarkerFileArchivePath(child.getPath())) {
                    // Do not materialize the marker file
                    continue;
                }
                // E.g. META-INF/my-super-descriptor.xml
                File resourceFile = new File(entryDirectory, child.getPath().get().replace(DELIMITER_RESOURCE_PATH, File.separatorChar));
                File resoureDirectory = resourceFile.getParentFile();
                if (!resoureDirectory.exists() && !resoureDirectory.mkdirs()) {
                    throw new DeploymentException("Could not create class path directory: " + entryDirectory);
                }
                resourceFile.createNewFile();
                try (InputStream in = child.getAsset().openStream(); OutputStream out = new FileOutputStream(resourceFile)) {
                    copy(in, out);
                }
                child.getPath().get();
            }
        }
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        final byte[] buffer = new byte[8192];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            out.write(buffer, 0, n);
        }
        out.flush();
    }

    public static void deleteRecursively(Path directory) throws IOException {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    public static void deleteContent(Path directory) throws IOException {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@assets:drawable/res/drawable/droid_asset.png"
        android:antialias="true"
        android:dither="false"
        android:filter="true"
        android:gravity="center"
        android:tileMode="disabled"
    />


text:
package uk.ac.susx.tag.gramexp;

/**
 * Encapsulates basic string output functionality.
 */
public class Printer {
    public final StringBuilder sb;
    public int indent;

    public Printer() {
        this(new StringBuilder());
    }

    public Printer(StringBuilder sb) {
        this.sb = sb;
    }

    public Printer indent(int delta) {
        indent += delta;
        return this;
    }

    public Printer print(String string) {
        sb.append(string);
        return this;
    }

    public Printer print(char c) {
        sb.append(c);
        return this;
    }

    public Printer println() {
        if (sb.length() > 0) print('\n');
        for (int i = 0; i < indent; i++) print(' ');
        return this;
    }

    public Printer printchkln() {
        if (!endsWithNewLine()) {
            if (sb.length() > 0) print('\n');
            for (int i = 0; i < indent; i++) print(' ');
        }
        return this;
    }

    public Printer printchkln(boolean printNewLine) {
        if (printNewLine) {
            if (sb.length() > 0) print('\n');
            for (int i = 0; i < indent; i++) print(' ');
        }
        return this;
    }

    public boolean endsWithNewLine() {
        int iMax = sb.length();

        for (int i = iMax; i-- > 0; ) {
           if (sb.charAt(i) != ' ') {
               return sb.charAt(i) == '\n';
           }
        }
        // all leading spaces
        return false;
    }

    public String getString() {
        return sb.toString();
    }

    public Printer clear() {
        sb.setLength(0);
        return this;
    }
}