text:
package terris.kilcli.io;

import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import terris.kilcli.KilCli;

/**
 * SocksSocket for KilCli is the class used to establish a Socks5 Proxy

 * connection, with or without username authentication

 * Ver: 1.0.0
 */

public class SocksSocket extends Socket {

	private InputStream in;
	private OutputStream out;

	/**
	 * Creates a Socks5 connection
	 * @param socksHost - proxy host
	 * @param socksPort - proxy port
	 * @param username - username
	 * @param password - password
	 * @param host - final host to connect to
	 * @param port - port on final host to connect to
	 */

	public SocksSocket(String socksHost, int socksPort, String username, String password, String host, int port) throws UnknownHostException, IOException {
		super(socksHost, socksPort);

		// Allocate a bytebuffer for negotiation.
		byte[] octets = new byte[1024];
		out = this.getOutputStream();
		in = this.getInputStream();

		// Set up the ID-String for our client.
		octets[0] = 5;    // SOCKS Version
		octets[1] = 3;    // Number of authentification methods
		octets[2] = 0;    // None - no authentification
		octets[3] = 1;    // GSSAPI - authentification via Kerberos (not implemented!)
		octets[4] = 2;    // Username/Passwd

		// Send the id to the SOCKS server
		out.write(octets, 0, 5);
		out.flush();

		in.read(octets, 0, 2);
		int version = octets[0];
		int allowedMethod = octets[1];
		switch (allowedMethod) {
			case 0:
				//KilCli.gameWrite("No Authentication Required");
				break;
			case 1:
				//KilCli.gameWrite("Authentification via GSSAPI");
				throw new java.io.IOException("Socks5 GSSAPI not implemented");
			case 2:
				//KilCli.gameWrite("Authentification via Username/Password");
		      	octets[0] = (byte) 1;

				byte[] namebuff = username.getBytes();
				octets[1] = (byte) namebuff.length;
				System.arraycopy(namebuff,0,octets,2,namebuff.length);

				byte[] passbuff = password.getBytes();
				octets[2+namebuff.length] = (byte) passbuff.length;
      			System.arraycopy(passbuff,0,octets,3+namebuff.length,passbuff.length);

				// Send authentification to the server and cross fingers...
				out.write(octets, 0, 3 + namebuff.length + passbuff.length);

				//KilCli.gameWrite("Sent " + username + " with passwd " + password + "!");

				// Get the answer.
				in.read(octets, 0, 2);
				if (octets[1] != 0) {
					//KilCli.gameWrite("Authentification failed with " + octets[1]);
					throw new java.io.IOException("U/P authentification failed!");
				}
				break;
			case -1:
				//KilCli.gameWrite("Authentification denied!");
				throw new java.io.IOException("Socks5 authentification denied!");
			default:
				//KilCli.gameWrite("Unknown answer " + octets[1]);
				throw new java.io.IOException("Socks5 unknown authentification required!");
		}

		// After the handshake was completed, we'll ask for a connection to
		// the remote host.
		octets[0] = 5;    // Socks version
		octets[1] = 1;    // command: Connect
		octets[2] = 0;    // Reserved 0
		octets[3] = 3;    // Domainname is following:

		byte[] namebuff = host.getBytes();

		octets[4] = (new Integer(namebuff.length)).byteValue();
		for (int i = 0; i < namebuff.length; i++) {
			octets[5 + i] = namebuff[i];
		}

		// since the port may be 16Bit wide and we're working with bytes we
		// need to split the port accordingly.
		int uport = port / 256;
		int lport = port % 256;

		//KilCli.gameWrite("Portid: " + port + "=" + uport + "*256+" + lport);
		octets[5 + namebuff.length + 0] = (new Integer(uport)).byteValue();
		octets[5 + namebuff.length + 1] = (new Integer(lport)).byteValue();

		// request connection...
		out.write(octets, 0, 5 + namebuff.length + 2);
		//KilCli.gameWrite("Connection Request sent");

		// retrieve the answer
		in.read(octets);
		switch (octets[1]) {
			case 0:
				//KilCli.gameWrite("Success!");
				break;
			case 1:
				//KilCli.gameWrite("general failure");
				throw new java.io.IOException("Socks5 server failure");
			case 2:
				//KilCli.gameWrite("connection refused by ruleset");
				throw new java.io.IOException("Socks5 refused by ruleset");
			case 3:
				//KilCli.gameWrite("network unreachable");
				throw new java.io.IOException("Socks5 network unreachable");
			case 4:
				//KilCli.gameWrite("host unreachable");
				throw new java.io.IOException("Socks5 host unreachable");
			case 5:
				//KilCli.gameWrite("connection refused");
				throw new java.io.IOException("Socks5 connection refused");
			case 6:
				//KilCli.gameWrite("TTL expired");
				throw new java.io.IOException("Socks5 TTL expired");
			case 7:
				//KilCli.gameWrite("Command not supported");
				throw new java.io.IOException("Socks5 command not supported");
			case 8:
				//KilCli.gameWrite("Address type not supported");
				throw new java.io.IOException("Socks5 address type not supported");
			default:
				//KilCli.gameWrite("Unknown answer " + octets[1]);
				throw new java.io.IOException("Socks5 unknown error!");
		}
		// hopefully we now get an IP-address and a port which describes the
		// connection which is routed through the SOCKS server to our
		// destination.
		switch (octets[3]) {
			case 1:
				//KilCli.gameWrite("IP V4 address");
				break;
			case 3:
				//KilCli.gameWrite("DOMAINNAME");
				throw new java.io.IOException("Socks5 Domainname encoding not implemented");
			case 4:
				//KilCli.gameWrite("IP V6 address");
				throw new java.io.IOException("Socks5 IP V6 encoding not implemented");
			default:
				//KilCli.gameWrite("Unknown hostname encoding!");
				throw new java.io.IOException("Socks5 server sent unknown hostname!");
		}
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_google_signin_btn_text_dark_focused"
    android:orientation="vertical"
    android:padding="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/attachmentbutton" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/common_google_signin_btn_text_light_pressed"
            android:text="Add Attachment"
            android:textColor="@android:color/white"
            android:textSize="20dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/addchecklistbutton" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/common_google_signin_btn_text_light_focused"
            android:text="Add Checklist"
            android:textColor="@android:color/white"
            android:textSize="20dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/deletebutton" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/common_google_signin_btn_text_light_focused"
            android:text="Delete"
            android:textColor="@android:color/white"
            android:textSize="20dp" />

    </LinearLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';

/**
 * Class CalendarInputWeek
 * Populates a single row of the calendar widget
 * @prop {Number} month  Numeric value of current month. Used for applying classes
 * @prop {Number} currentDay  Numeric value of current day. Used for applying classes
 * @prop {Array} days  Array of date objects { date: {Number}, month: {Number}, year: {Number}, }
 * @prop {Function} selectDate  Function to call when an individual date is clicked
 */
class CalendarInputWeek extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const days = this.props.days.map((day) => {
      let classes = 'calendar-day';
      if (day.month !== this.props.month) {
        classes += ' off-month';
      } else if (day.date === this.props.currentDay) {
        classes += ' current-day';
      }

      return (
        <p className={classes} key={`day${day.date}${day.month}`} onClick={
          () => {this.props.selectDate(day.date, day.month, day.year);}
        }>
          {day.date}

);
    });

    return (

        {days}

    );
  }
}

export default CalendarInputWeek;


text:
package ru.stqa.selenium;
//
import static org.testng.Assert.assertEquals;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import ru.stqa.selenium.factory.WebDriverFactory;

public class FindFilmNeg extends TestNgTestBase {

	public FindFilmNeg(){
		driver = WebDriverFactory.getDriver(gridHubUrl, capabilities);
    };

    public void find(String film) {

    	WebElement element = driver.findElement(By.id("q")); // Проверка поиска.
        element.clear();
        element.sendKeys(film);
        element.sendKeys(Keys.ENTER);
        driver.findElement(By.cssSelector("img[alt=\"Update all\"]")).click();
        WebDriverWait wait = new WebDriverWait(driver, 300); // Явное ожидание.
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1")));
        assertEquals(driver.findElement(By.id("results")).getText(), "No movies where found.");

    };
}


text:
#ifndef COMPUTE_CONCORDANCE_H
#define COMPUTE_CONCORDANCE_H

#include "program.h"

KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;

void compute_concordance(int argc, char ** argv);

#endif


text:
package com.webmanagement.faceformers;

/**
 * Created by Banpot.S on 8/22/14 AD.
 */
public class Config {
    public static String adsInterstitialUnitIDFullPage = "ca-app-pub-0398916667200592/2387989042";
    public static String adsInterstitialKeyword = "";

    public static String googleAnalyticTrackingId = "UA-18384901-18";
}


text:
require 'fakefs/safe'

module FakeFS
  module SpecHelpers
    def self.extended(example_group)
      example_group.use_fakefs(example_group)
    end

    def self.included(example_group)
      example_group.extend self
    end

    def use_fakefs(describe_block)
      describe_block.before :each do
        FakeFS.activate!
      end

      describe_block.after :each do
        FakeFS.deactivate!
        FakeFS::FileSystem.clear
      end
    end
  end
end


text:
package com.dedpp.dedppmvvm.custom;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dedpp.dedppmvvm.R;

import java.util.List;

/**
 * DataBindingAdapter
 * Created by Dedpp on 2017/9/11.
 */

public abstract class DataBindingAdapter<T, K extends BaseViewHolder> extends BaseQuickAdapter<T, K> {

    public DataBindingAdapter(int layoutResId, @Nullable List<T> data) {
        super(layoutResId, data);
    }

    public DataBindingAdapter(@Nullable List<T> data) {
        super(data);
    }

    public DataBindingAdapter(int layoutResId) {
        super(layoutResId);
    }

