text:
"""
Support for real-time departure information for Rhein-Main public transport.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rmvtransport/
"""
import logging

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION)

REQUIREMENTS = ['PyRMVtransport==0.1']

_LOGGER = logging.getLogger(__name__)

CONF_NEXT_DEPARTURE = 'next_departure'

CONF_STATION = 'station'
CONF_DESTINATIONS = 'destinations'
CONF_DIRECTIONS = 'directions'
CONF_LINES = 'lines'
CONF_PRODUCTS = 'products'
CONF_TIME_OFFSET = 'time_offset'
CONF_MAX_JOURNEYS = 'max_journeys'

DEFAULT_NAME = 'RMV Journey'

VALID_PRODUCTS = ['U-Bahn', 'Tram', 'Bus', 'S', 'RB', 'RE', 'EC', 'IC', 'ICE']

ICONS = {
    'U-Bahn': 'mdi:subway',
    'Tram': 'mdi:tram',
    'Bus': 'mdi:bus',
    'S': 'mdi:train',
    'RB': 'mdi:train',
    'RE': 'mdi:train',
    'EC': 'mdi:train',
    'IC': 'mdi:train',
    'ICE': 'mdi:train',
    'SEV': 'mdi:checkbox-blank-circle-outline',
    None: 'mdi:clock'
}
ATTRIBUTION = "Data provided by opendata.rmv.de"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_NEXT_DEPARTURE): [{
        vol.Required(CONF_STATION): cv.string,
        vol.Optional(CONF_DESTINATIONS, default=[]):
            vol.All(cv.ensure_list, [cv.string]),
        vol.Optional(CONF_DIRECTIONS, default=[]):
            vol.All(cv.ensure_list, [cv.string]),
        vol.Optional(CONF_LINES, default=[]):
            vol.All(cv.ensure_list, [cv.positive_int, cv.string]),
        vol.Optional(CONF_PRODUCTS, default=VALID_PRODUCTS):
            vol.All(cv.ensure_list, [vol.In(VALID_PRODUCTS)]),
        vol.Optional(CONF_TIME_OFFSET, default=0): cv.positive_int,
        vol.Optional(CONF_MAX_JOURNEYS, default=5): cv.positive_int,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string}]
})

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the RMV departure sensor."""
    sensors = []
    for next_departure in config.get(CONF_NEXT_DEPARTURE):
        sensors.append(
            RMVDepartureSensor(
                next_departure[CONF_STATION],
                next_departure.get(CONF_DESTINATIONS),
                next_departure.get(CONF_DIRECTIONS),
                next_departure.get(CONF_LINES),
                next_departure.get(CONF_PRODUCTS),
                next_departure.get(CONF_TIME_OFFSET),
                next_departure.get(CONF_MAX_JOURNEYS),
                next_departure.get(CONF_NAME)))
    add_entities(sensors, True)

class RMVDepartureSensor(Entity):
    """Implementation of an RMV departure sensor."""

    def __init__(self, station, destinations, directions,
                 lines, products, time_offset, max_journeys, name):
        """Initialize the sensor."""
        self._station = station
        self._name = name
        self._state = None
        self.data = RMVDepartureData(station, destinations, directions, lines,
                                     products, time_offset, max_journeys)
        self._icon = ICONS[None]

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def available(self):
        """Return True if entity is available."""
        return self._state is not None

    @property
    def state(self):
        """Return the next departure time."""
        return self._state

    @property
    def state_attributes(self):
        """Return the state attributes."""
        try:
            return {
                'next_departures': [val for val in self.data.departures[1:]],
                'direction': self.data.departures[0].get('direction'),
                'line': self.data.departures[0].get('line'),
                'minutes': self.data.departures[0].get('minutes'),
                'departure_time':
                    self.data.departures[0].get('departure_time'),
                'product': self.data.departures[0].get('product'),
            }
        except IndexError:
            return {}

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self._icon

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return "min"

    def update(self):
        """Get the latest data and update the state."""
        self.data.update()
        if not self.data.departures:
            self._state = None
            self._icon = ICONS[None]
            return
        if self._name == DEFAULT_NAME:
            self._name = self.data.station
        self._station = self.data.station
        self._state = self.data.departures[0].get('minutes')
        self._icon = ICONS[self.data.departures[0].get('product')]

class RMVDepartureData:
    """Pull data from the opendata.rmv.de web page."""

    def __init__(self, station_id, destinations, directions,
                 lines, products, time_offset, max_journeys):
        """Initialize the sensor."""
        import RMVtransport
        self.station = None
        self._station_id = station_id
        self._destinations = destinations
        self._directions = directions
        self._lines = lines
        self._products = products
        self._time_offset = time_offset
        self._max_journeys = max_journeys
        self.rmv = RMVtransport.RMVtransport()
        self.departures = []

    def update(self):
        """Update the connection data."""
        try:
            _data = self.rmv.get_departures(self._station_id,
                                            products=self._products,
                                            maxJourneys=50)
        except ValueError:
            self.departures = []
            _LOGGER.warning("Returned data not understood")
            return
        self.station = _data.get('station')
        _deps = []
        for journey in _data['journeys']:
            # find the first departure meeting the criteria
            _nextdep = {ATTR_ATTRIBUTION: ATTRIBUTION}
            if self._destinations:
                dest_found = False
                for dest in self._destinations:
                    if dest in journey['stops']:
                        dest_found = True
                        _nextdep['destination'] = dest
                if not dest_found:
                    continue
            elif self._lines and journey['number'] not in self._lines:
                continue
            elif journey['minutes'] < self._time_offset:
                continue
            for attr in ['direction', 'departure_time', 'product', 'minutes']:
                _nextdep[attr] = journey.get(attr, '')
            _nextdep['line'] = journey.get('number', '')
            _deps.append(_nextdep)
            if len(_deps) > self._max_journeys:
                break
        self.departures = _deps


text:
#include "stdafx.h"
#include "TestUtils.h"
#include "CrashRpt.h"
#include "Utility.h"
#include "strconv.h"

// A helper function that creates a error report for testing
BOOL TestUtils::CreateErrorReport(CString sTmpFolder, CString& sErrorReportName, CString& sMD5Hash)
{
    BOOL bStatus = FALSE;
    CString sReportFolder;
    DWORD dwExitCode = 1;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    CString sSearchPattern = sTmpFolder + "\\*.zip";
    CString sMD5FileName;
    FILE* f = NULL;
    TCHAR szHashBuff[256] = _T("");
    HKEY hKey = NULL;
    LONG lResult = -1;
    CString sKeyName = _T("Software\\CrashRpt&&#4216wer\\应用程序名称");
    CString sKeyName2 = _T("HKEY_CURRENT_USER\\") + sKeyName;

    lResult = RegCreateKey(HKEY_CURRENT_USER, sKeyName, &hKey);
    if(lResult!=ERROR_SUCCESS)
        goto cleanup;

    DWORD dwVal = 12345;
    lResult = RegSetValueEx(hKey, _T("Value$%^!@#&123fer"), 0, REG_DWORD, (LPBYTE)&dwVal, sizeof(DWORD));
    if(lResult!=ERROR_SUCCESS)
        goto cleanup;

    CR_INSTALL_INFOW infoW;
    memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
    infoW.cb = sizeof(CR_INSTALL_INFOW);
    infoW.pszAppName = L"My& app Name &";
    // Use appname with restricted XML characters
    infoW.pszAppVersion = L"1.0.0 &<'a应> \"<";
    infoW.pszErrorReportSaveDir = sTmpFolder;
    infoW.dwFlags = CR_INST_NO_GUI|CR_INST_DONT_SEND_REPORT|CR_INST_STORE_ZIP_ARCHIVES;

    int nInstallResult = crInstallW(&infoW);
    if(nInstallResult!=0)
        goto cleanup;

    crAddScreenshot(CR_AS_MAIN_WINDOW);
    crAddPropertyW(L"CustomProp", L"Property Value");
    crAddRegKey(sKeyName2, L"regkey.xml", 0);

    CR_EXCEPTION_INFO ei;
    memset(&ei, 0, sizeof(CR_EXCEPTION_INFO));
    ei.cb = sizeof(ei);
    ei.exctype = CR_SEH_EXCEPTION;
    ei.code = 0x123;

    // Generate error report
    int nGenResult = crGenerateErrorReport(&ei);
    if(nGenResult!=0)
        goto cleanup;

    // Wait until CrashSender process exits
    WaitForSingleObject(ei.hSenderProcess, INFINITE);

    // Check exit code
    GetExitCodeProcess(ei.hSenderProcess, &dwExitCode);
    if(dwExitCode!=0)
        goto cleanup;

    // Get ZIP name
    hFind = FindFirstFile(sSearchPattern, &ffd);
    if(hFind==INVALID_HANDLE_VALUE)
        goto cleanup;

    sErrorReportName = sTmpFolder + _T("\\") + CString(ffd.cFileName);

    FindClose(hFind);
    hFind = NULL;

    // Get MD5 name
    sSearchPattern = sTmpFolder + "\\*.md5";
    hFind = FindFirstFile(sSearchPattern, &ffd);
    if(hFind==INVALID_HANDLE_VALUE)
        goto cleanup;

    sMD5FileName = sTmpFolder + _T("\\") + CString(ffd.cFileName);

#if _MSC_VER < 1400
    f = _tfopen(sMD5FileName, _T("rt"));
#else
    _tfopen_s(&f, sMD5FileName, _T("rt"));
#endif
    if(f==NULL)
        goto cleanup;

    TCHAR* szHash = _fgetts(szHashBuff, 256, f);
    if(szHash==NULL)
        goto cleanup;

    sMD5Hash = szHash;

    if(sMD5Hash.GetLength()!=32)
        goto cleanup; // Hash must be 32 characters in length

    bStatus = TRUE;

cleanup:

    crUninstall();

    if(f!=NULL)
        fclose(f);

    if(hFind!=INVALID_HANDLE_VALUE)
        FindClose(hFind);

    if(hKey)
        RegCloseKey(hKey);

    RegDeleteKey(HKEY_CURRENT_USER, sKeyName);

    return bStatus;
}

// Returns the list of sections in an INI file.
int TestUtils::EnumINIFileSections(CString sFileName, std::vector<CString>& aSections)
{
	TCHAR buf[4096]=_T("");

	aSections.clear();

	int nLen = GetPrivateProfileString(NULL, NULL, NULL, buf, 4096, sFileName);

	CString sToken;
	int i;
	for(i=0;i<nLen;i++)
	{
		if(buf[i]==0)
		{
			if(sToken.GetLength()!=0)
				aSections.push_back(sToken);
			sToken.Empty();
		}
		else
		{
			sToken += buf[i];
		}
	}

	return (int)aSections.size();
}

// Returns the list of strings in the specified section in an INI file.
int TestUtils::EnumINIFileStrings(CString sFileName, CString sSectionName, std::vector<CString>& aStrings)
{
	TCHAR buf[4096]=_T("");

	aStrings.clear();

	int nLen = GetPrivateProfileString(sSectionName, NULL, NULL, buf, 4096, sFileName);

	CString sToken;
	int i;
	for(i=0;i<nLen;i++)
	{
		if(buf[i]==0)
		{
			if(sToken.GetLength()!=0)
				aStrings.push_back(sToken);
			sToken.Empty();
		}
		else
		{
			sToken += buf[i];
		}
	}

	return (int)aStrings.size();
}

int TestUtils::RunProgram(CString sExeName, CString sParams)
{
	BOOL bExecute = false;
	SHELLEXECUTEINFO sei;
    memset(&sei, 0, sizeof(SHELLEXECUTEINFO));
    DWORD dwExitCode = 1;

	sei.cbSize = sizeof(SHELLEXECUTEINFO);
    sei.fMask = SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI;
    sei.lpVerb = _T("open");
    sei.lpFile = sExeName;
    sei.lpParameters = sParams;

    bExecute = ShellExecuteEx(&sei);
    if(!bExecute)
		return 255;

	// Wait until process exits
    WaitForSingleObject(sei.hProcess, 10000);

    // Check crprober.exe process exit code - it should equal to 0
    GetExitCodeProcess(sei.hProcess, &dwExitCode);

	return (int)dwExitCode;
}

void TestUtils::wtrim(std::wstring& str, const wchar_t* szTrim)
{
    std::string::size_type pos = str.find_last_not_of(szTrim);
    if(pos != std::string::npos) {
        str.erase(pos + 1);
        pos = str.find_first_not_of(szTrim);
        if(pos != std::string::npos) str.erase(0, pos);
    }
    else str.erase(str.begin(), str.end());
}

std::wstring TestUtils::exec(LPCTSTR szCmd)
{
    FILE* pipe = _tpopen(szCmd, _T("rt"));
    if (!pipe) return L"ERROR";
    wchar_t buffer[4096];
    std::wstring result;
    while(!feof(pipe))
	{
    	if(fgetws(buffer, 4096, pipe) != NULL)
    		result += buffer;
    }
	wtrim(result);
    _pclose(pipe);
    return result;
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/cognito-idp/model/RevokeTokenRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CognitoIdentityProvider::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

RevokeTokenRequest::RevokeTokenRequest() :
    m_tokenHasBeenSet(false),
    m_clientIdHasBeenSet(false),
    m_clientSecretHasBeenSet(false)
{
}

Aws::String RevokeTokenRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_tokenHasBeenSet)
  {
   payload.WithString("Token", m_token);

  }

  if(m_clientIdHasBeenSet)
  {
   payload.WithString("ClientId", m_clientId);

  }

  if(m_clientSecretHasBeenSet)
  {
   payload.WithString("ClientSecret", m_clientSecret);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection RevokeTokenRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.RevokeToken"));
  return headers;

}


text:
import * as React from 'react';
import Box from '@material-ui/core/Box';
import Switch from '@material-ui/core/Switch';
import Paper from '@material-ui/core/Paper';
import Zoom from '@material-ui/core/Zoom';
import FormControlLabel from '@material-ui/core/FormControlLabel';

const icon = (
  <Paper sx={{ m: 1 }} elevation={4}>
    <Box component="svg" sx={{ width: 100, height: 100 }}>
      <Box
        component="polygon"
        sx={{
          fill: (theme) => theme.palette.common.white,
          stroke: (theme) => theme.palette.divider,
          strokeWidth: 1,
        }}
        points="0,100 50,00, 100,100"
      />
    </Box>
  </Paper>
);

export default function SimpleZoom() {
  const [checked, setChecked] = React.useState(false);

  const handleChange = () => {
    setChecked((prev) => !prev);
  };

  return (
    <Box sx={{ height: 180 }}>
      <FormControlLabel
        control={<Switch checked={checked} onChange={handleChange} />}
        label="Show"
      />
      <Box sx={{ display: 'flex' }}>
        <Zoom in={checked}>{icon}</Zoom>
        <Zoom in={checked} style={{ transitionDelay: checked ? '500ms' : '0ms' }}>
          {icon}
        </Zoom>
      </Box>
    </Box>
  );
}


text:
module Azure::DataMigration::Mgmt::V2018_03_15_preview
  module Models
    #
    # Migration level result for Sql server to Sql MI migration.
    #
    class MigrateSqlServerSqlMITaskOutputMigrationLevel < MigrateSqlServerSqlMITaskOutput

      include MsRestAzure

      def initialize
        @resultType = "MigrationLevelOutput"
      end

      attr_accessor :resultType

      # @return [DateTime] Migration start time
      attr_accessor :started_on

      # @return [DateTime] Migration end time
      attr_accessor :ended_on

      # @return [MigrationStatus] Current status of migration. Possible values
      # include: 'Default', 'Connecting', 'SourceAndTargetSelected',
      # 'SelectLogins', 'Configured', 'Running', 'Error', 'Stopped',
      # 'Completed', 'CompletedWithWarnings'
      attr_accessor :status

      # @return [MigrationState] Current state of migration. Possible values
      # include: 'None', 'InProgress', 'Failed', 'Warning', 'Completed',
      # 'Skipped', 'Stopped'
      attr_accessor :state

      # @return [String] Migration progress message
      attr_accessor :message

      # @return [Hash{String => String}] Selected databases as a map from
      # database name to database id
      attr_accessor :databases

      # @return [String] Source server version
      attr_accessor :source_server_version

      # @return [String] Source server brand version
      attr_accessor :source_server_brand_version

      # @return [String] Target server version
      attr_accessor :target_server_version

      # @return [String] Target server brand version
      attr_accessor :target_server_brand_version

      # @return [Array<ReportableException>] Migration exceptions and warnings.
      attr_accessor :exceptions_and_warnings

      #
      # Mapper for MigrateSqlServerSqlMITaskOutputMigrationLevel class as Ruby
      # Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'MigrationLevelOutput',
          type: {
            name: 'Composite',
            class_name: 'MigrateSqlServerSqlMITaskOutputMigrationLevel',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              resultType: {
                client_side_validation: true,
                required: true,
                serialized_name: 'resultType',
                type: {
                  name: 'String'
                }
              },
              started_on: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'startedOn',
                type: {
                  name: 'DateTime'
                }
              },
              ended_on: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'endedOn',
                type: {
                  name: 'DateTime'
                }
              },
              status: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'status',
                type: {
                  name: 'String'
                }
              },
              state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'state',
                type: {
                  name: 'String'
                }
              },
              message: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'message',
                type: {
                  name: 'String'
                }
              },
              databases: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'databases',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              source_server_version: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'sourceServerVersion',
                type: {
                  name: 'String'
                }
              },
              source_server_brand_version: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'sourceServerBrandVersion',
                type: {
                  name: 'String'
                }
              },
              target_server_version: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'targetServerVersion',
                type: {
                  name: 'String'
                }
              },
              target_server_brand_version: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'targetServerBrandVersion',
                type: {
                  name: 'String'
                }
              },
              exceptions_and_warnings: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'exceptionsAndWarnings',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ReportableExceptionElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ReportableException'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
Archived as migration is complete

# Coursemogy Migration
Migration script from Coursemology v1 to v2.

## Usage
Add these line to the application's Gemfile:

```ruby
gem 'mysql2'
gem 'redis'
```

Add a new connection to the old database in `database.yml`.
```yaml
v1:
  adapter: mysql2
  database: coursemology
  host: coursemology.org
```

Clone the files from this repo to Coursemology V2's `lib/tasks` directory.

And then:
```sh
$ rake migration:start
```


text:
// This package is generated by client-gen with custom arguments.

// This package has the automatically generated clientset.
package clientset_v1alpha1


text:
"""
Security group interface (1.1 extension).
"""

import six
from six.moves.urllib import parse

from novaclient import base

class SecurityGroup(base.Resource):
    def __str__(self):
        return str(self.id)

    def delete(self):
        self.manager.delete(self)

    def update(self):
        self.manager.update(self)

class SecurityGroupManager(base.ManagerWithFind):
    resource_class = SecurityGroup

    def create(self, name, description):
        """
        Create a security group

        :param name: name for the security group to create
        :param description: description of the security group
        :rtype: the security group object
        """
        body = {"security_group": {"name": name, 'description': description}}
        return self._create('/os-security-groups', body, 'security_group')

    def update(self, group, name, description):
        """
        Update a security group

        :param group: The security group to update (group or ID)
        :param name: name for the security group to update
        :param description: description for the security group to update
        :rtype: the security group object
        """
        body = {"security_group": {"name": name, 'description': description}}
        return self._update('/os-security-groups/%s' % base.getid(group),
                            body, 'security_group')

    def delete(self, group):
        """
        Delete a security group

        :param group: The security group to delete (group or ID)
        :rtype: None
        """
        self._delete('/os-security-groups/%s' % base.getid(group))

    def get(self, group_id):
        """
        Get a security group

        :param group_id: The security group to get by ID
        :rtype: :class:`SecurityGroup`
        """
        return self._get('/os-security-groups/%s' % group_id,
                         'security_group')

    def list(self, search_opts=None):
        """
        Get a list of all security_groups

        :rtype: list of :class:`SecurityGroup`
        """
        search_opts = search_opts or {}

        qparams = dict((k, v) for (k, v) in six.iteritems(search_opts) if v)

        query_string = '?%s' % parse.urlencode(qparams) if qparams else ''

        return self._list('/os-security-groups%s' % query_string,
                          'security_groups')


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

-->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <bean type="org.apache.struts2.views.TagLibraryDirectiveProvider" name="sm" class="com.moomanow.web.struts.views.StrutsMooTagLibrary" />
    <bean type="org.apache.struts2.views.TagLibraryModelProvider" name="sm" class="com.moomanow.web.struts.views.StrutsMooTagLibrary" />
</struts>