    @Override
    protected View getItemView(int layoutResId, ViewGroup parent) {
        ViewDataBinding binding = DataBindingUtil.inflate(mLayoutInflater, layoutResId, parent, false);
        if (binding == null)
            return super.getItemView(layoutResId, parent);
        View view = binding.getRoot();
        view.setTag(R.id.BaseQuickAdapter_databinding_support, binding);
        return view;
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.developpez.rpouiller</groupId>
  <artifactId>tutoriel-web-spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>tutoriel-web-spring Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.1.0</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.1.6.RELEASE</version>
	</dependency>

	<dependency>
		<groupId>org.hsqldb</groupId>
		<artifactId>hsqldb</artifactId>
		<version>2.3.2</version>
	</dependency>

<!-- Il faut donc rajouter les dépendances Maven suivantes.
Les dépendances « spring-orm » et « hibernate-entitymanager »
sont pour l'accès aux données.
Tandis que la dépendance « jstl » est pour l'utilisation
de la JSTL (Java Standard Tag Library) dans la JSP d'affichage.  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.4.Final</version>
</dependency>

<dependency>
	<groupId>jstl</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>

</dependencies>

  <build>
    <finalName>tutoriel-web-spring</finalName>
  </build>
</project>


text:
import os
import time
import re
import socket
import json
import logging
import netaddr
import importlib
import inspect
import xml.dom.minidom
from datetime import datetime
from dateutil import tz
import plugin
import event
import httpd
from pollinator import poll

def_events_port = 1315

#  Polling timeout in milliseconds
poll_timeout = 3000

class Barrel(object):

    #  File in datadir used to record current state
    #
    statefile_name = 'rainbarrel.state'

    #  Match valid hex numbers
    #
    is_hex = re.compile(r'^0x[0-9a-fA-F]+$')

    #  This is the number of seconds between Jan 1, 1970 UTC (unix epoch) and
    #  Jan 1, 2000 UTC (rainforest epoch).
    #
    #  Except the meter seems to actually be on local time, so subtract 6hrs
    #
    time_t_offset_2000 = 946706400 - 21600

    #  Configuration information for each message type.
    #
    properties = {
        'InstantaneousDemand': {
            'event_name': 'demand',
            'desired_period': 30,
            'readings': ['Demand'],
            'units': 'kW'
        },
        'CurrentSummationDelivered': {
            'event_name': 'summation',
            'desired_period': 300,
            'readings': ['SummationDelivered', 'SummationReceived'],
            'units': 'kWh'
        },
        'DeviceInfo': {},
        'NetworkInfo': {},
        'PriceCluster': {},
        'TimeCluster': {},
        'BlockPriceDetail': {},
    }

    #  Don't trigger a period update if the delta is less than this
    period_reset_tolerance = 5

    #  Response tuple when no action is needed
    #
    noop_response = (200, '', 'text/plain')

    set_schedule_template = """
<RavenCommand>
    <Name>set_schedule</Name>
    <DeviceMacId>%s</DeviceMacId>
    <Event>%s</Event>
    <Frequency>0x%04x</Frequency>
    <Enabled>Y</Enabled>
</RavenCommand>
"""

    def __init__(self, config, **params):
        self.log = params.get('log')
        if not self.log:
            self.log = logging.getLogger(__name__)
            self.log.addHandler(logging.NullHandler())
        self.config = config
        self.datadir = os.path.expandvars(os.path.expanduser(self.config.get('datadir')))
        if self.datadir:
            if not os.access(self.datadir, os.W_OK | os.X_OK):
                #  Throw this early because we don't actually attempt
                #  access until a POST arrives.
                #
                raise Exception("Data directory '%s' is not writable" % (self.datadir))
            self.statefile = os.path.join(self.datadir, self.statefile_name)
            self.state = self.load_state()
            self.recording = True
        else:
            self.statfile = None
            self.state = {}
            self.recording = False

        #  This is set by fill().
        self.is_inet = None

        self.authorized_addrs = None
        if self.config.get('authaddrs') is not None:
            self.authorized_addrs = []
            for addr in self.config['authaddrs']:
                self.authorized_addrs.append(netaddr.IPNetwork(addr))

        self.plugins = self._import_plugins()
        self.event_set = None

    def iso8601(self, tim=None, **params):
        if tim is None:
            tim = time.time()
        local = params.get('local', self.config.get('timestamp_local', True))
        resolution = params.get('resolution', self.config.get('timestamp_resolution', 'msec'))
        terse = params.get('terse', self.config.get('timestamp_terse', False))
        if isinstance(tim, datetime):
            if tim.tzinfo is None or tim.tzinfo.utcoffset(tim) is None:
                if local:
                    dt = tim.replace(tzinfo=tz.tzlocal())
                else:
                    dt = tim.replace(tzinfo=tz.tzutc())
            else:
                dt = tim
        else:
            if local:
                dt = datetime.fromtimestamp(tim, tz.tzlocal())
            else:
                #  Set the utc timezone so we get tz-aware rather than naive
                dt = datetime.fromtimestamp(tim, tz.tzutc())
        if terse:
            t = dt.strftime("%Y%m%dT%H%M%S")
        else:
            t = dt.strftime("%Y-%m-%dT%H:%M:%S")
        if resolution.lower().startswith('ms'):
            t += '.%03d' % (int((dt.microsecond + 0.5) / 1000), )
        elif resolution.lower().startswith('us'):
            t += '.%06d' % (dt.microsecond, )
        tzs = dt.strftime("%z")
        if terse:
            if tzs == '+0000':
                tzs = 'Z'
        else:
            tzs = tzs[:3] + ':' + tzs[3:]
        return t + tzs

    def load_state(self):
        if not self.statefile:
            self.log.info("State file processing disabled")
            return {}
        try:
            with open(self.statefile, 'r') as f:
                prev_state = f.read()
        except Exception as e:
            self.log.warning("No previous state file '%s' -- %s", self.statefile, e)
            return {}
        try:
            return json.loads(prev_state)
        except Exception as e:
            self.log.warning("Parse failed on previous state file '%s' -- %s", self.statefile, e)
            return {}

    def save_state(self):
        if not self.statefile:
            self.log.debug("State file processing disabled")
            return
        temp = self.statefile + '.tmp'
        try:
            with open(temp, 'w') as f:
                f.write(json.dumps(self.state, indent=4))
        except Exception as e:
            self.log.error("Write failed to '%s' -- %s", temp, e)
            return
        try:
            os.rename(temp, self.statefile)
        except Exception as e:
            self.log.error("Rename of '%s' to '%s' failed -- %s", temp, self.statefile, e)

    def log_command(self, info, level=logging.DEBUG):
        self.log.log(level, "%s ...", info['_name'])
        for line in json.dumps(info, indent=4).splitlines():
            self.log.log(level, "    %s", line)

    def check_schedule(self, info):
        name = info['_name']
        props = self.properties.get(name)
        if not props:
            self.log.debug("No properties for '%s', skipping schedule check", name)
            return self.noop_response
        dev_mac = info['_raw']['DeviceMacId']
        desired_period = props.get('desired_period')
        if not desired_period:
            self.log.warning("No desired period for '%s', skipping schedule check", name)
            return self.noop_response
        event_name = props.get('event_name')
        if not event_name:
            self.log.warning("No event name for '%s', skipping schedule check", name)
            return self.noop_response
        prev_info = self.state.get(name)
        curr_ts = info['_timestamp']
        if prev_info and '_timestamp' in prev_info and prev_info['_timestamp']:
            prev_ts = prev_info['_timestamp']
        else:
            self.log.info("No previous timestamp for '%s', skipping schedule check", name)
            return self.noop_response
        delta = curr_ts - prev_ts
        if abs(delta - desired_period) < self.period_reset_tolerance:
            self.log.debug("Report delta %.1fs within tolerance for '%s', skipping schedule change", delta, event_name)
            return self.noop_response
        self.log.info("Delta of %.1fs for %s differs from desired %.0f, changing schedule",
                            delta, event_name, desired_period)
        content = self.set_schedule_template % (dev_mac, event_name, desired_period)
        for line in content.splitlines():
            self.log.debug("%s", line.rstrip())
        return (200, content, 'text/xml')

    def read_meter(self, item, info):
        """
        Returns a float value based on value, multiplier, and divisor int values,
        as is received from the device for items such as Demand (in kW) or
        SummationDelivered (in kWh).
    """
        name = info['_name']
        sys_timestamp = info['_timestamp']

        timestamp = info.get('TimeStamp')
        value = info.get(item)
        multiplier = info.get('Multiplier')
        divisor = info.get('Divisor')
        if value is None:
            raise Exception("Missing '%s' in %s" % (item, name,))
        if multiplier is None:
            raise Exception("Missing 'Multiplier' in %s" % (name,))
        if divisor is None:
            raise Exception("Missing 'Divisor' in %s" % (name,))
        result = float(value) * multiplier / divisor
        try:
            clock_delta = ', clock delta %.3fs' % (sys_timestamp - timestamp - self.time_t_offset_2000, )
        except Exception as e:
            self.log.warning("Could not convert TimeStamp %r to clock delta -- %s", timestamp, e)
            clock_delta = ''

        #  Best I can tell, we just have to know the units, the device doesn't indicate them.
        #
        self.log.debug("Result is %.3f %s%s",
                        result, 'kWh' if item == 'SummationDelivered' else 'kW', clock_delta)
        return result

    def snapshot(self, path, postmap=None, **params):
        """
        Returns a json-formatted snapshot of the current state.
    """
        q = httpd.merge_query(path, postmap)
        if 'fmt' in q:
            fmt = q['fmt'][0]
        else:
            fmt = 'json'
        fmt = fmt.lower()

        if fmt == 'json':
            json_params = {}
            try:
                json_params['indent'] = int(q.get('indent')[0])
            except:
                pass

            return (200, json.dumps(self.state, indent=4), 'application/json')
        else:
            return (415, 'Invalid fmt request "%s"' % (fmt,), 'text/plain')

    def process(self, path, postmap, **params):
        """
        Receives all POSTs from device via httpd module.
        This queues updates to listening processes and runs each
        plugin synchonously in order.  Both plugins and processes
        receive the same data. Plugins are passed the data as a dict.
        Processes receive it as netstring-encapsulated JSON (see
        https://en.wikipedia.org/wiki/Netstring).

        The data sent consists of the complete state from the device for all
        known message types.  A top-level tag '_last_element' points at the
        name of the last element that changed, triggering the event.

        Because each event is handled synchronously, all recipients will
        receive all changes in order.  Exceptions to this are:

        -  A maximum number of pending changes is kept for each process
           so a process that stalls for some period may lose data.

        -  A write error on a process socket causes all the data to be flushed
           and the connection dropped.  The process will receive the current
           state when it next connects.
    """
        if self.is_inet and self.authorized_addrs is not None and 'handler' not in params:
            self.log.error("Missing handler - cannot validate client address")
            return None
        if 'data' not in params:
            self.log.error("Missing payload from device")
            return None
        if self.is_inet and self.authorized_addrs is not None:
            client_ip = netaddr.IPAddress(params['handler'].client_address[0])
            self.log.debug("Checking client address %s", client_ip)
            authorized = False
            for net in self.authorized_addrs:
                if client_ip in net:
                    authorized = True
                    break
            if not authorized:
                self.log.warning("Unauthorized access from client at %s", client_ip)
                return None
        payload = params['data']
        try:
            dom = xml.dom.minidom.parseString(payload)
        except Exception as e:
            self.log.error("Payload parse failed -- %s", e, exc_info=True)
            self.log.error("Failed payload was ...")
            if len(payload) > 1000:
                payload = payload[:1000] + ' ...'
            for line in str(payload).splitlines():
                self.log.error("  ] %s", line)
            return
        self.log.debug("Payload parsed successfully ...")
        for line in dom.toprettyxml(indent="  ").splitlines():
            line = line.rstrip()
            if line:
                self.log.debug("  ] %s", line)

        resp = (200, '', 'text/plain')

        now = time.time()
        for node in dom.getElementsByTagName('rainforest'):
            header = {}
            header['_version'] = node.getAttribute('version')
            header['_mac'] = node.getAttribute('macId')
            rainforest_timestamp = node.getAttribute('timestamp')
            if rainforest_timestamp:
                try:
                    header['_timestamp'] = int(rainforest_timestamp.strip('s'))
                    self.log.debug("Rainforest %s v%s timestamp delta %.3f",
                                    header['_mac'], header['_version'], now - header['_timestamp'])
                except Exception as e:
                    self.log.warning("Could not load Rainforest timestamp '%s' -- %s",
                                                rainforest_timestamp, e)
                    header['_timestamp'] = None
            else:
                self.log.warning("No timestamp in rainforest POST xml")

            if node.nodeType != node.ELEMENT_NODE or not node.hasChildNodes():
                self.log.warning("XML rainforest node had no children")
                continue
            for command in node.childNodes:
                if command.nodeType != command.ELEMENT_NODE:
                    continue
                self.log.debug("XML item '%s' has command element '%s'", node.nodeName, command.nodeName)
                info = {}
                raw_info = {}
                props = self.properties.get(command.nodeName, {})
                for elem in command.childNodes:
                    if elem.nodeType != elem.ELEMENT_NODE:
                        continue
                    tag = elem.nodeName
                    if elem.childNodes:
                        val = elem.childNodes[0].nodeValue.strip()
                        valstr = val
                        if self.is_hex.match(val):
                            try:
                                val = int(val, 0)
                                #  Handle hex for negative 32 bit values.
                                if len(valstr) <= 10 and val > 0x7FFFFFFF:
                                    val -= 0x100000000
                            except:
                                pass
                    else:
                        val = ''
                        valstr = val
                    self.log.debug("%s %s = %r", command.nodeName, elem.nodeName, val)
                    info[tag] = val
                    raw_info[tag] = valstr
                info['_name'] = command.nodeName
                info['_raw'] = raw_info
                info['_timestamp'] = now
                vals = {}
                for reading in props.get('readings', []):
                    vals[reading] = self.read_meter(reading, info)
                if 'units' in props:
                    vals['_units'] = props['units']
                if len(vals) > 0:
                    info['_readings'] = vals
                resp = self.check_schedule(info)
                self.state[command.nodeName] = info
                self.state['_last_element'] = command.nodeName

            self.state['_last_update'] = now
            self.state['_timestamp'] = header['_timestamp']
            for tag in ['_mac', '_version']:
                if header[tag] != self.state.get(tag):
                    self.log.info("Rainforest %s value changed from %r to %s", tag, self.state.get(tag), header[tag])
                    self.state[tag] = header[tag]
        for plug, name in self.plugins:
            try:
                self.log.debug("Running plugin '%s' for command '%s'", name, self.state['_last_element'])
                plug.handle(self)
            except Exception as e:
                self.log.error("Plugin '%s' failed for '%s' -- %s",
                                name, self.state['_last_element'], e, exc_info=True)
        self.save_state()
        if self.event_set is not None:
            self.event_set.filter(self.state)
        return resp

    def event_listener(self, addr, proto=socket.AF_INET, queue=5):
        host = None
        port = None
        if addr.find(':') >= 0:
            host, portstr = addr.rsplit(':', 1)
            port = int(portstr)
        else:
            host = addr
        if not host:
            raise Exception("Invalid event listener address '%s'" % (addr,))
        if not port:
            port = def_events_port

        sock = socket.socket(proto)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, port))
        sock.listen(queue)

        return sock

    def fill(self):
        """
        Operate the service.  This never exits, so return is always via
        an exception.
    """
        service = httpd.HttpService()
        service.listen = self.config['listen']
        service.certfile = self.config.get('certfile')
        if 'timeout' in self.config:
            service.timeout = float(self.config['timeout'])
        httpd_server = httpd.server(service, log=self.log)
        httpd_server.register_post(r'/rest', self.process)
        httpd_server.register_get(r'/snap', self.snapshot)

        self.is_inet = (httpd_server.address_family in [socket.AF_INET, socket.AF_INET6])

        pset = poll.poll()
        pset.register(httpd_server, poll.POLLIN)

        #  Event handling has to be processed via poll because sockets are
        #  long-running and have to interact with content in the master.
        #  In this case, a socketserver instance in threaded or multiprocess
        #  mode is awkward.
        #
        if 'events' in self.config:
            event_listen = self.event_listener(self.config['events'])
            pset.register(event_listen, poll.POLLIN)
        else:
            event_listen = None

        try:
            with event.EventSet(pset, event_listen) as self.event_set:
                while True:
                    evlist = pset.poll(poll_timeout)

                    if evlist is None:
                        event_cnt = 0
                    else:
                        event_cnt = len(evlist)
                    if event_cnt > 0:
                        self.log.debug("%d poll event%s received", event_cnt, '' if event_cnt == 1 else 's')
                        for item, mask in evlist:
                            if item == httpd_server:
                                item.handle_request()
                            elif item == event_listen:
                                self.event_set.add()
                            elif isinstance(item, event.Event):
                                item.handle(mask, self.state)
                            else:
                                raise Exception("Unknown poll item %r" % item)
                    else:
                        self.log.debug("Idle")
                        self.event_set.idle()
        except Exception as e:
            self.log.error("Unexpected event -- %s", e, exc_info=True)
        finally:
            if event_listen:
                try:
                    event_listen.close()
                except:
                    pass
                event_listen = None
            try:
                httpd_server.close()
            except Exception as e:
                self.log.warning("Error closing htto server -- %s", e)

    def _import_plugins(self):
        """
        Load any plugins that can be found.

        For now, just look for plugins in the "plugin" subdir of the
        module's dir.  May want to ultimately have a "BARREL_PLUGIN_PATH"
        configuration.
    """
        plugins = []

        plugin_subdir = 'plugins'
        plugin_dir = os.path.join(os.path.dirname(__file__), plugin_subdir)
        self.log.debug("Scanning plugin dir '%s'", plugin_dir)
        candidates = []
        try:
            for fname in os.listdir(plugin_dir):
                path = os.path.join(plugin_dir, fname)
                if os.path.isfile(path):
                    name, ext = os.path.splitext(fname)
                    if ext not in set(['.py', '.pyc', '.pyo']):
                        self.log.debug("Ignoring non-python file '%s' for plugin", path)
                        continue
                    module_name = 'rainbarrel.' + plugin_subdir + '.' + name
                    if module_name in candidates:
                        self.log.debug("Plugin module '%s' already known", module_name)
                    else:
                        self.log.debug("Adding plugin module candidate '%s'", module_name)
                        candidates.append(module_name)
        except Exception as e:
            self.log.debug("Scan of plugin dir '%s' failed -- %s", dir, e)
        self.log.debug("Plugin candidates: %s", candidates)
        for name in candidates:
            try:
                m = importlib.import_module(name)
                self.log.debug("Loaded module '%s'", name)
                for elem, obj in inspect.getmembers(m):
                    if elem == 'Plugin':
                        #  Ignore the abstract class
                        continue
                    obj_name = name + '.' + elem
                    try:
                        if inspect.isclass(obj):
                            if issubclass(obj, plugin.Plugin):
                                plug = obj()
                                plugins.append((plug, obj_name))
                                self.log.info("Instantiated plugin class %s()", obj_name)
                    except Exception as e:
                        self.log.warning("Class instantiation of '%s' failed -- %s", name, e)
            except Exception as e:
                self.log.warning("Module load of '%s' failed -- %s", name, e)
        return plugins


text:
class DataCoordinator : public QObject
{
	Q_OBJECT

signals:
	void currentJobFinished() const;

public:
	explicit DataCoordinator(QObject* parent = nullptr);

	void setNetworkAccessManager(QNetworkAccessManager* nam)
	{ wq->setNetworkAccessManager(nam); }

	void refreshDatabase();
	void forceRederiveData()
	{
		db->deepScanForRedirects();
		emit currentJobFinished();
	}

	void exportData(const QString& exportDir)
	{
		db->exportWikiText(exportDir);
		emit currentJobFinished();
	}

	QAbstractTableModel* dbModel() const
	{ return db->dbModel(); }

private:
	Database* db;
	WikiQuerier* wq;
};

#endif // DATACOORDINATOR_H


text:
<?php

class M_Login extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function get_user(){
        $this->db->select('loginid');
        $this->db->from('adminlogintb');
        $query = $this->db->get();

        return $query->result();
    }

    function get_userid($email){
        $this->db->select('login_id');
        $this->db->from('adminlogintb');
        $this->db->where('username', $email);
        $query = $this->db->get();

        return $query->result();
    }

    function confirm_users_password($userid, $password){
        $query = $this->db->query('select * from adminlogintb where login_id =  "'.$userid.'"  and password =  "'.$password.'" ');
        /*$this->db->select('password');
        $this->db->from('login');
        $this->db->where('password', $password);
        $query = $this->db->get();*/

        return $query->result();
    }

    function confirm_users_details($username, $user_password){
        $query = $this->db->query('select * from adminlogintb where username =  "'.$username.'"  and password =  "'.$user_password.'" ');

        return $query->result();
    }

    function update_password(){

        /*$query = $this->db->query('update login set password = "'.sha1($this->input->post('new_pass', TRUE)).'" where ID = "'.$this->session->userdata('user_id').'"');

        return $this->db->set();*/
        $this->db->set('password', sha1($this->input->post('new_pass', TRUE)));
        $this->db->where('login_id', $this->session->userdata('user_id'));

        return $this->db->update('adminlogintb');

    }

    function update_user_password(){

        /*$query = $this->db->query('update login set password = "'.sha1($this->input->post('new_pass', TRUE)).'" where ID = "'.$this->session->userdata('user_id').'"');

        return $this->db->set();*/
        $this->db->set('password', sha1($this->input->post('new_pass', TRUE)));
        $this->db->where('user_id', $this->session->userdata('user_id'));

        return $this->db->update('userstb');

    }

    function confirm_members_password($userid, $password){
        $query = $this->db->query('select * from userstb where user_id =  "'.$userid.'"  and password =  "'.$password.'" ');
        /*$this->db->select('password');
        $this->db->from('login');
        $this->db->where('password', $password);
        $query = $this->db->get();*/

        return $query->result();
    }

    function confirm_members_details($username, $user_password){
        $query = $this->db->query('select * from userstb where username =  "'.$username.'"  and password =  "'.$user_password.'" ');

        return $query->result();
    }
}


text:
<form id="mercury_html_editor" style="width:650px">

  <textarea class="mercury-display-pane-container" rows="5" style="width:100%"></textarea>

    <fieldset class="buttons">

<input class="submit" name="commit" type="submit" value="Save and Replace"/>

    </fieldset>

</form>


text:
from sqlalchemy import MetaData, Table, Column, Integer, String

meta = MetaData()
meta.bind = db.session.bind

event = Table('event', meta,
              Column('id', Integer, primary_key=True),
              Column('external_id', String, nullable=False, unique=True),
              Column('name', String))
event.create()


text:
package apollo.upload;

import apollo.maven.MavenDeployer;
import apollo.predicators.PomFilePredictor;
import apollo.xml_handlers.XmlReformer;
import com.google.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class MavenUploader implements Uploader {

    private final PomFilePredictor pomFilePredictor;
    private final MavenDeployer mavenDeployer;
    private final XmlReformer xmlReformer;
    private static final Logger logger = LogManager.getLogger(MavenUploader.class);
    private static final int maxThreadNo = Runtime.getRuntime().availableProcessors();
    private static ExecutorService executor = Executors.newFixedThreadPool(maxThreadNo);

    @Inject
    public MavenUploader(PomFilePredictor pomFilePredictor, MavenDeployer mavenDeployer, XmlReformer xmlReformer) {
        this.pomFilePredictor = pomFilePredictor;
        this.mavenDeployer = mavenDeployer;
        this.xmlReformer = xmlReformer;
    }

    @Override
    public void uploadToRepository(Path pathToUpload) {

        logger.info("Starting to upload artifacts from " + pathToUpload.toString());
        try (Stream<Path> files = Files.walk(pathToUpload)){
            files.filter(pomFilePredictor).filter(path -> {
                try {
                    xmlReformer.prepareXmlToDeploy(path);
                    return true;
                } catch (Exception e) {
                    logger.error("Error uploading " + path + " : " + e);
                    return false;
                }
            }).forEach(path -> {
                Runnable uploadThread = new MavenUploadAsync(mavenDeployer, path);
                executor.submit(uploadThread);
            });
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }

        executor.shutdown();
        try {
            if (executor.awaitTermination(5, TimeUnit.DAYS)) {
                logger.info("Executor service has shut down");
            }
        } catch (InterruptedException e) {
            logger.info("Executor service interrupted");
        }
    }
}


text:
@interface ANTableControllerUpdateOperation ()

@property (nonatomic, strong) ANStorageUpdateModel* updateModel;
@property (nonatomic, assign, getter=isFinished) BOOL finished;
@property (nonatomic, assign, getter=isExecuting) BOOL executing;

@end

@implementation ANTableControllerUpdateOperation

@synthesize finished = _finished;
@synthesize executing = _executing;

#pragma mark - ANStorageUpdateTableOperationDelegate

- (void)storageUpdateModelGenerated:(ANStorageUpdateModel*)updateModel
{
    self.updateModel = updateModel;
}

- (void)start
{
    if (self.isCancelled)
    {
        self.finished = YES;
    }
    else
    {
        self.executing = YES;
        [self main];
    }
}

- (void)main
{
    self.executing = YES;
    if (!self.isCancelled)
    {
        if (!self.updateModel.isEmpty)
        {
            [self _performAnimatedUpdate:self.updateModel];
        }
        else
        {
            self.finished = YES;
            self.executing = NO;
        }
    }
}

#pragma mark - Private

- (void)_performAnimatedUpdate:(ANStorageUpdateModel*)update
{
    id<ANListControllerUpdateOperationDelegate> delegate = self.delegate;
    UITableView* tableView = (UITableView*)[delegate listView];
    if ([tableView isKindOfClass:[UITableView class]])
    {
        if (!update.isRequireReload)
        {
            id<ANListControllerConfigurationModelInterface> configurationModel = [delegate configurationModel];

            [CATransaction begin];
            [CATransaction setCompletionBlock:^{
                self.finished = YES;
                self.executing = NO;
            }];

            UITableViewRowAnimation insertSectionAnimation = UITableViewRowAnimationNone;
            UITableViewRowAnimation deleteSectionAnimation = UITableViewRowAnimationNone;
            UITableViewRowAnimation reloadSectionAnimation = UITableViewRowAnimationNone;
            UITableViewRowAnimation insertRowAnimation = UITableViewRowAnimationNone;
            UITableViewRowAnimation deleteRowAnimation = UITableViewRowAnimationNone;
            UITableViewRowAnimation reloadRowAnimation = UITableViewRowAnimationNone;

            if (self.shouldAnimate)
            {
                insertSectionAnimation = configurationModel.insertSectionAnimation;
                deleteSectionAnimation = configurationModel.deleteSectionAnimation;
                reloadSectionAnimation = configurationModel.reloadSectionAnimation;
                insertRowAnimation = configurationModel.insertRowAnimation;
                deleteRowAnimation = configurationModel.deleteRowAnimation;
                reloadRowAnimation = configurationModel.reloadRowAnimation;
            }

            [tableView beginUpdates];

            [tableView insertSections:update.insertedSectionIndexes withRowAnimation:insertSectionAnimation];
            [tableView deleteSections:update.deletedSectionIndexes withRowAnimation:deleteSectionAnimation];
            [tableView reloadSections:update.updatedSectionIndexes withRowAnimation:reloadSectionAnimation];

            [update.movedRowsIndexPaths enumerateObjectsUsingBlock:^(ANStorageMovedIndexPathModel* obj, __unused NSUInteger idx, __unused BOOL *stop) {

                if (![update.deletedSectionIndexes containsIndex:(NSUInteger)obj.fromIndexPath.section])
                {
                    [tableView moveRowAtIndexPath:obj.fromIndexPath toIndexPath:obj.toIndexPath];
                }
            }];

            [tableView insertRowsAtIndexPaths:update.insertedRowIndexPaths withRowAnimation:insertRowAnimation];
            [tableView deleteRowsAtIndexPaths:update.deletedRowIndexPaths withRowAnimation:deleteRowAnimation];
            [tableView reloadRowsAtIndexPaths:update.updatedRowIndexPaths withRowAnimation:reloadRowAnimation];

            [tableView endUpdates];
            [CATransaction commit];
        }
        else
        {
            self.finished = YES;
            self.executing = NO;
            [delegate storageNeedsReloadWithIdentifier:self.name];
        }
    }
    else
    {
        NSAssert(NO, @"You assigned not a UITableView, this item can't be updated");
    }
}

#pragma mark - Getters / Setters

- (void)setFinished:(BOOL)finished
{
    if (_finished != finished)
    {
        [self willChangeValueForKey:NSStringFromSelector(@selector(isFinished))];
        _finished = finished;
        [self didChangeValueForKey:NSStringFromSelector(@selector(isFinished))];
    }
}

- (void)setExecuting:(BOOL)executing
{
    if (!_executing != executing)
    {
        [self willChangeValueForKey:NSStringFromSelector(@selector(isExecuting))];
        _executing = executing;
        [self didChangeValueForKey:NSStringFromSelector(@selector(isExecuting))];
    }
}

@end


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid href: path-leading-space</title>


text:
"""Glimpse network.

Glimpse network class builds feature representations based on glimpses of an
image and locations of glimpses.

The glimpse network receives two inputs image and location on the image. Image
locations are in the interval of [-1, 1] where points:
(-1, -1): upper left corner.
(-1, 1): upper right corner.
(1, 1): lower right corner.
(1, -1): lower left corner.
Glimpses are extracted with different resolutions at the provided location.
Then, glimpses are processed by convolutional layers.

"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v1 as tf

from saccader import model_utils
from saccader import utils
from tensorflow_models.slim.nets import nets_factory

class GlimpseNetwork(object):
  """Glimpse network.

  Network that receives an image and location and extracts representation from
  a glimpse of the image at that location.

  Attributes:
    network_type: (String) Network type.
    glimpse_shape: 2-D tuple of integers indicating glimpse shape.
    num_resolutions: (Integer) Number of image resolutions used.
    output_dims: (Integer) indicating network output dimensionality.
    regularizer: Regularizer for network.
    normalization_type: Normalization for layers either None, 'batch', or
      'layer'.
    residual_blocks_per_group: (Integer) length of one residual block.
    number_groups: (Integer) number of residual groups.
    num_units_fc_layers: List with number of units for fully connected layers
      (None or []: no fully connect layers are used).
    init_conv_channels: Starting size of convolutional channels.
    widening_factor: Network widening factor from init_conv_channels (k variable
      in the wide resnet paper).
    dropout_rate: Number [0, 1] indicating drop out rate.
    activation: Activation function (None: for linear network).
    global_average_pool: (boolean) Use global average pooling.
    zero_pad: (boolean) Skip connection by zero padding or 1x1 convolution.
    var_list: list of network variables.
    init_op: initialization operations for model variables.
    residual_blocks_per_group: Number of residual blacks per group (N variable
      in the wide resnet paper arXiv:1605.07146).
    number_groups: Number of groups in the network.
    conv_size: (integer) Convolution filter size.
    apply_stop_gradient: (boolean) If True, prevent gradient from propagating
      through the glimpse extraction procedure.
  """

  def __init__(self, config):
    """Init.

    Args:
      config: ConfigDict object with model parameters (see dram_config.py).
    """
    self.network_type = config.network_type
    if self.network_type == "wrn":
      self.regularizer = config.regularizer
      self.normalization_type = config.normalization_type
      self.residual_blocks_per_group = config.residual_blocks_per_group
      self.number_groups = config.number_groups
      self.init_conv_channels = config.init_conv_channels
      self.widening_factor = config.widening_factor
      self.dropout_rate = config.dropout_rate
      self.zero_pad = config.zero_pad
      self.activation = config.activation
      self.global_average_pool = config.global_average_pool

    self.glimpse_shape = config.glimpse_shape
    self.num_resolutions = config.num_resolutions  # number of resolutions.
    self.output_dims = config.output_dims
    self.apply_stop_gradient = config.apply_stop_gradient

    # Call once to create network variables. Then reuse variables later.
    self.var_list = []
    self.init_op = []

  def collect_variables(self):
    """Collects model variables.

    Populates self.var_list with model variables and self.init_op with
    variables' initializer. This function is only called once with __call__.

    """
    self.var_list = [
        v for v in tf.global_variables() if "glimpse_network" in v.name
    ]
    self.init_op = tf.variables_initializer(var_list=self.var_list)

  def extract_glimpses(self, images, locations):
    """Extracts fovea-like glimpses.

    Args:
      images: 4-D Tensor of shape [batch, height, width, channels].
      locations: 2D Tensor of shape [batch, 2] with glimpse locations. Locations
        are in the interval of [-1, 1] where points:
        (-1, -1): upper left corner.
        (-1, 1): upper right corner.
        (1, 1): lower right corner.
        (1, -1): lower left corner.

    Returns:
      glimpses: 5D tensor of size [batch, # glimpses, height, width, channels].
    """
    # Get multi resolution fields of view (first is full resolution)
    image_shape = tf.cast(tf.shape(images)[1:3], dtype=tf.float32)
    start = tf.cast(self.glimpse_shape[0], dtype=tf.float32) / image_shape[0]
    fields_of_view = tf.cast(tf.lin_space(start, 1., self.num_resolutions),
                             dtype=tf.float32)
    receptive_fields = [self.glimpse_shape] + [
        tf.cast(fields_of_view[i] * image_shape, dtype=tf.int32)
        for i in range(1, self.num_resolutions)
    ]
    images_glimpses_list = []
    for field in receptive_fields:
      # Extract a glimpse with specific shape and scale.
      images_glimpse = utils.extract_glimpse(
          images, size=field, offsets=locations)
      # Bigger receptive fields have lower resolution.
      images_glimpse = tf.image.resize_images(
          images_glimpse, size=self.glimpse_shape)
      # Stop gradient
      if self.apply_stop_gradient:
        images_glimpse = tf.stop_gradient(images_glimpse)
      images_glimpses_list.append(images_glimpse)
    return images_glimpses_list

  def __call__(self, images, locations, is_training, use_resolution):
    """Builds glimpse network.

    Args:
      images: 4-D Tensor of shape [batch, height, width, channels].
      locations: 2D Tensor of shape [batch, 2] with glimpse locations.
      is_training: (Boolean) training or inference mode.
      use_resolution: (List of Boolean of size num_resolutions) Indicates which
        resolutions to use from high (small receptive field)
        to low (wide receptive field).

    Returns:
      output: Network output reflecting representation learned from glimpses
        and locations.
      endpoints: Dictionary with activations at different layers.
    """
    if self.var_list:
      reuse = True
    else:
      reuse = False

    tf.logging.info("Build Glimpse Network")
    endpoints = {}

    # Append position channels.
    images_with_position = tf.concat(
        [images, utils.position_channels(images)], axis=3)

    images_glimpses_list = self.extract_glimpses(images_with_position,
                                                 locations)
    endpoints["images_glimpses_list"] = [
        g[:, :, :, 0:3] for g in images_glimpses_list
    ]
    endpoints["model_input_list"] = images_glimpses_list
    # Concatenate along channels axis.
    images_glimpses_list_ = []
    for use, g in zip(use_resolution, images_glimpses_list):
      if not use:
        # If masking is required, use the spatial mean per channel.
        images_glimpses_list_.append(0. * g + tf.stop_gradient(
            tf.reduce_mean(g, axis=[1, 2], keepdims=True)))
      else:
        images_glimpses_list_.append(g)

    images_glimpses_list = images_glimpses_list_

    images_glimpses = tf.concat(images_glimpses_list, axis=3)
    net = images_glimpses

    if self.network_type == "wrn":
      with tf.variable_scope("glimpse_network", reuse=reuse):
        output, endpoints_ = model_utils.build_wide_residual_network(
            net,
            self.output_dims,
            residual_blocks_per_group=self.residual_blocks_per_group,
            number_groups=self.number_groups,
            init_conv_channels=self.init_conv_channels,
            widening_factor=self.widening_factor,
            dropout_rate=self.dropout_rate,
            expand_rate=2,
            conv_size=3,
            is_training=is_training,
            activation=self.activation,
            regularizer=self.regularizer,
            normalization_type=self.normalization_type,
            zero_pad=self.zero_pad,
            global_average_pool=self.global_average_pool)
    else:
      network = nets_factory.get_network_fn(
          self.network_type, num_classes=self.output_dims,
          is_training=is_training)
      output, endpoints_ = network(net, scope="glimpse_network", reuse=reuse)
      if self.output_dims is None:
        # Global average of activations.
        output = tf.reduce_mean(output, [1, 2])

    endpoints.update(endpoints_)

    if not reuse:
      self.collect_variables()

    return output, endpoints


text:
class EventMachine::MQTTSN::ServerConnection < EventMachine::MQTT::Connection
  attr_accessor :gateway_handler
  attr_accessor :client_address
  attr_accessor :client_port
  attr_accessor :client_id
  attr_accessor :pending_requests

  def initialize(gateway_handler, client_address, client_port)
    @client_address = client_address
    @client_port = client_port
    @gateway_handler = gateway_handler
    @topic_id = 0
    @topic_map = {}
    @pending_requests = {}
  end

  # TCP connection to server has closed
  def unbind
    @gateway_handler.disconnect(self)
  end

  # Incoming packet from server has been received
  def process_packet(packet)
    if packet.class == MQTT::Packet::Connack and packet.return_code == 0
      @state = :connected
    end

    @gateway_handler.relay_from_server(self, packet)
  end

  # Get the topic ID for a topic name
  def get_topic_id(name)
    if name.length == 2
      return :short, name
    else
      # FIXME: improve this
      @topic_map.each_pair do |key,value|
        if value == name
          return :normal, key
        end
      end
      @topic_id += 1
      @topic_map[@topic_id] = name
      return :normal, @topic_id
    end
  end

  # Get the topic name for a topic ID
  def get_topic_name(id)
    @topic_map[id]
  end

  # Add a packet to a list of messages that we are expecting a reply to
  def add_to_pending(packet)
    @pending_requests[packet.id] = {
      :packet => packet,
      :time => Time.now
    }
  end

  # Remove a packet that we have now received a reply to
  def remove_from_pending(id)
    if @pending_requests.has_key?(id)
      request = @pending_requests[id]
      @pending_requests.delete(id)
      return request[:packet]
    end
  end

  # Politely close the connection to the MQTT server
  def disconnect
    send_packet(MQTT::Packet::Disconnect.new)
    @state = :disconnected
    close_connection_after_writing
  end
end


text:
<?php

namespace ZendTest\Code\Reflection;

use Zend\Code\Reflection;

/**
 * @group      Zend_Reflection
 * @group      Zend_Reflection_DocBlock
 * @group      Zend_Reflection_DocBlock_Tag
 */
class ReflectionDocBlockTagTest extends \PHPUnit_Framework_TestCase
{
    public function testTagDescriptionIsReturned()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5');

        $authorTag = $classReflection->getDocBlock()->getTag('author');
        $this->assertEquals('Ralph Schindler', $authorTag->getAuthorName());
        $this->assertEquals('ralph.schindler@zend.com', $authorTag->getAuthorEmail());
    }

    public function testTagShouldAllowJustTagNameInDocBlockTagLine()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass6');

        $tag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('emptyTag');
        $this->assertEquals($tag->getName(), 'emptyTag', 'Factory First Match Failed');
    }

    public function testTagShouldAllowMultipleWhitespacesBeforeDescription()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass6');

        $tag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('descriptionTag');
        $this->assertNotEquals('          A tag with just a description', $tag->getContent(), 'Final Match Failed');
        $this->assertEquals('A tag with just a description', $tag->getContent(), 'Final Match Failed');
    }

    public function testToString()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass6');

        $tag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('descriptionTag');

        $expectedString = 'DocBlock Tag [ * @descriptionTag ]' . PHP_EOL;

        $this->assertEquals($expectedString, (string) $tag);
    }

    public function testTypeParam()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('param');

        $this->assertEquals($paramTag->getType(), 'int');
    }

    public function testVariableName()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('param');
        $this->assertEquals($paramTag->getVariableName(), '$one');
    }

    public function testAllowsMultipleSpacesInDocBlockTagLine()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass6');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('param');

        $this->assertEquals($paramTag->getType(), 'int', 'Second Match Failed');
        $this->assertEquals($paramTag->getVariableName(), '$var', 'Third Match Failed');
        $this->assertEquals($paramTag->getDescription(),'Description of $var', 'Final Match Failed');
    }

    /**
     * @group ZF-8307
     */
    public function testNamespaceInParam()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass7');
        $paramTag        = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('param');

        $this->assertEquals('Zend\Foo\Bar', $paramTag->getType());
        $this->assertEquals('$var', $paramTag->getVariableName());
        $this->assertEquals('desc', $paramTag->getDescription());
    }

    public function testType()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('return');
        $this->assertEquals($paramTag->getType(), 'mixed');
    }

    public function testAllowsMultipleSpacesInDocBlockTagLine2()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass6');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('return');

        $this->assertEquals($paramTag->getType(), 'string', 'Second Match Failed');
        $this->assertEquals($paramTag->getDescription(), 'Description of return value', 'Final Match Failed');
    }

    /**
     * @group ZF-8307
     */
    public function testReturnClassWithNamespace()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass7');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('return');

        $this->assertEquals('Zend\Code\Reflection\DocBlock', $paramTag->getType());
    }
}


text:
'use strict';

var fs = require('graceful-fs');
// [tip] BOM(Byte Order Mark),字节顺序标记
// [tip] 出现在文本文件头部,Unicode编码标准中用于标识文件是采用哪种格式的编码
var removeBomBuffer = require('remove-bom-buffer');

function bufferFile(file, optResolver, onRead) {
  fs.readFile(file.path, onReadFile);

  function onReadFile(readErr, data) {
    if (readErr) {
      return onRead(readErr);
    }

    var removeBOM = optResolver.resolve('removeBOM', file);
    if (removeBOM) {
      file.contents = removeBomBuffer(data);
    } else {
      file.contents = data;
    }

    onRead();
  }
}

module.exports = bufferFile;


text:
import cv2
import sys

cascPath = 'haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture(2)
thersold=18000

while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(120, 120),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
    	print w*h
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()


text:
package edu.uw.zookeeper.netty;

import java.util.Collection;
import java.util.Collections;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.channel.Channel;
import edu.uw.zookeeper.common.Factory;
import edu.uw.zookeeper.common.ParameterizedFactory;
import edu.uw.zookeeper.net.Codec;
import edu.uw.zookeeper.net.CodecConnection;
import edu.uw.zookeeper.net.Connection;

public class ChannelCodecConnection<I,O,T extends Codec<I,? extends O,? extends I,?>> extends AbstractChannelConnection<I,O,ChannelCodecConnection<I,O,T>> implements CodecConnection<I,O,T,ChannelCodecConnection<I,O,T>> {

    public static <I,O,T extends Codec<I,O,? extends I,? extends O>, C extends Connection<?,?,?>> ParameterizedFactory<Channel, C> factory(
            final Factory<? extends T> codecFactory,
            final ParameterizedFactory<CodecConnection<I,O,T,?>, C> connectionFactory) {
        return new ParameterizedFactory<Channel, C>() {
            @Override
            public C get(Channel channel) {
                T codec = codecFactory.get();
                ChannelCodecConnection<I,O,T> connection = ChannelCodecConnection.defaults(codec, channel);
                return connectionFactory.get(connection);
            }
        };
    }

    public static <I,O,T extends Codec<I,O,? extends I,? extends O>> ChannelCodecConnection<I,O,T> defaults(
            T codec,
            Channel channel) {
        Collection<Connection.Listener<? super O>> listeners = Collections.emptySet();
        return withListeners(codec, channel, listeners);
    }

    public static <I,O,T extends Codec<I,O,? extends I,? extends O>> ChannelCodecConnection<I,O,T> withListeners(
            T codec,
            Channel channel,
            Collection<? extends Connection.Listener<? super O>> listeners) {
        Logger logger = LogManager.getLogger(ChannelCodecConnection.class);
        EventfulHandler<? extends O> eventful = EventfulHandler.withLogger(codec.decodeType(), logger);
        ConnectionStateHandler state = ConnectionStateHandler.withLogger(logger);
        return newInstance(codec, channel, eventful, state, listeners, logger);
    }

    public static <I,O,T extends Codec<I,O,? extends I,? extends O>> ChannelCodecConnection<I,O,T> newInstance(
            T codec,
            Channel channel,
            EventfulHandler<? extends O> eventful,
            ConnectionStateHandler state,
            Collection<? extends Connection.Listener<? super O>> listeners,
            Logger logger) {
        return new ChannelCodecConnection<I,O,T>(codec, channel, eventful, state, listeners, logger);
    }

    protected final T codec;

    protected ChannelCodecConnection(
            T codec,
            Channel channel,
            EventfulHandler<? extends O> eventful,
            ConnectionStateHandler state,
            Collection<? extends Connection.Listener<? super O>> listeners,
            Logger logger) {
        super(channel, eventful, state, listeners, logger);
        this.codec = codec;

        DecoderHandler.toPipeline(
                DecoderHandler.withDecoder(codec, logger),
                EncoderHandler.toPipeline(
                        EncoderHandler.withEncoder(codec, logger),
                        channel.pipeline()));
    }

    @Override
    public T codec() {
        return codec;
    }

    @Override
    protected ChannelCodecConnection<I,O,T> self() {
        return this;
    }
}


text:
import React from "react";
import ReactDOM from "react-dom";
import {HashRouter, Route, Switch} from "react-router-dom";
import {Provider} from "react-redux";
import injectTapEventPlugin from 'react-tap-event-plugin';
import configureStore from "./js/store/ConfigureStore";
import {appStartUp} from "./js/store/GlobalAction";
import {MuiThemeProvider} from "material-ui";
import Location from "./js/constant/Location";
import App from "./js/view/App";
import Login from "./js/view/Login";
import Home from "./js/view/Home";
import 'sha1/sha1';
import "font-awesome/css/font-awesome.min.css"
import "./css/style.css";

const store = configureStore();
window.store = store;

injectTapEventPlugin();

const rootRoute = (
    <Switch>
      <Route path={Location.LOGIN} component={Login}/>
      <Route path={Location.ROOT} component={App}/>
      <Route path={Location.DEFAULT} component={Home}/>
    </Switch>
);

const render = () => {
  ReactDOM.render(
      <MuiThemeProvider>
        <Provider store={store}>
          <HashRouter onUpdate={console.log("Changing route")}>
            {rootRoute}
          </HashRouter>
        </Provider>
      </MuiThemeProvider>,
      document.getElementById('root')
  );
}

console.log('App Start Up');
store.dispatch(appStartUp(render));


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    BRTabBarController *tabBarVC = [[BRTabBarController alloc] init];
    //BRLoginViewController *loginVC = [[BRLoginViewController alloc] init];
    self.window.rootViewController = tabBarVC;
    [self.window makeKeyAndVisible];
    // 广告视图
    //BRADView *adView = [[BRADView alloc]initWithFrame:SCREEN_BOUNDS];
    //[self.window addSubview:adView];

    [[BRLocationManager sharedBRLocationManager] getGPS:^(NSString *lat, NSString *lon) {
        NSLog(@"当前位置的经纬度:(%@, %@)", lat, lon);
    }];

    // 初始化友盟控件
//    [self setupUMeung];

    return YES;
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//    BOOL result = [UMSocialSnsService handleOpenURL:url];
//    if (result == FALSE) {
//        //调用其他SDK,例如支付宝SDK等
//    }
//    return result;
//}

@end


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

 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd">
    <page name="CheckoutCart" mca="checkout/cart/index" module="Magento_Checkout">
        <block name="cartBlock" class="Magento\Checkout\Test\Block\Cart" locator="//div[contains(@class, 'column main')]" strategy="xpath"/>
        <block name="braintreePaypalBlock" class="Magento\Braintree\Test\Block\Paypal\PopupWindow" locator="body" strategy="xpath"/>
    </page>
</config>


text:
this.transition(
  this.between({childOf: '#liquid-with-demo'}),
  this.use('rotateBelow')
);


text:
<?php

declare(strict_types=1);

namespace Mindy\Orm\Tests\Fields;

use Mindy\Orm\Tests\Models\Blogger;
use Mindy\Orm\Tests\Models\Category;
use Mindy\Orm\Tests\Models\Group;
use Mindy\Orm\Tests\Models\Membership;
use Mindy\Orm\Tests\Models\Product;
use Mindy\Orm\Tests\Models\ProductList;
use Mindy\Orm\Tests\Models\Project;
use Mindy\Orm\Tests\Models\ProjectMembership;
use Mindy\Orm\Tests\Models\User;
use Mindy\Orm\Tests\Models\Worker;
use Mindy\Orm\Tests\OrmDatabaseTestCase;
use Mindy\QueryBuilder\Utils\TableNameResolver;

abstract class ManyToManyFieldTest extends OrmDatabaseTestCase
{
    public $prefix = '';

    protected function getModels()
    {
        return [
            new Category(),
            new ProductList(),
            new Product(),
            new Group(),
            new Membership(),
            new User(),
            new Project(),
            new ProjectMembership(),
            new Worker(),
            new Blogger(),
        ];
    }

    public function testTableNames()
    {
        $tables = $this->connection->getSchemaManager()->listTableNames();
        $this->assertTrue(in_array('product_list', $tables, true));
    }

    public function testSimple()
    {
        $category = new Category();
        $category->name = 'Toys';
        $category->save();

        $product = new Product();
        $product->name = 'Bear';
        $product->price = 100;
        $product->description = 'Funny white bear';
        $product->category = $category;

        $this->assertNull($product->pk);

        // General error: 1 no such table: product_list fix for sqlite
        $product->setConnection($this->connection);
        $lists = $product->lists;
        $lists->getModel()->setConnection($this->connection);

        // TODO тут нужно выбрасывать исключение потому что обращаемся к связанным данным у новой(!) не сохраненной модели
        $this->assertEquals(0, $product->lists->count());
        $this->assertEquals([], $product->lists->all());
        // TODO тут нужно выбрасывать исключение потому что обращаемся к связанным данным у новой(!) не сохраненной модели

        $this->assertTrue($product->save());
        $this->assertEquals(1, $product->pk);
        $this->assertEquals(1, $product->id);

        $list = new ProductList();
        $this->assertTrue($list->getIsNewRecord());

        $list->name = 'qwe';
        $this->assertTrue($list->save());
        $this->assertFalse($list->getIsNewRecord());
        $this->assertEquals(1, $list->id);
        $this->assertEquals(1, $list->pk);

        $list->products->link($product);

        $this->assertEquals(1, ProductList::objects()->count());
        $this->assertEquals(1, $product->lists->count());
        $this->assertEquals(1, count($product->lists->all()));

        $new = Product::objects()->get(['id' => 1]);
        $this->assertFalse($new->getIsNewRecord());
        $this->assertEquals(1, $new->id);
        $this->assertEquals(1, $new->pk);

//        $this->assertSql("SELECT [[product_list_1]].* FROM [[product_list]] AS [[product_list_1]] LEFT JOIN [[product_product_list]] AS [[product_product_list_1]] ON [[product_product_list_1]].[[product_list_id]]=[[product_list_1]].[[id]] WHERE ([[product_product_list_1]].[[product_id]]=@1@)",
//            $new->lists->allSql());
        $this->assertEquals(1, count($new->lists->all()));
    }

    public function testVia()
    {
        $group = new Group();
        $group->name = 'Administrators';
        $this->assertNull($group->pk);
        $this->assertInstanceOf('\Mindy\Orm\ManyToManyManager', $group->users);
        $this->assertEquals(0, $group->users->count());
        $this->assertEquals([], $group->users->all());

        $this->assertTrue($group->save());
        $this->assertEquals(1, $group->pk);

        $user = new User();
        $user->username = 'Anton';
        $user->password = 'VeryGoodP@ssword';
        $this->assertTrue($user->save());

        $this->assertEquals(0, count($group->users->all()));

        $group->users->link($user);
        $this->assertEquals(1, count($group->users->all()));

        $new = Group::objects()->get(['id' => 1]);
        $this->assertEquals(1, count($new->users->all()));

        $memberships = Membership::objects()->filter(['group_id' => 1, 'user_id' => 1])->all();
        $this->assertEquals(1, count($memberships));
    }

    public function testSet()
    {
        $category = new Category();
        $category->name = 'Toys';
        $category->save();

        $product = new Product();
        $product->name = 'Bear';
        $product->price = 100;
        $product->description = 'Funny white bear';
        $product->category = $category;

        $product->save();

        $list = new ProductList();
        $list->name = 'Toys';
        $list->save();

        $pk = $list->pk;

        // General error: 1 no such table: product_list fix for sqlite
        $product->setConnection($this->connection);
        $lists = $product->lists;
        $lists->getModel()->setConnection($this->connection);

        // Test array of Models
        $product->lists = [$list];
        $product->save(['lists']);
        $this->assertEquals(1, $product->lists->count());

//        // Test empty array
        $product->lists = [];
        $product->save(['lists']);
        $this->assertEquals(0, $product->lists->count());

        // Test array of pk
        $product->lists = [$pk];
        $product->save(['lists']);
        $this->assertEquals(1, $product->lists->count());

        // Test clean()
        $product->lists->clean();
        $this->assertEquals(0, $product->lists->count());
    }

    public function testLink()
    {
        $category = new Category(['name' => 'Toys']);
        $this->assertTrue($category->save());

        $product = new Product([
            'name' => 'Bear',
            'price' => 100,
            'description' => 'Funny white bear',
            'category' => $category,
        ]);
        $this->assertTrue($product->save());

        $list = new ProductList(['name' => 'Toys']);
        $this->assertTrue($list->save());

        // General error: 1 no such table: product_list fix for sqlite
        $product->setConnection($this->connection);
        $lists = $product->lists;
        $lists->getModel()->setConnection($this->connection);

        $this->assertEquals(0, $product->lists->count());
        $product->lists = [$list];
        $product->save();
        $this->assertEquals(1, $product->lists->count());

        $product->lists->unlink($list);
        $product->save();
        $this->assertEquals(0, $product->lists->count());
    }

    public function testCross()
    {
        $category = new Category();
        $category->name = 'Toys';
        $category->save();

        $product_bear = new Product();
        $product_bear->category = $category;
        $product_bear->name = 'Bear';
        $product_bear->price = 100;
        $product_bear->description = 'Funny white bear';
        $product_bear->save();

        $product_rabbit = new Product();
        $product_rabbit->category = $category;
        $product_rabbit->name = 'Rabbit';
        $product_rabbit->price = 110;
        $product_rabbit->description = 'Rabbit with carrot';
        $product_rabbit->save();

        $this->assertInstanceOf('\Mindy\Orm\ManyToManyManager', $product_rabbit->lists);

        // General error: 1 no such table: product_list fix for sqlite
        $product_rabbit->setConnection($this->connection);
        $product_rabbit->lists->getModel()->setConnection($this->connection);
        $this->assertEquals(0, $product_rabbit->lists->count());

        $best_sellers = new ProductList();
        $best_sellers->name = 'Best sellers';
        $best_sellers->save();

        // General error: 1 no such table: product_list fix for sqlite
        $best_sellers->setConnection($this->connection);
        $best_sellers->products->getModel()->setConnection($this->connection);

        $this->assertEquals(0, $best_sellers->products->count());

        $best_sellers->products->link($product_rabbit);

        $this->assertEquals(1, $best_sellers->products->count());
        $this->assertEquals(1, $product_rabbit->lists->count());

        $product_bear->lists->link($best_sellers);

        $this->assertEquals(2, $best_sellers->products->count());
        $this->assertEquals(1, $product_bear->lists->count());
    }

    public function testExtraLinkRecords()
    {
        $product = new Product();
        $product->name = 'Bear';
        $product->price = 100;
        $product->description = 'Funny white bear';
        $product->save();

        $list1 = new ProductList();
        $list1->name = 'Toys';
        $list1->save();

        $list2 = new ProductList();
        $list2->name = 'Trash';
        $list2->save();

        $this->assertEquals(1, Product::objects()->count());
        $this->assertEquals(2, ProductList::objects()->count());
        $tableName = $product->getField('lists')->getTableName();
        $tableName = TableNameResolver::getTableName($tableName);
        $cmd = $this->getConnection()->query('SELECT * FROM '.$tableName);
        $all = $cmd->fetchAll();
        $this->assertEquals([], $all);
        $this->assertEquals(0, count($all));

        $product->lists = [$list1];
        $product->save();

        $cmd = $this->getConnection()->query('SELECT * FROM '.$tableName);
        $all = $cmd->fetchAll();
        $this->assertEquals([
            ['product_id' => 1, 'product_list_id' => 1],
        ], $all);
        $this->assertEquals(1, count($all));

        $product->lists = [$list2];
        $product->save();

        $cmd = $this->getConnection()->query("SELECT * FROM {$tableName}");
        $all = $cmd->fetchAll();
        $this->assertEquals([
            ['product_id' => 1, 'product_list_id' => 2],
        ], $all);
        $this->assertEquals(1, count($all));

        $product->lists = [$list1];
        $product->save();

        $cmd = $this->getConnection()->query("SELECT * FROM {$tableName}");
        $all = $cmd->fetchAll();
        $this->assertEquals([
            ['product_id' => 1, 'product_list_id' => 1],
        ], $all);
        $this->assertEquals(1, count($all));

        $product->lists = [$list1, $list1, $list1];
        $product->save();

        $cmd = $this->getConnection()->query("SELECT * FROM {$tableName}");
        $all = $cmd->fetchAll();
        $this->assertEquals([
            ['product_id' => 1, 'product_list_id' => 1],
            ['product_id' => 1, 'product_list_id' => 1],
            ['product_id' => 1, 'product_list_id' => 1],
        ], $all);
        $this->assertEquals(3, count($all));
    }

    public function testViaOrder()
    {
        $firstProject = new Project();
        $firstProject->name = 'Building';
        $firstProject->save();

        $secondProject = new Project();
        $secondProject->name = 'Logistic';
        $secondProject->save();

        $firstWorker = new Worker();
        $firstWorker->name = 'Mark';
        $firstWorker->save();

        $secondWorker = new Worker();
        $secondWorker->name = 'Alex';
        $secondWorker->save();

        (new ProjectMembership([
            'project' => $firstProject,
            'worker' => $firstWorker,
            'position' => 1,
            'curator' => $secondWorker,
        ]))->save();

        (new ProjectMembership([
            'project' => $firstProject,
            'worker' => $secondWorker,
            'position' => 2,
            'curator' => $firstWorker,
        ]))->save();

        $this->assertEquals([
            [
                'id' => '1',
                'project_id' => '1',
                'worker_id' => '1',
                'position' => '1',
                'curator_id' => '2',
            ],
            [
                'id' => '2',
                'project_id' => '1',
                'worker_id' => '2',
                'position' => '2',
                'curator_id' => '1',
            ],
        ], ProjectMembership::objects()->asArray()->all());

        $qs = Worker::objects()->filter(['projects__id__in' => [$firstProject->id]])->order(['projects__through__position'])->asArray();
        $this->assertSql('SELECT [[worker_1]].* FROM [[worker]] AS [[worker_1]]
LEFT JOIN [[project_membership]] AS [[project_membership_1]] ON [[project_membership_1]].[[worker_id]]=[[worker_1]].[[id]]
LEFT JOIN [[project]] AS [[project_1]] ON [[project_1]].[[id]]=[[project_membership_1]].[[project_id]]
WHERE ([[project_1]].[[id]] IN (1))
ORDER BY [[project_membership_1]].[[position]] ASC', $qs->allSql());
        $this->assertEquals([
            ['id' => '1', 'name' => 'Mark'],
            ['id' => '2', 'name' => 'Alex'],
        ], $qs->asArray()->all());

        $this->assertEquals([
            ['id' => '2', 'name' => 'Alex'],
            ['id' => '1', 'name' => 'Mark'],
        ], Worker::objects()->filter(['projects__id__in' => [$firstProject->id]])->order(['-projects__through__position'])->asArray()->all());

        $this->assertEquals([
            ['id' => '1', 'name' => 'Mark'],
            ['id' => '2', 'name' => 'Alex'],
        ], Worker::objects()->order(['projects__through__position'])->asArray()->all());

        $this->assertEquals([
            ['id' => '2', 'name' => 'Alex'],
            ['id' => '1', 'name' => 'Mark'],
        ], Worker::objects()->order(['-projects__through__position'])->asArray()->all());

        $this->assertEquals([
            ['id' => '2', 'name' => 'Alex'],
        ], Worker::objects()->filter(['projects__through__curator' => $firstWorker])->asArray()->all());

        $this->assertEquals([
            ['id' => '1', 'name' => 'Mark'],
        ], Worker::objects()->filter(['projects__through__curator' => $secondWorker])->asArray()->all());

        $this->assertSame(
            'SELECT worker_1.* FROM worker AS worker_1 LEFT JOIN project_membership AS project_membership_1 ON project_membership_1.worker_id=worker_1.id LEFT JOIN project AS project_1 ON project_1.id=project_membership_1.project_id WHERE (project_membership_1.curator_id = 2)',
            Worker::objects()->filter(['projects__through__curator' => $secondWorker])->allSql()
        );
        $this->assertSame(
            'SELECT worker_1.* FROM worker AS worker_1 LEFT JOIN project_membership AS project_membership_1 ON project_membership_1.worker_id=worker_1.id LEFT JOIN project AS project_1 ON project_1.id=project_membership_1.project_id ORDER BY project_membership_1.position ASC',
            Worker::objects()->order(['projects__through__position'])->asArray()->allSql()
        );
        $this->assertSame(
            'SELECT worker_1.* FROM worker AS worker_1 LEFT JOIN project_membership AS project_membership_1 ON project_membership_1.worker_id=worker_1.id LEFT JOIN project AS project_1 ON project_1.id=project_membership_1.project_id WHERE (project_1.id IN (1, 2)) ORDER BY project_membership_1.position DESC',
            Worker::objects()->filter(['projects__id__in' => [$firstProject->id, $secondProject->id]])->order(['-projects__through__position'])->allSql()
        );
    }

    public function testToSelf()
    {
        $max = new Blogger(['name' => 'max']);
        $this->assertTrue($max->save());

        $alex = new Blogger(['name' => 'alex']);
        $this->assertTrue($alex->save());

        $peter = new Blogger(['name' => 'peter']);
        $this->assertTrue($peter->save());

        // Max was subscribed to Peter and Alex
        $max->subscribes = [$peter, $alex];
        $max->save();

        // Alex was subscribed to Peter
        $alex->subscribes = [$peter];
        $alex->save();

        // General error: 1 no such table: product_list fix for sqlite
//        $max->setConnection($this->connection);
//        $max->subscribes->setConnection($this->connection);
//        $max->subscribes->getModel()->setConnection($this->connection);

//        $max->setConnection($this->connection);
//        $max->subscribes->setConnection($this->connection);
//        $max->subscribes->setConnection($this->connection);

        $tables = $this->connection->getSchemaManager()->listTableNames();
        $this->assertTrue(in_array('blogger', $tables, true));

        $this->assertEquals(2, $max->subscribes->count());
        $this->assertEquals(0, $max->subscribers->count());
        $this->assertEquals(1, $alex->subscribes->count());
        $this->assertEquals(1, $alex->subscribers->count());
        $this->assertEquals(0, $peter->subscribes->count());
        $this->assertEquals(2, $peter->subscribers->count());
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.fft.fftshift — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="Discrete Fourier Transform (numpy.fft)" href="../routines.fft.html" />
    <link rel="next" title="numpy.fft.ifftshift" href="numpy.fft.ifftshift.html" />
    <link rel="prev" title="numpy.fft.rfftfreq" href="numpy.fft.rfftfreq.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

Discrete Fourier Transform (<tt class="docutils literal docutils literal docutils literal docutils literal docutils literal">numpy.fft</tt>) »

numpy.fft.fftshift¶

<tt class="descclassname">numpy.fft.</tt><tt class="descname">fftshift</tt><big>(</big>x, axes=None<big>)</big>[source]¶

Shift the zero-frequency component to the center of the spectrum.

This function swaps half-spaces for all axes listed (defaults to all).
Note that <tt class="docutils literal">y[0]</tt> is the Nyquist component only if <tt class="docutils literal">len(x)</tt> is even.

<col class="field-name" />
<col class="field-body" />

Parameters:
x : array_like

Input array.

axes : int or shape tuple, optional

Axes over which to shift.  Default is None, which shifts all axes.

Returns:
y : ndarray

The shifted array.

See also

<tt class="xref py py-obj docutils literal">ifftshift</tt>

The inverse of <tt class="xref py py-obj docutils literal">fftshift</tt>.

Examples

>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0.,  1.,  2.,  3.,  4., -5., -4., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])

Shift the zero-frequency component only along the second axis:

>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2.,  0.,  1.],
       [-4.,  3.,  4.],
       [-1., -3., -2.]])

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Morchella radicosa Leuba

### Remarks
null


text:
describe("Namespace oui5lib.formatter", function() {

    describe("Format/convert Date and date string", function() {
        it("should get a Date object from a  date string", function() {
            var dateString = "6.8.1945";
            var dateFormat = "d.M.yyyy";
            var date = oui5lib.formatter.getDateFromString(dateString, dateFormat);
            expect(date instanceof Date).toBe(true);
        });
        it("should format a Date to a date string", function() {
            var date = new Date("2015", "10", "25");
            var dateStr = oui5lib.formatter.getDateString(date);
            expect(dateStr).toEqual("Nov 25, 2015");
            dateStr = oui5lib.formatter.getDateString(date, "YYYYMMdd");
            expect(dateStr).toEqual("20151125");
        });

        it("should format a Date to a time string", function() {
            var date = new Date("2015", "10", "25", "9", "46", "10");
            var timeStr = oui5lib.formatter.getTimeString(date);
            expect(timeStr).toEqual("9:46:10 AM");
            timeStr = oui5lib.formatter.getTimeString(date, "HHmmss");
            expect(timeStr).toEqual("094610");

            date = new Date("2015", "10", "25", "13", "8", "2");
            timeStr = oui5lib.formatter.getTimeString(date);
            expect(timeStr).toEqual("1:08:02 PM");
            timeStr = oui5lib.formatter.getTimeString(date, "HHmmss");
            expect(timeStr).toEqual("130802");
        });

        it("should convert date and time strings into a Date object", function() {
            var date = new Date("2014", "4", "5", "1", "00", "10");
            var dateStr = "2014-05-05";
            var timeStr = "01:00:10";
            var dateObj = oui5lib.formatter.getDateFromStrings(dateStr, timeStr);
            expect(dateObj).toEqual(date);

            date = new Date("2014", "9", "11", "23", "59", "9");
            dateStr = "2014-10-11";
            timeStr = "23:59:09";
            dateObj = oui5lib.formatter.getDateFromStrings(dateStr, timeStr);
            expect(dateObj).toEqual(date);
        });

        it("should reformat a date string to a specified pattern", function() {
            var inDateStr = "4.1.2017";
            var outDateStr = oui5lib.formatter.convertDateString(inDateStr, "YYYY-MM-dd", "dd.MM.YYYY");
            expect(outDateStr).toEqual("2017-01-04");
        });

        it("should return an empty string if the date string cannot be parsed", function() {
            var inDateStr = "4.1.2017";
            var outDateStr = oui5lib.formatter.convertDateString(inDateStr, "YYYY-MM-dd");
            expect(outDateStr).toEqual("");
        });
    });
    it("should convert industrial minutes to human readable time", function() {
        var timeStr = oui5lib.formatter.convertIndustrialMinutes("85");
        expect(timeStr).toEqual("01:25");

        timeStr = oui5lib.formatter.convertIndustrialMinutes(85.5);
        expect(timeStr).toEqual("01:25");

        timeStr = oui5lib.formatter.convertIndustrialMinutes("713");
        expect(timeStr).toEqual("11:53");
    });

    it("should convert time string to industrial minutes", function() {
        expect(oui5lib.formatter.convertToIndustrialMinutes("10:10")).toEqual(610);
        expect(oui5lib.formatter.convertToIndustrialMinutes("01:10")).toEqual(70);
        expect(oui5lib.formatter.convertToIndustrialMinutes("01:10:30")).toEqual(70);
        expect(oui5lib.formatter.convertToIndustrialMinutes("00:10")).toEqual(10);
        expect(oui5lib.formatter.convertToIndustrialMinutes()).toBe(null);
        expect(oui5lib.formatter.convertToIndustrialMinutes("abc")).toBe(null);
    });

    it("should base64 encode a string", function() {
        var str = "abc\ntest#!null";
        var encodedStr = oui5lib.formatter.base64Encode(str);
        expect(encodedStr).toEqual("YWJjCnRlc3QjIW51bGw=");
    });

    it("should base64 decode an encoded string", function() {
        var encodedStr = "YWJjCnRlc3QjIW51bGw=";
        var decodedStr = oui5lib.formatter.base64Decode(encodedStr);
        expect(decodedStr).toEqual("abc\ntest#!null");
    });

});


text:
#pragma once

#include <Windows.h>

class Event
{
public:
	Event();
	~Event();

	//! locks the mutex
	void Signal() const;
	//! unlocks the mutex
	void Wait() const;

private:
	/// windows critical section structure
	mutable HANDLE event_;
};