hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c8b9a4cd8ac7fb5a3162c4a262341a99ed45205 | 4,393 | swift | Swift | Vinyl/Track.swift | rafalszastok/Vinyl | ef3145936e229231c82552b920cb49e93c9492bc | [
"MIT"
] | null | null | null | Vinyl/Track.swift | rafalszastok/Vinyl | ef3145936e229231c82552b920cb49e93c9492bc | [
"MIT"
] | null | null | null | Vinyl/Track.swift | rafalszastok/Vinyl | ef3145936e229231c82552b920cb49e93c9492bc | [
"MIT"
] | null | null | null | //
// Track.swift
// Vinyl
//
// Created by David Rodrigues on 14/02/16.
// Copyright © 2016 Velhotes. All rights reserved.
//
import Foundation
public typealias EncodedObject = [String : Any]
public typealias HTTPHeaders = [String : String]
public typealias Request = URLRequest
public struct Track {
public let request: Request
public let response: Response
public init(request: Request, response: Response) {
self.request = request
self.response = response
}
public init(response: Response) {
self.response = response
let urlString = response.urlResponse?.url?.absoluteString
let url = URL(string: urlString!)!
self.request = URLRequest(url: url)
}
}
// MARK: - Extensions
extension Track {
public init(encodedTrack: EncodedObject) {
guard let encodedResponse = encodedTrack["response"] as? EncodedObject else {
fatalError("request/response not found 😞 for Track: \(encodedTrack)")
}
let response = Response(encodedResponse: encodedResponse)
if let encodedRequest = encodedTrack["request"] as? EncodedObject {
// We're using a helper function because we cannot mutate a NSURLRequest directly
let request = Request.create(with: encodedRequest)
self.init(request: request, response: response)
} else {
self.init(response: response)
}
}
func encodedTrack() -> EncodedObject {
var json = EncodedObject()
json["request"] = request.encodedObject()
json["response"] = response.encodedObject()
return json
}
}
extension Track: Hashable {
public var hashValue: Int {
return request.hashValue ^ response.hashValue
}
}
public func ==(lhs: Track, rhs: Track) -> Bool {
return lhs.request == rhs.request && lhs.response == rhs.response
}
// MARK: - Factory
public struct TrackFactory {
public static func createTrack(url: URL, statusCode: Int, body: Data? = nil, error: Error? = nil, headers: HTTPHeaders = [:]) -> Track {
guard
let response = HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: nil, headerFields: headers)
else {
fatalError("We weren't able to create the Track 😫")
}
let track = Track(response: Response(urlResponse: response, body: body, error: error))
return track
}
public static func createBadTrack(url: URL, statusCode: Int, error: Error? = nil, headers: HTTPHeaders = [:]) -> Track {
return createTrack(url: url, statusCode: statusCode, body: nil, error: error, headers: headers)
}
public static func createErrorTrack(url: URL, error: Error) -> Track {
let request = URLRequest(url: url)
let response = Response(urlResponse: nil, body: nil, error: error)
return Track(request: request, response: response)
}
public static func createValidTrack(url: URL, body: Data? = nil, headers: HTTPHeaders = [:]) -> Track {
return createTrack(url: url, statusCode: 200, body: body, error: nil, headers: headers)
}
public static func createValidTrack(url: URL, jsonBody: AnyObject, headers: HTTPHeaders = [:]) -> Track {
do {
let body = try JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted)
return createTrack(url: url, statusCode: 200, body: body, error: nil, headers: headers)
}
catch {
fatalError("Invalid JSON 😕\nBefore trying again check your JSON here http://jsonlint.com/ 👍")
}
}
public static func createValidTrack(url: URL, base64Body: String, headers: HTTPHeaders = [:]) -> Track {
let body = Data(base64Encoded: base64Body, options: .ignoreUnknownCharacters)
return createTrack(url: url, statusCode: 200, body: body, error: nil, headers: headers)
}
public static func createValidTrack(url: URL, utf8Body: String, headers: HTTPHeaders = [:]) -> Track {
let body = utf8Body.data(using: String.Encoding.utf8)
return createTrack(url: url, statusCode: 200, body: body, error: nil, headers: headers)
}
}
| 32.301471 | 140 | 0.619167 |
39e6471cc6fcce3ef726b94ed22d42f37c901472 | 255 | java | Java | proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/ASdebug/IASDebugStream.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/ASdebug/IASDebugStream.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/pitest/reloc/antlr/common/ASdebug/IASDebugStream.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | //
// Decompiled by Procyon v0.5.36
//
package org.pitest.reloc.antlr.common.ASdebug;
import org.pitest.reloc.antlr.common.Token;
public interface IASDebugStream
{
String getEntireText();
TokenOffsetInfo getOffsetInfo(final Token p0);
}
| 17 | 50 | 0.733333 |
c82415a5365b06bab0db1b4a8928662ddf377f74 | 353 | kt | Kotlin | app/src/main/java/me/peterhenderson/perudo/game/GamePresenter.kt | PeterH139/perudo-android | 37a9b4326ca5aacbbaab3d0eee582141a72159ed | [
"MIT"
] | null | null | null | app/src/main/java/me/peterhenderson/perudo/game/GamePresenter.kt | PeterH139/perudo-android | 37a9b4326ca5aacbbaab3d0eee582141a72159ed | [
"MIT"
] | 1 | 2017-12-24T15:43:37.000Z | 2017-12-25T17:54:45.000Z | app/src/main/java/me/peterhenderson/perudo/game/GamePresenter.kt | PeterH139/perudo-android | 37a9b4326ca5aacbbaab3d0eee582141a72159ed | [
"MIT"
] | null | null | null | package me.peterhenderson.perudo.game
import me.peterhenderson.perudo.core.DiceRoller
import javax.inject.Inject
class GamePresenter @Inject constructor(val rng: DiceRoller) {
lateinit var view: GameView
fun onCreate(view: GameView) {
this.view = view
}
fun rollDiceTapped() {
view.displayDice(rng.rollNd6(5))
}
} | 22.0625 | 62 | 0.708215 |
6ee3e4491452905de9a24c040628c7dcb406058e | 691 | html | HTML | app/partials/chart.html | ChrisBoesch/angular-scorecard | 073e7ac00bf36864404558a49e92acb54fdd2e3f | [
"MIT"
] | 1 | 2019-02-12T23:37:24.000Z | 2019-02-12T23:37:24.000Z | app/partials/chart.html | ChrisBoesch/angular-scorecard | 073e7ac00bf36864404558a49e92acb54fdd2e3f | [
"MIT"
] | null | null | null | app/partials/chart.html | ChrisBoesch/angular-scorecard | 073e7ac00bf36864404558a49e92acb54fdd2e3f | [
"MIT"
] | 1 | 2021-03-18T15:34:43.000Z | 2021-03-18T15:34:43.000Z | <div ng-switch on="data.type">
<div class="chart" ng-switch-when="boxPlot">
<sc-box-plot sc-data="data"/>
</div>
<div class="chart" ng-switch-when="groupedBoxPlot">
<sc-grouped-box-plot sc-data="data"/>
</div>
<div class="chart" ng-switch-when="bar">
<sc-bar sc-data="data"/>
</div>
<div class="chart" ng-switch-when="groupedBar">
<sc-grouped-bar sc-data="data"/>
</div>
<div class="chart" ng-switch-when="pie">
<sc-pie sc-data="data"/>
</div>
<div class="chart" ng-switch-when="stackedBar">
<sc-stacked-bar sc-data="data"/>
</div>
<div class="chart" ng-switch-when="combined">
<sc-combined sc-data="data"/>
</div>
</div> | 22.290323 | 53 | 0.599132 |
5c62c8401aec236f1b1ace7ce1efe37535149b6b | 2,171 | h | C | src/nemesis-ospf.h | Inphi/nemesis | 3e9d77dd9b14a2b6e667733452339dd0b5a28e65 | [
"BSD-3-Clause"
] | 1 | 2016-08-17T10:11:25.000Z | 2016-08-17T10:11:25.000Z | src/nemesis-ospf.h | Inphi/nemesis | 3e9d77dd9b14a2b6e667733452339dd0b5a28e65 | [
"BSD-3-Clause"
] | null | null | null | src/nemesis-ospf.h | Inphi/nemesis | 3e9d77dd9b14a2b6e667733452339dd0b5a28e65 | [
"BSD-3-Clause"
] | null | null | null | /*
* $Id: nemesis-ospf.h,v 1.1.1.1 2003/10/31 21:29:37 jnathan Exp $
*
* THE NEMESIS PROJECT
* Copyright (C) 1999, 2000 Mark Grimes <mark@stateful.net>
* Copyright (C) 2001 - 2003 Jeff Nathan <jeff@snort.org>
*
* nemesis-ospf.h (OSPF Packet Injector)
*
*/
#ifndef __NEMESIS_OSPF_H__
#define __NEMESIS_OSPF_H__
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#if defined(WIN32)
#include <pcap.h>
#endif
#if defined(HAVE_MACHINE_ENDIAN_H)
#include <machine/endian.h>
#endif
#if defined(HAVE_NETINET_IN_H)
#include <netinet/in.h>
#elif defined(WIN32)
#include <winsock2.h>
#endif
#include <libnet.h>
#include "nemesis.h"
u_short id, /* IP id */
frag, /* frag shit */
mtusize, /* Max dgram length (DBD) */
num, /* LSA_RTR num */
interval, /* secs since last pkt sent */
rtr_flags, /* LSA_RTR flags */
metric, /* OSPF metric */
ospf_age; /* OSPF advertisement age */
u_long source, /* source address */
dest, /* destination address */
neighbor, /* neighbor router */
as_fwd, /* AS_EXT forward address */
addrid, /* advertising router id */
addaid, /* advertising area id */
router, /* advertising router */
auth[2], /* authentication type */
mask; /* subnet mask (icmp_mask) */
u_char priority, /* OSPF priority */
exchange, /* DBD exchange type */
rtrtype, /* LSA_RTR type */
ooptions; /* OSPF options */
u_int dead_int, /* dead router interval in secs */
as_tag, /* AS_EXT tag */
seqnum, /* seqnum for LSA */
bcastnum, /* num of LSAs to bcast (LSU) */
rtrdata, /* LSA_RTR router data */
rtrid; /* router id for LSA */
int mode; /* OSPF injection mode */
int buildospf(ETHERhdr *, IPhdr *, FileData *, FileData *, char *);
#endif /* __NEMESIS_OSPF_H__ */
| 29.337838 | 67 | 0.55965 |
042f18723278b901d591977c5e77d2ba2652a8c2 | 158 | kt | Kotlin | lib_arch/src/main/java/com/yyxnb/arch/common/MsgEvent.kt | y1xian/Awesome | 4235798ef24c2d05945f308b213fb098d619016d | [
"Apache-2.0"
] | null | null | null | lib_arch/src/main/java/com/yyxnb/arch/common/MsgEvent.kt | y1xian/Awesome | 4235798ef24c2d05945f308b213fb098d619016d | [
"Apache-2.0"
] | null | null | null | lib_arch/src/main/java/com/yyxnb/arch/common/MsgEvent.kt | y1xian/Awesome | 4235798ef24c2d05945f308b213fb098d619016d | [
"Apache-2.0"
] | null | null | null | package com.yyxnb.arch.common
import java.io.Serializable
data class MsgEvent(var code: Int = 0, var msg: String = "", var data: Any = Any()) : Serializable | 31.6 | 98 | 0.721519 |
cbb8fb62726804b4cf1076b9627b17ff79d1ffa6 | 207 | kt | Kotlin | app/src/main/java/com/lumiwallet/lumi_core/domain/entity/Output.kt | lumiwallet/lumi-android-core | 64aeec26c27f66b2e99745d462e34100ae18dc11 | [
"Apache-2.0",
"MIT"
] | 6 | 2020-05-04T18:37:40.000Z | 2021-12-25T19:40:22.000Z | app/src/main/java/com/lumiwallet/lumi_core/domain/entity/Output.kt | lumiwallet/lumi-android-core | 64aeec26c27f66b2e99745d462e34100ae18dc11 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-12-24T08:24:18.000Z | 2020-12-24T08:24:18.000Z | app/src/main/java/com/lumiwallet/lumi_core/domain/entity/Output.kt | lumiwallet/lumi-android-core | 64aeec26c27f66b2e99745d462e34100ae18dc11 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-11-30T08:15:42.000Z | 2021-11-30T08:15:42.000Z | package com.lumiwallet.lumi_core.domain.entity
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Output(
var address: String,
var amount: Long
): Parcelable | 20.7 | 46 | 0.792271 |
b1a2b75b42b39a512b859337b5d55d310560f51c | 4,215 | h | C | ProcessParser.h | zinan93/htop_udacity | 2f0ec7e6a78e9d9cf6fd29a1e732650ec21ba5b9 | [
"MIT"
] | null | null | null | ProcessParser.h | zinan93/htop_udacity | 2f0ec7e6a78e9d9cf6fd29a1e732650ec21ba5b9 | [
"MIT"
] | null | null | null | ProcessParser.h | zinan93/htop_udacity | 2f0ec7e6a78e9d9cf6fd29a1e732650ec21ba5b9 | [
"MIT"
] | null | null | null | #ifndef PROCESSPARSER_H
#define PROCESSPARSER_H
#include <algorithm>
#include <iostream>
#include <math.h>
#include <thread>
#include <chrono>
#include <iterator>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <dirent.h>
#include <time.h>
#include <unistd.h>
#include "constants.h"
#include "util.h"
using namespace std;
class ProcessParser{
private:
ifstream stream;
public:
static string getCmd(string pid);
static vector<string> getPidList();
static string getVmSize(string pid);
static string getCpuPercent(string pid);
static long int getSysUpTime();
static string getProcUpTime(string pid);
static string getProcUser(string pid);
static vector<string> getSysCpuPercent(string coreNumber = "");
static float getSysRamPercent();
static string getSysKernelVersion();
static int getNumberOfCores();
static int getTotalThreads();
static int getTotalNumberOfProcesses();
static int getNumberOfRunningProcesses();
static string getOSName();
static string PrintCpuStats(vector<string> values1, vector<string>values2);
static bool isPidExisting(string pid);
};
// TODO: Define all of the above functions below:
//formulate path, get stream, and convert to line
string ProcessParser::getCmd(string pid){
string path, line;
path = Path::basePath() + pid + Path::cmdPath();
ifstream stream = Util::getStream(path);
getline(stream, line);
return line;
}
//return the list of all pids in /proc/
vector<string> ProcessParser::getPidList(){
vector<string> list;
DIR* dir;
string path = Path::basePath();
dir = opendir(path.c_str());
while(dirent* dirp = readdir(dir))
{
//if not a directory then start over
if(dirp->d_type != DT_DIR)
continue;
//check if every char is a digit, otherwise start over
if(!all_of(dirp->d_name, dirp->d_name + std::strlen(dirp->d_name),
[](char c){ return std::isdigit(c); }))
continue;
//if a pid then save to list
list.push_back(dirp->d_name);
}
return list;
}
//TODO: VmData vs VmSize
string ProcessParser::getVmSize(string pid){
string path = Path::basePath() + pid + Path::statusPath();
ifstream stream(Util::getStream(path));
string str;
size_t found;
string vmsize;
while (getline(stream, str))
{
found=str.find("VmSize");
if (found!=std::string::npos){
for (int i = str.find(":")+1; i <= str.length(); i++){
if (isdigit(char(str[i])))
vmsize += str[i];
}
vmsize = to_string(stof(vmsize)/float(1024*1024));
break;
}
}
return vmsize;
}
string ProcessParser::getProcUpTime(string pid){
vector<string> values;
//TODO: ifstream cannot be copied, is there a better way to pass by reference?
values = Util::getVecFromStream(Util::getStream((Path::basePath() + pid + Path::statPath())));
float procuptime = stof(values[13]);
float freq = sysconf(_SC_CLK_TCK);
return to_string(procuptime/freq);
}
long int ProcessParser::getSysUpTime(){
string line;
vector<string> values;
values = Util::getVecFromStream(Util::getStream(Path::basePath() + Path::upTimePath()));
return stoi(values[0]);
}
string ProcessParser::getCpuPercent(string pid)
{
float result;
vector<string> values;
values = Util::getVecFromStream(Util::getStream((Path::basePath()+ pid + "/" + Path::statPath())));
float utime = stof(ProcessParser::getProcUpTime(pid));
float stime = stof(values[14]);
float cutime = stof(values[15]);
float cstime = stof(values[16]);
float starttime = stof(values[21]);
float uptime = ProcessParser::getSysUpTime();
//get system frequency (clock ticks)
float freq = sysconf(_SC_CLK_TCK);
float total_time = utime + stime + cutime + cstime;
float seconds = uptime - (starttime/freq);
result = 100.0*((total_time/freq)/seconds);
return to_string(result);
}
#endif | 28.47973 | 103 | 0.651246 |
19630f642c7b2c65baff7d04f7c9c880708e0715 | 643 | kt | Kotlin | ok-marketplace-be-common/src/main/kotlin/ru/otus/otuskotlin/marketplace/common/backend/repositories/IAdRepository.kt | otuskotlin/202012-otuskotlin-marketplace | 5f05fe658504dfa5d7300e3f0f523d250ff6ce31 | [
"MIT"
] | 1 | 2021-02-23T18:26:47.000Z | 2021-02-23T18:26:47.000Z | ok-marketplace-be-common/src/main/kotlin/ru/otus/otuskotlin/marketplace/common/backend/repositories/IAdRepository.kt | otuskotlin/202012-otuskotlin-marketplace | 5f05fe658504dfa5d7300e3f0f523d250ff6ce31 | [
"MIT"
] | 1 | 2021-03-02T09:42:55.000Z | 2021-04-25T07:22:49.000Z | ok-marketplace-be-common/src/main/kotlin/ru/otus/otuskotlin/marketplace/common/backend/repositories/IAdRepository.kt | otuskotlin/202012-otuskotlin-marketplace | 5f05fe658504dfa5d7300e3f0f523d250ff6ce31 | [
"MIT"
] | null | null | null | package ru.otus.otuskotlin.marketplace.common.backend.repositories
import ru.otus.otuskotlin.marketplace.common.backend.context.MpBeContext
import ru.otus.otuskotlin.marketplace.common.backend.models.IMpItemModel
import ru.otus.otuskotlin.marketplace.common.backend.models.MpDemandModel
interface IAdRepository<T: IMpItemModel> {
suspend fun read(context: MpBeContext): T
suspend fun create(context: MpBeContext): T
suspend fun update(context: MpBeContext): T
suspend fun delete(context: MpBeContext): T
suspend fun list(context: MpBeContext): Collection<T>
suspend fun offers(context: MpBeContext): Collection<T>
}
| 40.1875 | 73 | 0.797823 |
ef8bbc9696c66cc1c48e6be14f7e1788e4a82a71 | 2,259 | kt | Kotlin | erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/MoonWaxingGibbous4.kt | ravitejasc/compose-icons | 09f752ef051b1c47e60554f3893bbed5ddd8bc1f | [
"MIT"
] | 230 | 2020-11-11T14:52:11.000Z | 2022-03-31T05:04:52.000Z | erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/MoonWaxingGibbous4.kt | ravitejasc/compose-icons | 09f752ef051b1c47e60554f3893bbed5ddd8bc1f | [
"MIT"
] | 17 | 2021-03-02T00:00:32.000Z | 2022-03-02T16:01:03.000Z | erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/MoonWaxingGibbous4.kt | ravitejasc/compose-icons | 09f752ef051b1c47e60554f3893bbed5ddd8bc1f | [
"MIT"
] | 18 | 2021-02-08T06:18:41.000Z | 2022-03-22T21:48:23.000Z | package compose.icons.weathericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.WeatherIcons
public val WeatherIcons.MoonWaxingGibbous4: ImageVector
get() {
if (_moonWaxingGibbous4 != null) {
return _moonWaxingGibbous4!!
}
_moonWaxingGibbous4 = Builder(name = "MoonWaxingGibbous4", defaultWidth = 30.0.dp,
defaultHeight = 30.0.dp, viewportWidth = 30.0f, viewportHeight = 30.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.73f, 14.43f)
curveToRelative(0.0f, 1.19f, 0.07f, 2.29f, 0.2f, 3.3f)
reflectiveCurveToRelative(0.35f, 2.0f, 0.67f, 2.99f)
reflectiveCurveToRelative(0.76f, 1.9f, 1.33f, 2.75f)
reflectiveCurveToRelative(1.27f, 1.59f, 2.09f, 2.25f)
curveToRelative(1.53f, 0.0f, 2.99f, -0.3f, 4.38f, -0.89f)
reflectiveCurveToRelative(2.58f, -1.4f, 3.59f, -2.4f)
reflectiveCurveToRelative(1.81f, -2.2f, 2.4f, -3.6f)
reflectiveCurveToRelative(0.89f, -2.85f, 0.89f, -4.39f)
curveToRelative(0.0f, -2.04f, -0.5f, -3.93f, -1.51f, -5.65f)
reflectiveCurveToRelative(-2.37f, -3.1f, -4.1f, -4.1f)
reflectiveCurveToRelative(-3.61f, -1.51f, -5.65f, -1.51f)
curveToRelative(-1.35f, 1.3f, -2.4f, 2.94f, -3.16f, 4.93f)
reflectiveCurveTo(10.73f, 12.19f, 10.73f, 14.43f)
close()
}
}
.build()
return _moonWaxingGibbous4!!
}
private var _moonWaxingGibbous4: ImageVector? = null
| 49.108696 | 95 | 0.635237 |
90af0c3b5c35784252e7535ec9333b5f74334c22 | 1,751 | py | Python | algorithm/graph_theory/even_tree/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | 1 | 2017-07-02T01:35:39.000Z | 2017-07-02T01:35:39.000Z | algorithm/graph_theory/even_tree/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | null | null | null | algorithm/graph_theory/even_tree/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | 1 | 2018-04-03T15:11:56.000Z | 2018-04-03T15:11:56.000Z | #!/usr/bin/env python3
"""Solution for https://www.hackerrank.com/challenges/even-tree"""
from collections import defaultdict, deque
from typing import Dict, Set
Vertex = int
Tree = Dict[Vertex, Set[Vertex]]
def trim_tree(tree: Tree, root=1) -> None:
"""Make tree a directed graph."""
for child in tree[root]:
try:
tree[child].remove(root)
except KeyError:
pass
trim_tree(tree, child)
def prune_tree(tree: Tree, root: Vertex=1) -> int:
"""Given a tree, determine the amount of edges that can be pruned."""
count = 0
for child in tree[root]:
if tree_size(tree, child) % 2 == 0:
count += 1
count += prune_tree(tree, child)
return count
def tree_size(subtree: Tree, start: Vertex=1, *, root: Vertex=1) -> int:
"""Count the amount of vertices in the subtree using a bfs traversal."""
visited = {root, start}
queue = deque([x for x in subtree[start]])
count = 1
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
count += 1
for next_vertex in subtree[vertex]:
if next_vertex not in visited:
queue.append(next_vertex)
return count
def main():
"""Print the amount of edges that can be pruned from a tree."""
tree = defaultdict(set)
vertex_count, edge_count = input().split()
vertex_count = int(vertex_count)
edge_count = int(edge_count)
for _ in range(edge_count):
v1, v2 = input().split()
v1 = int(v1)
v2 = int(v2)
tree[v1].add(v2)
tree[v2].add(v1)
trim_tree(tree)
print(prune_tree(tree))
if __name__ == '__main__':
main()
| 26.530303 | 76 | 0.596802 |
76f656833be7fd57a5ff406550cfaa17c059c69b | 1,034 | kt | Kotlin | library/src/androidTest/java/graf/semmel/valium/helper/FormFragmentRobot.kt | graf-semmel/valium | 2ddfcf61b5c520919461bcdeecb027d997611323 | [
"Apache-2.0"
] | 1 | 2021-04-22T00:38:01.000Z | 2021-04-22T00:38:01.000Z | library/src/androidTest/java/graf/semmel/valium/helper/FormFragmentRobot.kt | graf-semmel/valium | 2ddfcf61b5c520919461bcdeecb027d997611323 | [
"Apache-2.0"
] | null | null | null | library/src/androidTest/java/graf/semmel/valium/helper/FormFragmentRobot.kt | graf-semmel/valium | 2ddfcf61b5c520919461bcdeecb027d997611323 | [
"Apache-2.0"
] | null | null | null | package graf.semmel.valium.helper
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.grafsemmel.valium.R
import org.hamcrest.CoreMatchers.not
class FormFragmentRobot : BaseRobot() {
private val submitButton get() = Espresso.onView(withId(R.id.btn_submit))
fun setInput1Valid() {
fillEditText(R.id.et_1, "123")
}
fun setInput2Valid() {
fillEditText(R.id.et_2, "123")
}
fun setInput3Valid() {
fillEditText(R.id.et_3, "123")
}
fun setInput3TooShort() {
fillEditText(R.id.et_3, "12")
}
fun submitButtonShouldBeDisabled() {
submitButton.check(matches(not(isEnabled())))
}
fun submitButtonShouldBeEnabled() {
submitButton.check(matches(isEnabled()))
}
}
fun formFragmentRobot(action: FormFragmentRobot.() -> Unit) = FormFragmentRobot().apply(action) | 26.512821 | 95 | 0.709865 |
8997591a071c03293c9ec4287eea9bcb4a8c85c1 | 4,053 | kt | Kotlin | src/main/kotlin/com/lykke/matching/engine/messages/MessageWrapper.kt | NovichikhinAlexey/MatchingEngine | 828800ca6e77df2ea6c763a9753361bc1b608d14 | [
"MIT"
] | 31 | 2016-02-26T00:08:19.000Z | 2022-02-02T20:56:29.000Z | src/main/kotlin/com/lykke/matching/engine/messages/MessageWrapper.kt | NovichikhinAlexey/MatchingEngine | 828800ca6e77df2ea6c763a9753361bc1b608d14 | [
"MIT"
] | 17 | 2016-03-26T09:18:38.000Z | 2019-04-24T11:13:23.000Z | src/main/kotlin/com/lykke/matching/engine/messages/MessageWrapper.kt | NovichikhinAlexey/MatchingEngine | 828800ca6e77df2ea6c763a9753361bc1b608d14 | [
"MIT"
] | 16 | 2016-10-17T11:17:11.000Z | 2021-03-09T07:18:50.000Z | package com.lykke.matching.engine.messages
import com.google.protobuf.Message
import com.google.protobuf.MessageOrBuilder
import com.lykke.matching.engine.deduplication.ProcessedMessage
import com.lykke.matching.engine.socket.ClientHandler
import com.lykke.matching.engine.utils.ByteHelper.Companion.toByteArray
import com.lykke.utils.logging.MetricsLogger
import com.lykke.utils.logging.ThrottlingLogger
import java.io.IOException
import java.lang.IllegalStateException
class MessageWrapper(
val sourceIp: String,
val type: Byte,
val byteArray: ByteArray,
val clientHandler: ClientHandler?,
val startTimestamp: Long = System.nanoTime(),
var timestamp: Long? = null,
var messageId: String? = null,
var parsedMessage: MessageOrBuilder? = null,
var id: String? = null,
var triedToPersist: Boolean = false,
var persisted: Boolean = false,
var context: Any? = null) {
companion object {
private val LOGGER = ThrottlingLogger.getLogger(MessageWrapper::class.java.name)
private val METRICS_LOGGER = MetricsLogger.getLogger()
}
var messagePreProcessorStartTimestamp: Long? = null
var messagePreProcessorEndTimestamp: Long? = null
var writeResponseTime: Long? = null
var processedMessage: ProcessedMessage? = null
fun writeResponse(responseBuilder: ProtocolMessages.Response.Builder) {
if (!responseBuilder.hasMessageId() && messageId != null) {
responseBuilder.messageId = messageId
}
if (!responseBuilder.hasUid() && id != null) {
responseBuilder.uid = id!!.toLong()
}
writeClientResponse(responseBuilder.build(), MessageType.RESPONSE)
}
fun writeNewResponse(responseBuilder: ProtocolMessages.NewResponse.Builder) {
if (!responseBuilder.hasMessageId() && messageId != null) {
responseBuilder.messageId = messageId
}
if (!responseBuilder.hasId() && id != null) {
responseBuilder.id = id
}
writeClientResponse(responseBuilder.build(), MessageType.NEW_RESPONSE)
}
fun writeMarketOrderResponse(responseBuilder: ProtocolMessages.MarketOrderResponse.Builder) {
if (!responseBuilder.hasMessageId() && messageId != null) {
responseBuilder.messageId = messageId
}
if (!responseBuilder.hasId() && id != null) {
responseBuilder.id = id
}
writeClientResponse(responseBuilder.build(), MessageType.MARKER_ORDER_RESPONSE)
}
fun writeMultiLimitOrderResponse(responseBuilder: ProtocolMessages.MultiLimitOrderResponse.Builder) {
if (!responseBuilder.hasMessageId() && messageId != null) {
responseBuilder.messageId = messageId
}
if (!responseBuilder.hasId() && id != null) {
responseBuilder.id = id
}
writeClientResponse(responseBuilder.build(), MessageType.MULTI_LIMIT_ORDER_RESPONSE)
}
private fun writeClientResponse(message: Message, messageType: MessageType) {
if (clientHandler != null) {
try {
if (writeResponseTime != null) {
val errorMessage = "[$sourceIp]: Can not write response - response was already written to socket, message id $messageId"
LOGGER.error(errorMessage)
METRICS_LOGGER.logError(errorMessage)
throw IllegalStateException(errorMessage)
}
val start = System.nanoTime()
clientHandler.writeOutput(toByteArray(messageType.type, message.serializedSize, message.toByteArray()))
writeResponseTime = System.nanoTime() - start
} catch (exception: IOException){
LOGGER.error("[$sourceIp]: Unable to write for message with id $messageId response: ${exception.message}", exception)
METRICS_LOGGER.logError( "[$sourceIp]: Unable to write response", exception)
}
}
}
}
| 38.235849 | 140 | 0.660745 |
abf1747adee340a339442cb80f757b004e049504 | 632 | rb | Ruby | spec/factories/content_element.rb | edraut/pulitzer | 33ed6382175ef9b3d77d9dde53d023a64d60c265 | [
"MIT"
] | 3 | 2015-06-22T20:24:12.000Z | 2017-04-30T19:11:00.000Z | spec/factories/content_element.rb | edraut/pulitzer | 33ed6382175ef9b3d77d9dde53d023a64d60c265 | [
"MIT"
] | 40 | 2015-06-30T16:58:16.000Z | 2017-08-03T03:18:41.000Z | spec/factories/content_element.rb | edraut/pulitzer | 33ed6382175ef9b3d77d9dde53d023a64d60c265 | [
"MIT"
] | 2 | 2015-06-24T20:47:00.000Z | 2016-03-30T22:26:20.000Z | FactoryGirl.define do
factory :content_element, class: Pulitzer::ContentElement do
sequence(:label) { |n| "Slide 1 content element #{n}" }
body { "I pledge my life and honor to the Night's Watch, for this night and all the nights to come" }
association :content_element_type
trait :video do
body { "https://www.youtube.com/watch?v=yLisM2KPDIA" }
association :content_element_type, :video
end
trait :image do
image { Rack::Test::UploadedFile.new(File.join(Dir.pwd, "spec/support/files/sam_and_snow.jpg")) }
association :content_element_type, :image
end
end
end
| 35.111111 | 118 | 0.68038 |
1702f90caad912b49c31fe94f4d0bd2e5b17f70e | 976 | h | C | source/extensions/http/header_validators/envoy_default/config.h | CrazyHZM/envoy | 416c6f5a1d85ceb5ed9cc173533eb36b2e2dcac0 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:23:12.000Z | 2022-03-02T14:23:12.000Z | source/extensions/http/header_validators/envoy_default/config.h | CrazyHZM/envoy | 416c6f5a1d85ceb5ed9cc173533eb36b2e2dcac0 | [
"Apache-2.0"
] | 153 | 2021-10-04T04:32:48.000Z | 2022-03-31T04:22:40.000Z | source/extensions/http/header_validators/envoy_default/config.h | CrazyHZM/envoy | 416c6f5a1d85ceb5ed9cc173533eb36b2e2dcac0 | [
"Apache-2.0"
] | 1 | 2021-12-14T02:39:44.000Z | 2021-12-14T02:39:44.000Z | #pragma once
#include "envoy/http/header_validator.h"
#include "envoy/registry/registry.h"
#include "source/common/protobuf/protobuf.h"
namespace Envoy {
namespace Extensions {
namespace Http {
namespace HeaderValidators {
namespace EnvoyDefault {
/**
* Config registration for the custom header IP detection extension.
* @see OriginalIPDetectionFactory.
*/
class HeaderValidatorFactoryConfig : public ::Envoy::Http::HeaderValidatorFactoryConfig {
public:
::Envoy::Http::HeaderValidatorFactorySharedPtr
createFromProto(const Protobuf::Message& config,
Server::Configuration::FactoryContext& context) override;
ProtobufTypes::MessagePtr createEmptyConfigProto() override;
std::string name() const override { return "envoy.http.header_validators.envoy_default"; }
};
DECLARE_FACTORY(HeaderValidatorFactoryConfig);
} // namespace EnvoyDefault
} // namespace HeaderValidators
} // namespace Http
} // namespace Extensions
} // namespace Envoy
| 27.111111 | 92 | 0.773566 |
9bc150972a4e0e9109bb37ec44a774ef3ddd77ec | 2,509 | js | JavaScript | src/js/modules/videoAnchor/UI/ToolBtn.js | bruceCzK/bilibili-helper | 34d56fd47da9d9844213bc57efcf007742826bcd | [
"MIT"
] | 1 | 2020-11-26T02:07:58.000Z | 2020-11-26T02:07:58.000Z | src/js/modules/videoAnchor/UI/ToolBtn.js | 3318193168/bilibili-helper | faa240996154587e82b5fa5704db6d369184e581 | [
"MIT"
] | null | null | null | src/js/modules/videoAnchor/UI/ToolBtn.js | 3318193168/bilibili-helper | faa240996154587e82b5fa5704db6d369184e581 | [
"MIT"
] | 1 | 2022-03-29T13:02:23.000Z | 2022-03-29T13:02:23.000Z | /**
* Author: DrowsyFlesh
* Create: 2018/10/10
* Description:
*/
import React from 'react';
import styled from 'styled-components';
import ToolContentBuilder from './ToolContent';
export default () => {
const ToolContent = ToolContentBuilder();
const HelperBtn = styled.span`
display: inline-block;
padding: 0 15px;
border-radius: 4px;
transition: all 0.3s;
width: ${({old}) => old ? 'auto' : 48}px;
.func-module & {
width: 90px;
border: 1px solid #e5e9ef;
&:hover {
border-color: rgb(0, 161, 214);
}
}
&:hover, &.show {
color: rgb(0, 161, 214);
}
.entry-old .bilibili-helper &, #entryOld .bilibili-helper & {
display: block;
position: relative;
margin-top: 8px;
padding: 8px 0;
line-height: 16px;
background-color: #fb7299;
font-size: 12px;
color: #fff;
border-radius: 2px;
cursor: pointer;
text-align: center;
-webkit-box-shadow: 0 2px 10px 0 rgba(251,114,153,.4);
box-shadow: 0 2px 10px 0 rgba(251,114,153,.4);
z-index: 2;
user-select: none;
&:hover {
background-color: #ff85ad;
}
}
`;
return class ToolBtn extends React.Component {
constructor(props) {
super(props);
this.show = false;
this.isOldPage = !!document.querySelector('#__bofqi');
}
handleClick = (e) => {
e.preventDefault();
const content = document.querySelector('.bilibili-helper-content');
if (this.show) {
this.show = false;
content && content.setAttribute('style', 'visibility: hidden;');
} else {
this.show = true;
content && content.setAttribute('style', 'visibility: visible;');
}
};
render() {
return (
<React.Fragment>
<link href="https://at.alicdn.com/t/font_894803_ilqifyzi68.css" rel="stylesheet" type="text/css"/>
<HelperBtn
onClick={this.handleClick}
title="哔哩哔哩助手"
old={this.isOldPage}
>
{this.isOldPage ? '哔哩哔哩助手' : '助手'}
</HelperBtn>
<ToolContent/>
</React.Fragment>
);
}
}
}
| 29.174419 | 118 | 0.489438 |
7cebb7c6c288e08275244ad353438e1018afb2ec | 276 | lua | Lua | shared/common/githubSha.lua | kurabirko/phys400 | 1e7608322457c090e4db8c52ff1c7c8c55a612c3 | [
"CC-BY-4.0"
] | null | null | null | shared/common/githubSha.lua | kurabirko/phys400 | 1e7608322457c090e4db8c52ff1c7c8c55a612c3 | [
"CC-BY-4.0"
] | null | null | null | shared/common/githubSha.lua | kurabirko/phys400 | 1e7608322457c090e4db8c52ff1c7c8c55a612c3 | [
"CC-BY-4.0"
] | null | null | null | local M = {}
function M.print()
local is_ci = os.getenv('CI') or ''
if is_ci ~= 'true' then
return
end
local version = os.getenv('GITHUB_SHA')
tex.sprint('\\begingroup Build: \\ttfamily ' ..
string.sub(version, 1, 7) ..
' \\endgroup')
end
return M
| 16.235294 | 49 | 0.594203 |
917f1f89093f152339b734180c54d938aa7ce946 | 1,180 | html | HTML | app/connect/connect.html | riblee/chat-client | 10d3d6b465a7d6cc0479ada01f674f8250e6a6ae | [
"MIT"
] | null | null | null | app/connect/connect.html | riblee/chat-client | 10d3d6b465a7d6cc0479ada01f674f8250e6a6ae | [
"MIT"
] | null | null | null | app/connect/connect.html | riblee/chat-client | 10d3d6b465a7d6cc0479ada01f674f8250e6a6ae | [
"MIT"
] | null | null | null | <md-card class="center">
<md-card-title>Connect</md-card-title>
<md-card-subtitle *ngIf="channel.errors">
<p *ngIf="channel.errors.alreadyConnected" color="warn">
You already connected to this Room
</p>
</md-card-subtitle>
<md-card-subtitle *ngIf="!channel.errors || channel.valid || channel.value === ''">
Connect to a Room
</md-card-subtitle>
<md-card-content>
<form [ngFormModel]="connectForm">
<md-input type="text" ngControl="channel" id="channel" [required]="true"
[dividerColor]="channel.valid ? 'primary' : 'warn'"
placeholder="Room" style="width: 100%"></md-input>
<md-input type="text" required
ngControl="nickname" id="nickname" [required]="true"
[dividerColor]="nickname.valid ? 'primary' : 'warn'"
placeholder="Nickname" style="width: 100%"></md-input>
</form>
</md-card-content>
<md-card-actions>
<button md-raised-button (click)="connect()" [disabled]="!(channel.valid && nickname.valid)">Connect</button>
</md-card-actions>
</md-card> | 47.2 | 117 | 0.569492 |
1663e589a07d50792f441207056292c62aedef78 | 376 | ts | TypeScript | src/entities/DTO/ProfileDTO.ts | fossabot/SkiAPIv2 | 37d64278e5c240d84cef0b18b2105af6cd07220e | [
"MIT"
] | null | null | null | src/entities/DTO/ProfileDTO.ts | fossabot/SkiAPIv2 | 37d64278e5c240d84cef0b18b2105af6cd07220e | [
"MIT"
] | null | null | null | src/entities/DTO/ProfileDTO.ts | fossabot/SkiAPIv2 | 37d64278e5c240d84cef0b18b2105af6cd07220e | [
"MIT"
] | null | null | null | import { User } from "../User";
export class ProfileDTO {
userId: number;
firstName: string;
lastName: string;
userRoles: string[];
/**
*
*/
constructor(user: User, userRoles) {
this.userId = user.userId;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.userRoles = userRoles;
}
}
| 17.090909 | 40 | 0.571809 |
fe129cc38e9bbd2af7fbd559021012b9c07ed682 | 175 | h | C | event-driven-simulator/OrderStack.h | xia0ran-meng/comp-2150 | 768562efec2f5cd12074eeed206260c05174f3a0 | [
"MIT"
] | null | null | null | event-driven-simulator/OrderStack.h | xia0ran-meng/comp-2150 | 768562efec2f5cd12074eeed206260c05174f3a0 | [
"MIT"
] | null | null | null | event-driven-simulator/OrderStack.h | xia0ran-meng/comp-2150 | 768562efec2f5cd12074eeed206260c05174f3a0 | [
"MIT"
] | null | null | null | #pragma once
#include "OrderList.h"
/**
* Model an order stack
*/
class OrderStack : public OrderList {
public:
OrderStack();
void add(Entity* item) override;
};
| 12.5 | 37 | 0.657143 |
90aab92c1f990f1bf8a76881ea4041d11b95e741 | 738 | py | Python | apps/webmarks/bookmarks/migrations/00012_remove_uuid_null.py | EricMuller/mynote-backend | 69bc39b8cfad52d6c42003cfa7bd629f3e8eccb7 | [
"MIT"
] | 1 | 2017-04-26T10:24:21.000Z | 2017-04-26T10:24:21.000Z | apps/webmarks/bookmarks/migrations/00012_remove_uuid_null.py | EricMuller/mynotes-backend | 69bc39b8cfad52d6c42003cfa7bd629f3e8eccb7 | [
"MIT"
] | 5 | 2020-06-05T18:16:39.000Z | 2022-01-13T00:45:49.000Z | apps/webmarks/bookmarks/migrations/00012_remove_uuid_null.py | EricMuller/webmarks-rest-api | 69bc39b8cfad52d6c42003cfa7bd629f3e8eccb7 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-30 12:03
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('webmarks_bookmarks', '0011_populate_uuid_values'),
]
operations = [
migrations.AlterField(
model_name='historicalbookmark',
name='uuid',
field=models.UUIDField(
db_index=True, default=uuid.uuid4, editable=False),
),
migrations.AlterField(
model_name='node',
name='uuid',
field=models.UUIDField(
default=uuid.uuid4, editable=False, unique=True),
),
]
| 24.6 | 67 | 0.596206 |
3bfb79561e0c9015ea93b616f534579a48a1afe5 | 3,319 | c | C | Multiple_Interrupt/main.c | hodoemelem/Stm32l4-Bare-Metal | a4dc462699cda0488eaaebc5a751ce6167486884 | [
"MIT"
] | null | null | null | Multiple_Interrupt/main.c | hodoemelem/Stm32l4-Bare-Metal | a4dc462699cda0488eaaebc5a751ce6167486884 | [
"MIT"
] | null | null | null | Multiple_Interrupt/main.c | hodoemelem/Stm32l4-Bare-Metal | a4dc462699cda0488eaaebc5a751ce6167486884 | [
"MIT"
] | null | null | null | #include "stm32l4xx.h" // Device header
//Led: PA5
//push Button:PC13
//PB10 conneted to GND or VCC
void SysClock_Config(void);
void systickDelayMS(int n);
void EXTI15_10_IRQHandler(void); // External interrupt callback function
volatile int pb10_counter;
volatile int pc13_counter;
int main(void)
{
SysClock_Config();
__disable_irq(); // disable global interrupts request initially
RCC->AHB2ENR |= (1<<0)|(1<<1)|(1<<2); // GPIO A,B,C clk enable
RCC->APB2ENR |= (1<<0); // enable clock for SYSCFG
GPIOA->MODER = 0xABFFF7FF; // ie ... 0111 1111 1111 MODE5 is PA5, 01 for output mode
GPIOB->MODER = 0xFFCFFEBF; // MODE10 for PB10, input mode
GPIOC->MODER = 0xF3FFFFFF; // ie 1111 0011 1111 ... MODE13 is PC13, 00 for input mode
SYSCFG->EXTICR[3] |= 0x20; // select EXTI13 for PC13 interrupt with 0x20
SYSCFG->EXTICR[2] |= 0x100; // select EXTI10 for PB10 interrupt with 0x100
EXTI->IMR1 |= 0x2000; // unmask EXTI13
EXTI->FTSR1 |= 0x2000; // select falling edge intrreupt trigger on pin 13
EXTI->IMR1 |= 0x400; // unmask EXTI10
EXTI->FTSR1 |= 0x400; // select falling edge trigger for PB10
EXTI->RTSR1 = 1<<10;
GPIOB->PUPDR =0x100000; // enable pullup resistor on PB10
NVIC_EnableIRQ(EXTI15_10_IRQn); // enable IRQ for EXT115 to 10
__enable_irq(); // enable global interrupt
while(1);
}
//ISR for EXTI15 to 10
void EXTI15_10_IRQHandler(void)
{
if(EXTI->PR1 & 0x2000){ // PC13
EXTI->PR1 = 0x2000; // clear pin 13 interrupt pending flag
pc13_counter++;
GPIOA->BSRR = (1<<5); // or 0x20; set PA5 High
systickDelayMS(300);
GPIOA->BSRR = 1<<(5+16); // or 0x002; reset PA5
systickDelayMS(300);
}
else if(EXTI->PR1 & 0x0400){ //PB10
EXTI->PR1 = 0x0400; // clear pin 10 interrupt pending flag
pb10_counter++;
GPIOA->BSRR = (1<<5); // or 0x20; set PA5 High
systickDelayMS(300);
GPIOA->BSRR = 1<<(5+16); // or 0x002; reset PA5
systickDelayMS(300);
GPIOA->BSRR = (1<<5); // or 0x20; set PA5 High
systickDelayMS(300);
GPIOA->BSRR = 1<<(5+16); // or 0x002; reset PA5
systickDelayMS(300);
GPIOA->BSRR = (1<<5); // or 0x20; set PA5 High
systickDelayMS(300);
GPIOA->BSRR = 1<<(5+16); // or 0x002; reset PA5
systickDelayMS(300);
}
}
void SysClock_Config(void)
{
RCC->CR = RCC_CR_MSION; // MSI ON
RCC->CFGR &=~ RCC_CFGR_SW; // select MSI as clk source
while((RCC->CR & RCC_CR_MSIRDY) == 0); // wait for MSI to be ready
RCC->CR &=~ RCC_CR_MSIRANGE; // clear the range register
RCC->CR |= RCC_CR_MSIRANGE_8; // select 16MHz range
RCC->CR |= RCC_CR_MSIRGSEL; // Use the MSIRANGE in CR
while((RCC->CR & RCC_CR_MSIRDY) == 0); // wait for MSI to be ready
}
void systickDelayMS(int n)
{
// Based on 16MHz clk
SysTick->LOAD = 16000 - 1; // 1m sec event @16MHz clk
SysTick->VAL = 0; // Clear current value reg.
SysTick->CTRL =0x5; // Enable Systick
for(int i = 0; i<n; i++)
{
while((SysTick->CTRL & 0x10000) == 0);
}
SysTick->CTRL = 0; // Disable SysTick
}
| 27.204918 | 88 | 0.590238 |
cb87a6fbfd05e606e856578b95f3a22109758e7b | 245 | asm | Assembly | libsrc/_DEVELOPMENT/arch/zxn/esxdos/c/sccz80/esx_ide_get_lfn_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/_DEVELOPMENT/arch/zxn/esxdos/c/sccz80/esx_ide_get_lfn_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/_DEVELOPMENT/arch/zxn/esxdos/c/sccz80/esx_ide_get_lfn_callee.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z | ; unsigned char esx_ide_get_lfn(struct esx_lfn *dir, struct esx_cat_entry *query)
SECTION code_esxdos
PUBLIC esx_ide_get_lfn_callee
EXTERN asm_esx_ide_get_lfn
esx_ide_get_lfn_callee:
pop hl
pop de
ex (sp),hl
jp asm_esx_ide_get_lfn
| 15.3125 | 81 | 0.804082 |
fbae12a6b206b567383df965ededec1aca415c95 | 2,362 | c | C | kernel/test-suite/physical-memory-test.c | sts-q/Einherjar | dcbeb8ff408baf9678edbc6f8e2e149b0ec74fb9 | [
"MIT"
] | 20 | 2015-07-24T04:42:50.000Z | 2022-03-17T22:01:20.000Z | kernel/test-suite/physical-memory-test.c | narke/oldrg | f359d2ec24e1c912c08144870c324b480bb62759 | [
"MIT"
] | 1 | 2018-01-01T15:52:47.000Z | 2018-01-01T15:52:47.000Z | kernel/test-suite/physical-memory-test.c | narke/oldrg | f359d2ec24e1c912c08144870c324b480bb62759 | [
"MIT"
] | 2 | 2021-03-27T23:21:54.000Z | 2021-06-25T17:06:36.000Z | #include <lib/types.h>
#include <lib/libc.h>
#include <lib/queue.h>
#include <arch/x86-pc/io/vga.h>
#include <memory/physical-memory.h>
#include "physical-memory-test.h"
#define MY_PPAGE_NUM_INT 511
struct phys_page
{
uint32_t before[MY_PPAGE_NUM_INT];
TAILQ_ENTRY(phys_page) next;
uint32_t after[MY_PPAGE_NUM_INT];
};
void test_physical_memory(void)
{
TAILQ_HEAD(, phys_page) phys_pages_head;
struct phys_page *phys_page;
uint32_t nb_allocated_physical_pages = 0;
uint32_t nb_free_physical_pages = 0;
TAILQ_INIT(&phys_pages_head);
printf("\n\n++ Physical memory allocaion/deallocation test! ++\n");
// Test the allocation
while ((phys_page = (struct phys_page*)physical_memory_page_reference_new()) != NULL)
{
int i;
nb_allocated_physical_pages++;
vga_set_position(0, 7);
printf("Can allocate %d pages\n", nb_allocated_physical_pages);
for (i = 0 ; i < MY_PPAGE_NUM_INT ; i++)
{
phys_page->before[i] = (uint32_t)phys_page;
phys_page->after[i] = (uint32_t)phys_page;
}
TAILQ_INSERT_TAIL(&phys_pages_head, phys_page, next);
}
// Test the deallocation
TAILQ_FOREACH(phys_page, &phys_pages_head, next)
{
int i;
for (i = 0 ; i < MY_PPAGE_NUM_INT ; i++)
{
if ((phys_page->before[i] != (uint32_t)phys_page)
|| (phys_page->after[i] != (uint32_t)phys_page))
{
printf("Page overwritten\n");
return;
}
}
if (physical_memory_page_unreference((uint32_t)phys_page) < 0)
{
printf("Cannot dealloc page\n");
return;
}
nb_free_physical_pages++;
vga_set_position(30, 7);
printf("Can free %d pages\n", nb_free_physical_pages);
}
assert(nb_allocated_physical_pages == nb_free_physical_pages);
printf("Can allocate %d bytes and free %d bytes \n",
nb_allocated_physical_pages << X86_PAGE_SHIFT,
nb_free_physical_pages << X86_PAGE_SHIFT);
}
| 28.457831 | 93 | 0.552498 |
48c49ea5fd7a8b37a1e386f95150e45c8cfcdb5d | 1,151 | h | C | TAO/examples/Simple/time/Time_i.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/examples/Simple/time/Time_i.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/examples/Simple/time/Time_i.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//=============================================================================
/**
* @file Time_i.h
*
* $Id: Time_i.h 94530 2011-09-28 12:37:43Z johnnyw $
*
* This class implements the Time IDL interface.
*
*
* @author Darrell Brunsch <brunsch@cs.wustl.edu>
*/
//=============================================================================
#ifndef TIME_I_H
#define TIME_I_H
#include "TimeS.h"
/**
* @class Time_i:
*
* @brief Time Object Implementation
*
* Implementation of a simple object that has two methods, one that
* return the current time/date on the server and the other that
* shuts down the server.
*/
class Time_i: public POA_Time
{
public:
// = Initialization and termination methods.
/// Constructor
Time_i (void);
/// Destructor
virtual ~Time_i (void);
/// Return the current time/date on the server
virtual CORBA::Long current_time (void);
/// Shutdown the server.
virtual void shutdown (void);
/// Set the ORB pointer.
void orb (CORBA::ORB_ptr o);
private:
/// ORB pointer.
CORBA::ORB_var orb_;
void operator= (const Time_i &);
};
#endif /* TIME_I_H */
| 19.844828 | 79 | 0.565595 |
5bd9dccdff340a5db4938edd14de9843e82ce367 | 3,104 | c | C | drivers/bl702_driver/hal_drv/src/hal_boot2.c | zeroherolin/bl_mcu_sdk | 97760e3633d7ce0f435be1d98e7c9e8c46bfaca7 | [
"Apache-2.0"
] | 2 | 2021-08-20T06:50:43.000Z | 2021-08-20T07:30:49.000Z | drivers/bl702_driver/hal_drv/src/hal_boot2.c | zeroherolin/bl_mcu_sdk | 97760e3633d7ce0f435be1d98e7c9e8c46bfaca7 | [
"Apache-2.0"
] | null | null | null | drivers/bl702_driver/hal_drv/src/hal_boot2.c | zeroherolin/bl_mcu_sdk | 97760e3633d7ce0f435be1d98e7c9e8c46bfaca7 | [
"Apache-2.0"
] | null | null | null | #include "hal_boot2.h"
#include "hal_flash.h"
#include "bl702_ef_ctrl.h"
#include "bl702_hbn.h"
#include "bl702_glb.h"
#include "bl702_xip_sflash.h"
#include "tzc_sec_reg.h"
#include "hal_gpio.h"
/**
* @brief boot2 custom
*
* @param None
* @return uint32
*/
uint32_t hal_boot2_custom(void)
{
return 0;
}
/**
* @brief get efuse Boot2 config
*
* @param g_efuse_cfg
* @param
* @param
* @return None
*/
void hal_boot2_get_efuse_cfg(boot2_efuse_hw_config *g_efuse_cfg)
{
uint32_t tmp;
HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL);
/* Get sign and aes type*/
EF_Ctrl_Read_Secure_Boot((EF_Ctrl_Sign_Type *)g_efuse_cfg->sign, (EF_Ctrl_SF_AES_Type *)g_efuse_cfg->encrypted);
/* Get hash:aes key slot 0 and slot1*/
EF_Ctrl_Read_AES_Key(0, (uint32_t *)g_efuse_cfg->pk_hash_cpu0, 8);
EF_Ctrl_Read_Chip_ID(g_efuse_cfg->chip_id);
/* Get HBN check sign config */
EF_Ctrl_Read_Sw_Usage(0, &tmp);
g_efuse_cfg->hbn_check_sign = (tmp >> 22) & 0x01;
GLB_Set_System_CLK_Div(0, 1);
HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL);
}
/**
* @brief reset sec eng clock
*
* @return
*/
void hal_boot2_reset_sec_eng(void)
{
GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SEC);
}
/**
* @brief system soft reset
*
* @return
*/
void hal_boot2_sw_system_reset(void)
{
GLB_SW_System_Reset();
}
/**
* @brief
*
* @param flag
* @param
* @param
* @return
*/
void hal_boot2_set_psmode_status(uint32_t flag)
{
HBN_Set_Status_Flag(flag);
}
/**
* @brief
*
* @param
* @param
* @param
* @return flag
*/
uint32_t hal_boot2_get_psmode_status(void)
{
return HBN_Get_Status_Flag();
}
/**
* @brief
*
* @param
* @param
* @param
* @return user define flag
*/
uint8_t *hal_boot2_get_user_fw(void)
{
return (uint8_t *)(HBN_BASE + HBN_RSV0_OFFSET);
}
/**
* @brief clr user define flag
*
* @param
* @param
* @param
* @return
*/
void hal_boot2_clr_user_fw(void)
{
uint32_t *p = (uint32_t *)(HBN_BASE + HBN_RSV0_OFFSET);
*p = 0;
}
/**
* @brief hal_boot2_sboot_finish
*
* @return
*/
void ATTR_TCM_SECTION hal_boot2_sboot_finish(void)
{
uint32_t tmp_val;
tmp_val = BL_RD_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL);
tmp_val = BL_SET_REG_BITS_VAL(tmp_val, TZC_SEC_TZC_SBOOT_DONE, 0xf);
BL_WR_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL, tmp_val);
}
/**
* @brief hal_boot2_pll_init
*
* @return
*/
void hal_boot2_uart_gpio_init(void)
{
GLB_GPIO_Type gpios[]={GPIO_PIN_14,GPIO_PIN_15};
GLB_GPIO_Func_Init(GPIO_FUN_UART,gpios,2);
GLB_UART_Fun_Sel((GPIO_PIN_14 % 8), GLB_UART_SIG_FUN_UART0_TXD);// GPIO_FUN_UART1_TX
GLB_UART_Fun_Sel((GPIO_PIN_15 % 8), GLB_UART_SIG_FUN_UART0_RXD);
}
/**
* @brief hal_boot2_pll_init
*
* @return
*/
void hal_boot2_debug_uart_gpio_init(void)
{
GLB_GPIO_Type gpios[]={GPIO_PIN_17};
GLB_GPIO_Func_Init(GPIO_FUN_UART,gpios,1);
GLB_UART_Fun_Sel((GPIO_PIN_17 % 8), GLB_UART_SIG_FUN_UART1_TXD);
}
| 18.586826 | 117 | 0.656894 |
40ffc076361674499ba934a04524b8c77032b66c | 282 | py | Python | xe_currencies/settings.py | aisayko/django-xe-currencies | 483646a93bf15a8dc942b6b9e08c2516193eee1a | [
"MIT"
] | 2 | 2015-04-06T19:13:35.000Z | 2019-03-01T06:19:42.000Z | xe_currencies/settings.py | aisayko/django-xe-currencies | 483646a93bf15a8dc942b6b9e08c2516193eee1a | [
"MIT"
] | 3 | 2020-02-11T22:23:11.000Z | 2021-06-10T17:42:48.000Z | xe_currencies/settings.py | aisayko/django-xe-currencies | 483646a93bf15a8dc942b6b9e08c2516193eee1a | [
"MIT"
] | 1 | 2015-05-12T20:31:19.000Z | 2015-05-12T20:31:19.000Z | """
The following settings should be defined in your global settings
XE_DATAFEED_URL should be set to your registered XE username.
"""
try:
from django.conf import settings
except ImportError:
settings = {}
XE_DATAFEED_URL = 'http://www.xe.com/dfs/datafeed2.cgi?xeuser'
| 20.142857 | 64 | 0.748227 |
400bea91ad46a0cb4ff8371afab7e1ce0d518ca6 | 20,828 | py | Python | convlab/lib/util.py | ngduyanhece/ConvLab | a04582a77537c1a706fbf64715baa9ad0be1301a | [
"MIT"
] | 405 | 2019-06-17T05:38:47.000Z | 2022-03-29T15:16:51.000Z | convlab/lib/util.py | ngduyanhece/ConvLab | a04582a77537c1a706fbf64715baa9ad0be1301a | [
"MIT"
] | 69 | 2019-06-20T22:57:41.000Z | 2022-03-04T12:12:07.000Z | convlab/lib/util.py | ngduyanhece/ConvLab | a04582a77537c1a706fbf64715baa9ad0be1301a | [
"MIT"
] | 124 | 2019-06-17T05:11:23.000Z | 2021-12-31T05:58:18.000Z | # Modified by Microsoft Corporation.
# Licensed under the MIT license.
import json
import operator
import os
import pickle
import subprocess
import sys
import time
from collections import deque
from contextlib import contextmanager
from datetime import datetime
from importlib import reload
from pprint import pformat
import numpy as np
import pandas as pd
import pydash as ps
import regex as re
import torch
import torch.multiprocessing as mp
import ujson
import yaml
from convlab import ROOT_DIR, EVAL_MODES
NUM_CPUS = mp.cpu_count()
FILE_TS_FORMAT = '%Y_%m_%d_%H%M%S'
RE_FILE_TS = re.compile(r'(\d{4}_\d{2}_\d{2}_\d{6})')
class LabJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, (np.ndarray, pd.Series)):
return obj.tolist()
else:
return str(obj)
def batch_get(arr, idxs):
'''Get multi-idxs from an array depending if it's a python list or np.array'''
if isinstance(arr, (list, deque)):
return np.array(operator.itemgetter(*idxs)(arr))
else:
return arr[idxs]
def calc_srs_mean_std(sr_list):
'''Given a list of series, calculate their mean and std'''
cat_df = pd.DataFrame(dict(enumerate(sr_list)))
mean_sr = cat_df.mean(axis=1)
std_sr = cat_df.std(axis=1)
return mean_sr, std_sr
def calc_ts_diff(ts2, ts1):
'''
Calculate the time from tss ts1 to ts2
@param {str} ts2 Later ts in the FILE_TS_FORMAT
@param {str} ts1 Earlier ts in the FILE_TS_FORMAT
@returns {str} delta_t in %H:%M:%S format
@example
ts1 = '2017_10_17_084739'
ts2 = '2017_10_17_084740'
ts_diff = util.calc_ts_diff(ts2, ts1)
# => '0:00:01'
'''
delta_t = datetime.strptime(ts2, FILE_TS_FORMAT) - datetime.strptime(ts1, FILE_TS_FORMAT)
return str(delta_t)
def cast_df(val):
'''missing pydash method to cast value as DataFrame'''
if isinstance(val, pd.DataFrame):
return val
return pd.DataFrame(val)
def cast_list(val):
'''missing pydash method to cast value as list'''
if ps.is_list(val):
return val
else:
return [val]
def clear_periodic_ckpt(prepath):
'''Clear periodic (with -epi) ckpt files in prepath'''
if '-epi' in prepath:
run_cmd(f'rm {prepath}*')
def concat_batches(batches):
'''
Concat batch objects from body.memory.sample() into one batch, when all bodies experience similar envs
Also concat any nested epi sub-batches into flat batch
{k: arr1} + {k: arr2} = {k: arr1 + arr2}
'''
# if is nested, then is episodic
is_episodic = isinstance(batches[0]['dones'][0], (list, np.ndarray))
concat_batch = {}
for k in batches[0]:
datas = []
for batch in batches:
data = batch[k]
if is_episodic: # make into plain batch instead of nested
data = np.concatenate(data)
datas.append(data)
concat_batch[k] = np.concatenate(datas)
return concat_batch
def downcast_float32(df):
'''Downcast any float64 col to float32 to allow safer pandas comparison'''
for col in df.columns:
if df[col].dtype == 'float':
df[col] = df[col].astype('float32')
return df
def epi_done(done):
'''
General method to check if episode is done for both single and vectorized env
Only return True for singleton done since vectorized env does not have a natural episode boundary
'''
return np.isscalar(done) and done
def find_ckpt(prepath):
'''Find the ckpt-lorem-ipsum in a string and return lorem-ipsum'''
if 'ckpt' in prepath:
ckpt_str = ps.find(prepath.split('_'), lambda s: s.startswith('ckpt'))
ckpt = ckpt_str.replace('ckpt-', '')
else:
ckpt = None
return ckpt
def frame_mod(frame, frequency, num_envs):
'''
Generic mod for (frame % frequency == 0) for when num_envs is 1 or more,
since frame will increase multiple ticks for vector env, use the remainder'''
remainder = num_envs or 1
return (frame % frequency < remainder)
def flatten_dict(obj, delim='.'):
'''Missing pydash method to flatten dict'''
nobj = {}
for key, val in obj.items():
if ps.is_dict(val) and not ps.is_empty(val):
strip = flatten_dict(val, delim)
for k, v in strip.items():
nobj[key + delim + k] = v
elif ps.is_list(val) and not ps.is_empty(val) and ps.is_dict(val[0]):
for idx, v in enumerate(val):
nobj[key + delim + str(idx)] = v
if ps.is_object(v):
nobj = flatten_dict(nobj, delim)
else:
nobj[key] = val
return nobj
def get_class_name(obj, lower=False):
'''Get the class name of an object'''
class_name = obj.__class__.__name__
if lower:
class_name = class_name.lower()
return class_name
def get_class_attr(obj):
'''Get the class attr of an object as dict'''
attr_dict = {}
for k, v in obj.__dict__.items():
if hasattr(v, '__dict__') or ps.is_tuple(v):
val = str(v)
else:
val = v
attr_dict[k] = val
return attr_dict
def get_file_ext(data_path):
'''get the `.ext` of file.ext'''
return os.path.splitext(data_path)[-1]
def get_fn_list(a_cls):
'''
Get the callable, non-private functions of a class
@returns {[*str]} A list of strings of fn names
'''
fn_list = ps.filter_(dir(a_cls), lambda fn: not fn.endswith('__') and callable(getattr(a_cls, fn)))
return fn_list
def get_git_sha():
return subprocess.check_output(['git', 'rev-parse', 'HEAD'], close_fds=True, cwd=ROOT_DIR).decode().strip()
def get_lab_mode():
return os.environ.get('lab_mode')
def get_prepath(spec, unit='experiment'):
spec_name = spec['name']
meta_spec = spec['meta']
predir = f'output/{spec_name}_{meta_spec["experiment_ts"]}'
prename = f'{spec_name}'
trial_index = meta_spec['trial']
session_index = meta_spec['session']
t_str = '' if trial_index is None else f'_t{trial_index}'
s_str = '' if session_index is None else f'_s{session_index}'
if unit == 'trial':
prename += t_str
elif unit == 'session':
prename += f'{t_str}{s_str}'
ckpt = meta_spec['ckpt']
if ckpt is not None:
prename += f'_ckpt-{ckpt}'
prepath = f'{predir}/{prename}'
return prepath
def get_ts(pattern=FILE_TS_FORMAT):
'''
Get current ts, defaults to format used for filename
@param {str} pattern To format the ts
@returns {str} ts
@example
util.get_ts()
# => '2017_10_17_084739'
'''
ts_obj = datetime.now()
ts = ts_obj.strftime(pattern)
assert RE_FILE_TS.search(ts)
return ts
def insert_folder(prepath, folder):
'''Insert a folder into prepath'''
split_path = prepath.split('/')
prename = split_path.pop()
split_path += [folder, prename]
return '/'.join(split_path)
def in_eval_lab_modes():
'''Check if lab_mode is one of EVAL_MODES'''
return get_lab_mode() in EVAL_MODES
def is_jupyter():
'''Check if process is in Jupyter kernel'''
try:
get_ipython().config
return True
except NameError:
return False
return False
@contextmanager
def ctx_lab_mode(lab_mode):
'''
Creates context to run method with a specific lab_mode
@example
with util.ctx_lab_mode('eval'):
foo()
@util.ctx_lab_mode('eval')
def foo():
...
'''
prev_lab_mode = os.environ.get('lab_mode')
os.environ['lab_mode'] = lab_mode
yield
if prev_lab_mode is None:
del os.environ['lab_mode']
else:
os.environ['lab_mode'] = prev_lab_mode
def monkey_patch(base_cls, extend_cls):
'''Monkey patch a base class with methods from extend_cls'''
ext_fn_list = get_fn_list(extend_cls)
for fn in ext_fn_list:
setattr(base_cls, fn, getattr(extend_cls, fn))
def parallelize(fn, args, num_cpus=NUM_CPUS):
'''
Parallelize a method fn, args and return results with order preserved per args.
args should be a list of tuples.
@returns {list} results Order preserved output from fn.
'''
pool = mp.Pool(num_cpus, maxtasksperchild=1)
results = pool.starmap(fn, args)
pool.close()
pool.join()
return results
def prepath_split(prepath):
'''
Split prepath into useful names. Works with predir (prename will be None)
prepath: output/dqn_pong_2018_12_02_082510/dqn_pong_t0_s0
predir: output/dqn_pong_2018_12_02_082510
prefolder: dqn_pong_2018_12_02_082510
prename: dqn_pong_t0_s0
spec_name: dqn_pong
experiment_ts: 2018_12_02_082510
ckpt: ckpt-best of dqn_pong_t0_s0_ckpt-best if available
'''
prepath = prepath.strip('_')
tail = prepath.split('output/')[-1]
ckpt = find_ckpt(tail)
if ckpt is not None: # separate ckpt
tail = tail.replace(f'_ckpt-{ckpt}', '')
if '/' in tail: # tail = prefolder/prename
prefolder, prename = tail.split('/', 1)
else:
prefolder, prename = tail, None
predir = f'output/{prefolder}'
spec_name = RE_FILE_TS.sub('', prefolder).strip('_')
experiment_ts = RE_FILE_TS.findall(prefolder)[0]
return predir, prefolder, prename, spec_name, experiment_ts, ckpt
def prepath_to_idxs(prepath):
'''Extract trial index and session index from prepath if available'''
_, _, prename, spec_name, _, _ = prepath_split(prepath)
idxs_tail = prename.replace(spec_name, '').strip('_')
idxs_strs = ps.compact(idxs_tail.split('_')[:2])
if ps.is_empty(idxs_strs):
return None, None
tidx = idxs_strs[0]
assert tidx.startswith('t')
trial_index = int(tidx.strip('t'))
if len(idxs_strs) == 1: # has session
session_index = None
else:
sidx = idxs_strs[1]
assert sidx.startswith('s')
session_index = int(sidx.strip('s'))
return trial_index, session_index
def prepath_to_spec(prepath):
'''
Given a prepath, read the correct spec recover the meta_spec that will return the same prepath for eval lab modes
example: output/a2c_cartpole_2018_06_13_220436/a2c_cartpole_t0_s0
'''
predir, _, prename, _, experiment_ts, ckpt = prepath_split(prepath)
sidx_res = re.search('_s\d+', prename)
if sidx_res: # replace the _s0 if any
prename = prename.replace(sidx_res[0], '')
spec_path = f'{predir}/{prename}_spec.json'
# read the spec of prepath
spec = read(spec_path)
# recover meta_spec
trial_index, session_index = prepath_to_idxs(prepath)
meta_spec = spec['meta']
meta_spec['experiment_ts'] = experiment_ts
meta_spec['ckpt'] = ckpt
meta_spec['experiment'] = 0
meta_spec['trial'] = trial_index
meta_spec['session'] = session_index
check_prepath = get_prepath(spec, unit='session')
assert check_prepath in prepath, f'{check_prepath}, {prepath}'
return spec
def read(data_path, **kwargs):
'''
Universal data reading method with smart data parsing
- {.csv} to DataFrame
- {.json} to dict, list
- {.yml} to dict
- {*} to str
@param {str} data_path The data path to read from
@returns {data} The read data in sensible format
@example
data_df = util.read('test/fixture/lib/util/test_df.csv')
# => <DataFrame>
data_dict = util.read('test/fixture/lib/util/test_dict.json')
data_dict = util.read('test/fixture/lib/util/test_dict.yml')
# => <dict>
data_list = util.read('test/fixture/lib/util/test_list.json')
# => <list>
data_str = util.read('test/fixture/lib/util/test_str.txt')
# => <str>
'''
data_path = smart_path(data_path)
try:
assert os.path.isfile(data_path)
except AssertionError:
raise FileNotFoundError(data_path)
ext = get_file_ext(data_path)
if ext == '.csv':
data = read_as_df(data_path, **kwargs)
elif ext == '.pkl':
data = read_as_pickle(data_path, **kwargs)
else:
data = read_as_plain(data_path, **kwargs)
return data
def read_as_df(data_path, **kwargs):
'''Submethod to read data as DataFrame'''
ext = get_file_ext(data_path)
data = pd.read_csv(data_path, **kwargs)
return data
def read_as_pickle(data_path, **kwargs):
'''Submethod to read data as pickle'''
with open(data_path, 'rb') as f:
data = pickle.load(f)
return data
def read_as_plain(data_path, **kwargs):
'''Submethod to read data as plain type'''
open_file = open(data_path, 'r')
ext = get_file_ext(data_path)
if ext == '.json':
data = ujson.load(open_file, **kwargs)
elif ext == '.yml':
data = yaml.load(open_file, **kwargs)
else:
data = open_file.read()
open_file.close()
return data
def run_cmd(cmd):
'''Run shell command'''
print(f'+ {cmd}')
proc = subprocess.Popen(cmd, cwd=ROOT_DIR, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
return proc
def run_cmd_wait(proc):
'''Wait on a running process created by util.run_cmd and print its stdout'''
for line in proc.stdout:
print(line.decode(), end='')
output = proc.communicate()[0]
if proc.returncode != 0:
raise subprocess.CalledProcessError(proc.args, proc.returncode, output)
else:
return output
def self_desc(cls):
'''Method to get self description, used at init.'''
desc_list = [f'{get_class_name(cls)}:']
for k, v in get_class_attr(cls).items():
if k == 'spec':
desc_v = v['name']
elif ps.is_dict(v) or ps.is_dict(ps.head(v)):
desc_v = pformat(v)
else:
desc_v = v
desc_list.append(f'- {k} = {desc_v}')
desc = '\n'.join(desc_list)
return desc
def set_attr(obj, attr_dict, keys=None):
'''Set attribute of an object from a dict'''
if keys is not None:
attr_dict = ps.pick(attr_dict, keys)
for attr, val in attr_dict.items():
setattr(obj, attr, val)
return obj
def set_cuda_id(spec):
'''Use trial and session id to hash and modulo cuda device count for a cuda_id to maximize device usage. Sets the net_spec for the base Net class to pick up.'''
# Don't trigger any cuda call if not using GPU. Otherwise will break multiprocessing on machines with CUDA.
# see issues https://github.com/pytorch/pytorch/issues/334 https://github.com/pytorch/pytorch/issues/3491 https://github.com/pytorch/pytorch/issues/9996
for agent_spec in spec['agent']:
if 'net' not in agent_spec or not agent_spec['net'].get('gpu'):
return
meta_spec = spec['meta']
trial_idx = meta_spec['trial'] or 0
session_idx = meta_spec['session'] or 0
if meta_spec['distributed'] == 'shared': # shared hogwild uses only global networks, offset them to idx 0
session_idx = 0
job_idx = trial_idx * meta_spec['max_session'] + session_idx
job_idx += meta_spec['cuda_offset']
device_count = torch.cuda.device_count()
cuda_id = None if not device_count else job_idx % device_count
for agent_spec in spec['agent']:
agent_spec['net']['cuda_id'] = cuda_id
def set_logger(spec, logger, unit=None):
'''Set the logger for a lab unit give its spec'''
os.environ['LOG_PREPATH'] = insert_folder(get_prepath(spec, unit=unit), 'log')
reload(logger) # to set session-specific logger
def set_random_seed(spec):
'''Generate and set random seed for relevant modules, and record it in spec.meta.random_seed'''
torch.set_num_threads(1) # prevent multithread slowdown, set again for hogwild
trial = spec['meta']['trial']
session = spec['meta']['session']
random_seed = int(1e5 * (trial or 0) + 1e3 * (session or 0) + time.time())
torch.cuda.manual_seed_all(random_seed)
torch.manual_seed(random_seed)
np.random.seed(random_seed)
spec['meta']['random_seed'] = random_seed
return random_seed
def _sizeof(obj, seen=None):
'''Recursively finds size of objects'''
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([_sizeof(v, seen) for v in obj.values()])
size += sum([_sizeof(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += _sizeof(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([_sizeof(i, seen) for i in obj])
return size
def sizeof(obj, divisor=1e6):
'''Return the size of object, in MB by default'''
return _sizeof(obj) / divisor
def smart_path(data_path, as_dir=False):
'''
Resolve data_path into abspath with fallback to join from ROOT_DIR
@param {str} data_path The input data path to resolve
@param {bool} as_dir Whether to return as dirname
@returns {str} The normalized absolute data_path
@example
util.smart_path('convlab/lib')
# => '/Users/ANON/Documents/convlab/convlab/lib'
util.smart_path('/tmp')
# => '/tmp'
'''
if not os.path.isabs(data_path):
abs_path = os.path.abspath(data_path)
if os.path.exists(abs_path):
data_path = abs_path
else:
data_path = os.path.join(ROOT_DIR, data_path)
if as_dir:
data_path = os.path.dirname(data_path)
return os.path.normpath(data_path)
def split_minibatch(batch, mb_size):
'''Split a batch into minibatches of mb_size or smaller, without replacement'''
size = len(batch['rewards'])
assert mb_size < size, f'Minibatch size {mb_size} must be < batch size {size}'
idxs = np.arange(size)
np.random.shuffle(idxs)
chunks = int(size / mb_size)
nested_idxs = np.array_split(idxs, chunks)
mini_batches = []
for minibatch_idxs in nested_idxs:
minibatch = {k: v[minibatch_idxs] for k, v in batch.items()}
mini_batches.append(minibatch)
return mini_batches
def to_json(d, indent=2):
'''Shorthand method for stringify JSON with indent'''
return json.dumps(d, indent=indent, cls=LabJsonEncoder)
def to_render():
return get_lab_mode() in ('dev', 'enjoy') and os.environ.get('RENDER', 'true') == 'true'
def to_torch_batch(batch, device, is_episodic):
'''Mutate a batch (dict) to make its values from numpy into PyTorch tensor'''
for k in batch:
if is_episodic: # for episodic format
batch[k] = np.concatenate(batch[k])
elif ps.is_list(batch[k]):
batch[k] = np.array(batch[k])
batch[k] = torch.from_numpy(batch[k].astype(np.float32)).to(device)
return batch
def write(data, data_path):
'''
Universal data writing method with smart data parsing
- {.csv} from DataFrame
- {.json} from dict, list
- {.yml} from dict
- {*} from str(*)
@param {*} data The data to write
@param {str} data_path The data path to write to
@returns {data_path} The data path written to
@example
data_path = util.write(data_df, 'test/fixture/lib/util/test_df.csv')
data_path = util.write(data_dict, 'test/fixture/lib/util/test_dict.json')
data_path = util.write(data_dict, 'test/fixture/lib/util/test_dict.yml')
data_path = util.write(data_list, 'test/fixture/lib/util/test_list.json')
data_path = util.write(data_str, 'test/fixture/lib/util/test_str.txt')
'''
data_path = smart_path(data_path)
data_dir = os.path.dirname(data_path)
os.makedirs(data_dir, exist_ok=True)
ext = get_file_ext(data_path)
if ext == '.csv':
write_as_df(data, data_path)
elif ext == '.pkl':
write_as_pickle(data, data_path)
else:
write_as_plain(data, data_path)
return data_path
def write_as_df(data, data_path):
'''Submethod to write data as DataFrame'''
df = cast_df(data)
ext = get_file_ext(data_path)
df.to_csv(data_path, index=False)
return data_path
def write_as_pickle(data, data_path):
'''Submethod to write data as pickle'''
with open(data_path, 'wb') as f:
pickle.dump(data, f)
return data_path
def write_as_plain(data, data_path):
'''Submethod to write data as plain type'''
open_file = open(data_path, 'w')
ext = get_file_ext(data_path)
if ext == '.json':
json.dump(data, open_file, indent=2, cls=LabJsonEncoder)
elif ext == '.yml':
yaml.dump(data, open_file)
else:
open_file.write(str(data))
open_file.close()
return data_path
| 30.674521 | 164 | 0.649942 |
cb54622187845fa97e82757c7ec34e436fff7ec1 | 2,971 | html | HTML | Python/output/charts/chart_heater_2021-01-23.html | hqrrr/arduino_project_anwendungswerkstatt | d42cd26f5b64e79a7b8f20c08a32e0230d6259bb | [
"Apache-2.0"
] | null | null | null | Python/output/charts/chart_heater_2021-01-23.html | hqrrr/arduino_project_anwendungswerkstatt | d42cd26f5b64e79a7b8f20c08a32e0230d6259bb | [
"Apache-2.0"
] | null | null | null | Python/output/charts/chart_heater_2021-01-23.html | hqrrr/arduino_project_anwendungswerkstatt | d42cd26f5b64e79a7b8f20c08a32e0230d6259bb | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<style>
.error {
color: red;
}
</style>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega@5"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega-lite@4.8.1"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega-embed@6"></script>
</head>
<body>
<div id="vis"></div>
<script>
(function(vegaEmbed) {
var spec = {"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"name": "data-eadf6663a33cc33451223379fa85ae50"}, "mark": "line", "encoding": {"x": {"type": "nominal", "field": "Date"}, "y": {"type": "quantitative", "field": "heater_onOff"}}, "$schema": "https://vega.github.io/schema/vega-lite/v4.8.1.json", "datasets": {"data-eadf6663a33cc33451223379fa85ae50": [{"Date": "23.10.2021 12:10:28", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}, {"Date": "23.10.2021 12:10:53", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}, {"Date": "23.11.2021 12:11:18", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}, {"Date": "23.11.2021 12:11:43", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}, {"Date": "23.12.2021 12:12:09", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}, {"Date": "23.12.2021 12:12:34", "t_mean": 32.8, "Temperature": 22.5, "Humidity": 20.0, "heater_onOff": 1, "T_set": 40.0, "is_sitting": 0, "T00_is_chair": 50.7, "T01_is_chair": 23.9, "T02_is_chair": 23.8, "PID Output": 19.0, "consumption": 0.0}]}};
var embedOpt = {"mode": "vega-lite"};
function showError(el, error){
el.innerHTML = ('<div class="error" style="color:red;">'
+ '<p>JavaScript Error: ' + error.message + '</p>'
+ "<p>This usually means there's a typo in your chart specification. "
+ "See the javascript console for the full traceback.</p>"
+ '</div>');
throw error;
}
const el = document.getElementById('vis');
vegaEmbed("#vis", spec, embedOpt)
.catch(error => showError(el, error));
})(vegaEmbed);
</script>
</body>
</html> | 84.885714 | 1,870 | 0.600135 |
dda3c7f4b03fd3fc686664c855bb80440e9bb3a4 | 231 | php | PHP | src/Interfaces/Field.php | peter44322/dy-form | ab7c0e607e4bf6938363f8633fc2156f60fb8ba6 | [
"MIT"
] | 2 | 2019-07-14T18:56:49.000Z | 2019-08-30T07:52:14.000Z | src/Interfaces/Field.php | peter44322/dy-form | ab7c0e607e4bf6938363f8633fc2156f60fb8ba6 | [
"MIT"
] | null | null | null | src/Interfaces/Field.php | peter44322/dy-form | ab7c0e607e4bf6938363f8633fc2156f60fb8ba6 | [
"MIT"
] | null | null | null | <?php
namespace Peterzaccha\DyForm\Interfaces;
use Peterzaccha\DyForm\Models\DyColumn;
interface Field
{
public function __construct(DyColumn $column);
public function render();
public function setValue($value);
}
| 15.4 | 50 | 0.748918 |
7992957cc8993984e81206a44a7b16520a6a1684 | 4,067 | sql | SQL | wget3.sql | QuoInsight/sql | 3d4c4a893bb0c6bad4afa3f2983598b98a064837 | [
"MIT"
] | null | null | null | wget3.sql | QuoInsight/sql | 3d4c4a893bb0c6bad4afa3f2983598b98a064837 | [
"MIT"
] | null | null | null | wget3.sql | QuoInsight/sql | 3d4c4a893bb0c6bad4afa3f2983598b98a064837 | [
"MIT"
] | null | null | null | DECLARE
TYPE txtHash IS TABLE OF VARCHAR2(255) INDEX BY VARCHAR2(50);
headers txtHash;
data CLOB;
l_count NUMBER;
/*------------------------------------------------------------------*/
FUNCTION println(p_Data IN OUT NOCOPY CLOB)
RETURN NUMBER
AS
i number;
startPos number;
endPos number;
chunkSize number;
totalSize number;
lc_buffer varchar2(32767);
BEGIN
-- http://stackoverflow.com/questions/11647041/reading-clob-line-by-line-with-pl-sql
if ( dbms_lob.isopen(p_Data) != 1 ) then
dbms_lob.open(p_Data, 0);
end if;
i := 0;
startPos := 1;
totalSize := Dbms_Lob.getlength(p_Data);
loop
i := i + 1;
endPos := instr(p_Data, Chr(10), startPos);
IF endPos=0 THEN endPos:=totalSize+1; END IF;
IF endPos > startPos THEN
chunkSize := (endPos-startPos);
dbms_lob.read(p_Data, chunkSize, startPos, lc_buffer);
ELSE
lc_buffer := NULL;
END IF;
dbms_output.put_line(SubStr(lc_buffer,1,240));
startPos := endPos+1;
EXIT WHEN startPos >= totalSize;
end loop;
if ( dbms_lob.isopen(p_Data) = 1 ) then
dbms_lob.close(p_Data);
end if;
RETURN i;
END;
/*------------------------------------------------------------------*/
PROCEDURE write_lob(l IN OUT NOCOPY CLOB, v VARCHAR2) AS
BEGIN
--IF ( dbms_lob.isopen(l) != 1 ) THEN
-- dbms_lob.createtemporary(l, TRUE, dbms_lob.call);
-- dbms_lob.open(l, dbms_lob.lob_readwrite);
--END IF;
dbms_lob.writeappend(l, length(v), v);
END;
/*------------------------------------------------------------------*/
FUNCTION wget3(
url VARCHAR2, method VARCHAR2 DEFAULT 'GET',
headers txtHash, data CLOB, timeout NUMBER DEFAULT 0
) RETURN CLOB AS
httpReq utl_http.req;
headerName VARCHAR2(240);
startPos NUMBER:=1;
chunkSize NUMBER:=1024;
totalSize number;
lc_buffer varchar2(32767);
httpResp utl_http.resp;
respTxt VARCHAR2(1024);
tempLob CLOB;
BEGIN
dbms_lob.createtemporary(tempLob, TRUE, dbms_lob.call);
dbms_lob.open(tempLob, dbms_lob.lob_readwrite);
-- utl_http.set_wallet(<wallet_path>, <wallet_password>);
utl_http.set_response_error_check(false); -- do not raise an exception when get_response returns a status codes of 4xx or 5xx
utl_http.set_persistent_conn_support(false);
httpReq := utl_http.begin_request(url, method);
utl_http.set_header(httpReq, 'User-Agent', 'Mozilla/4.0');
utl_http.set_header(httpReq, 'Content-Length', Nvl(LengthB(data),0));
headerName := headers.FIRST;
WHILE headerName IS NOT NULL LOOP
utl_http.set_header(httpReq, headerName, headers(headerName));
headerName := headers.NEXT(headerName);
END LOOP;
WHILE startPos < DBMS_LOB.getlength(data) LOOP
DBMS_LOB.READ(data, chunkSize, startPos, lc_buffer);
utl_http.write_text(httpReq, lc_buffer);
startPos := startPos + chunkSize;
END LOOP;
httpResp := utl_http.get_response(httpReq);
IF (httpResp.status_code <> UTL_HTTP.HTTP_OK) THEN
dbms_output.put_line('responseCode: '||httpResp.status_code);
END IF;
BEGIN
LOOP
utl_http.read_text(httpResp, respTxt, 1024);
dbms_lob.writeappend(tempLob, length(respTxt), respTxt);
END LOOP;
EXCEPTION
WHEN utl_http.end_of_body THEN
dbms_output.put_line('==end read_text==');
WHEN OTHERS THEN
dbms_output.put_line('ERR #'||SQLCODE||': '||SQLERRM);
END;
utl_http.end_response(httpResp);
RETURN tempLob;
END;
/*------------------------------------------------------------------*/
BEGIN
headers('Content-Type') := 'application/x-www-form-urlencoded';
headers('TEST') := 'TEST12';
dbms_lob.createtemporary(data, TRUE, dbms_lob.call);
dbms_lob.open(data, dbms_lob.lob_readwrite);
write_lob(data, 'A=1&B=2');
data := wget3('https://www.google.com', 'POST', headers, data, 0);
l_count := println(data);
--dbms_lob.freetemporary(data);
END;
| 29.686131 | 129 | 0.615933 |
6232f488e62dd07233640879ff91ffd88de0757d | 4,533 | kt | Kotlin | src/main/kotlin/com/valaphee/blit/source/dav/DavSource.kt | valaphee/accumuload | e686d5898553021e1b4f3e825350f46472f25e4f | [
"Apache-2.0"
] | 7 | 2022-01-05T04:08:29.000Z | 2022-02-10T03:26:40.000Z | src/main/kotlin/com/valaphee/blit/source/dav/DavSource.kt | valaphee/accumuload | e686d5898553021e1b4f3e825350f46472f25e4f | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/com/valaphee/blit/source/dav/DavSource.kt | valaphee/accumuload | e686d5898553021e1b4f3e825350f46472f25e4f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021-2022, Valaphee.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.valaphee.blit.source.dav
import com.fasterxml.jackson.module.kotlin.readValue
import com.valaphee.blit.source.NotFoundError
import com.valaphee.blit.source.Source
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.auth.Auth
import io.ktor.client.plugins.auth.providers.BasicAuthCredentials
import io.ktor.client.plugins.auth.providers.basic
import io.ktor.client.plugins.cookies.HttpCookies
import io.ktor.client.plugins.json.JacksonSerializer
import io.ktor.client.plugins.json.JsonPlugin
import io.ktor.client.request.request
import io.ktor.client.statement.readBytes
import io.ktor.client.statement.request
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.URLBuilder
import io.ktor.http.encodedPath
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
/**
* @author Kevin Ludwig
*/
class DavSource(
internal val url: String,
internal val username: String,
private val password: String,
internal val nextcloud: Boolean,
internal val nextcloudUploadChunkSize: Long
) : Source<DavEntry> {
internal val httpClient by lazy {
HttpClient(OkHttp) {
engine {
config {
sslSocketFactory(socketFactory, trustManagers[0])
hostnameVerifier { _, _ -> true }
}
}
expectSuccess = false
install(HttpTimeout) { socketTimeoutMillis = 60_000L }
install(HttpCookies)
install(Auth) {
basic {
sendWithoutRequest { true }
credentials { BasicAuthCredentials(this@DavSource.username, this@DavSource.password) }
}
}
install(JsonPlugin) {
serializer = JacksonSerializer(xmlMapper)
accept(ContentType.Application.Xml)
}
}
}
internal val _url = if (nextcloud) "${url}/files/${username}" else url
internal val path = URLBuilder(_url).encodedPath
override val home get() = "/"
override suspend fun get(path: String): DavEntry {
val path = if (path.startsWith('/')) path.substring(1) else path // Unix path correction, "." ("") and "/" are the same
val httpResponse = httpClient.request("$_url/$path") { method = httpMethodPropfind }
return when (httpResponse.status) {
HttpStatusCode.MultiStatus -> {
val href = httpResponse.request.url.encodedPath
xmlMapper.readValue<Multistatus>(httpResponse.readBytes()).response.find { it.href.equals(href, true) }?.propstat?.find { it.status == "HTTP/1.1 200 OK" }?.prop?.let { DavEntry(this, path, it) } ?: TODO()
}
HttpStatusCode.NotFound -> throw NotFoundError(path)
else -> TODO()
}
}
override fun close() {
httpClient.close()
}
companion object {
private val trustManagers = arrayOf<X509TrustManager>(object : X509TrustManager {
private val parent = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(null as KeyStore?) }.trustManagers.find { it is X509TrustManager } as X509TrustManager
override fun checkClientTrusted(chain: Array<out X509Certificate>, authType: String) = parent.checkClientTrusted(chain, authType)
override fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String) = Unit
override fun getAcceptedIssuers() = parent.acceptedIssuers
})
private val socketFactory = SSLContext.getInstance("TLS").apply { init(null, trustManagers, SecureRandom()) }.socketFactory
}
}
| 40.115044 | 220 | 0.68608 |
bb5788c3b60830be20c2db5291aeca310dc40806 | 470 | rs | Rust | Rust/Algorithms/1374.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | 2 | 2021-01-15T17:22:54.000Z | 2021-05-16T19:58:02.000Z | Rust/Algorithms/1374.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | null | null | null | Rust/Algorithms/1374.rs | DimitrisJim/leetcode_solutions | 765ea578748f8c9b21243dec9dc8a16163e85c0c | [
"Unlicense"
] | null | null | null | impl Solution {
pub fn generate_the_string(n: i32) -> String {
if n == 1 {
return String::from("a");
}
let (excess, takes) = match n & 1 == 1 {
true => ("bc", n-2),
false => ("b", n-1),
};
let mut res: String = "a"
.chars()
.into_iter()
.cycle()
.take(takes as usize)
.collect();
res.push_str(excess);
res
}
}
| 23.5 | 50 | 0.389362 |
857d5ee12a7e764050ac46281a99aa03f281cc3f | 560 | js | JavaScript | src/middleware/service/signing/account/list.js | ufwd-dev/activity | d9f7619ca7211075d53e1a6749722fbbb064997a | [
"MIT"
] | 1 | 2020-07-28T12:07:13.000Z | 2020-07-28T12:07:13.000Z | src/middleware/service/signing/account/list.js | ufwd-dev/activity | d9f7619ca7211075d53e1a6749722fbbb064997a | [
"MIT"
] | 20 | 2018-06-17T21:41:33.000Z | 2019-07-27T12:09:04.000Z | src/middleware/service/signing/account/list.js | ufwd-dev/activity | d9f7619ca7211075d53e1a6749722fbbb064997a | [
"MIT"
] | null | null | null | 'use strict';
const {throwError} = require('error-standardize');
module.exports = function* getAccountAttendanceList(req, res, next) {
const Attendance = res.sequelize.model('ufwdAttendance');
const Account = res.sequelize.model('account');
const accountId = req.params.accountId;
const account = yield Account.findOne({
where: {
id: accountId
}
});
if (!account) {
throwError('The account is not existed', 404);
}
const attendanceList = yield Attendance.findAll({
where: {
accountId
}
});
res.data(attendanceList);
next();
}; | 19.310345 | 69 | 0.691071 |
a03d73567ba2dc7219d3db37c0e92a937c78ef90 | 264 | swift | Swift | ProjectPharma/Pharma/PresentationLayer/UserStories/ComponentInfo/ComponentInfoInput.swift | MadL0rd/Pharma | 5bfded05b349ab5f9fc10a19eec5579b65924770 | [
"Apache-2.0"
] | null | null | null | ProjectPharma/Pharma/PresentationLayer/UserStories/ComponentInfo/ComponentInfoInput.swift | MadL0rd/Pharma | 5bfded05b349ab5f9fc10a19eec5579b65924770 | [
"Apache-2.0"
] | null | null | null | ProjectPharma/Pharma/PresentationLayer/UserStories/ComponentInfo/ComponentInfoInput.swift | MadL0rd/Pharma | 5bfded05b349ab5f9fc10a19eec5579b65924770 | [
"Apache-2.0"
] | null | null | null | //
// ComponentInfoInput.swift
// Pharma
//
// Created by Антон Текутов on 20.06.2021.
//
protocol CustomizableComponentInfoViewModel: AnyObject {
var output: ComponentInfoOutput? { get set }
var component: SupplementComponent! { get set }
}
| 18.857143 | 56 | 0.689394 |
6d10bfeec8541aeb25e97ba07a77bb97777b92e3 | 195 | sql | SQL | PL3/Ex2/2.sql | DFTF-PConsole/BD-PLs-PostgreSQL-LEI-2021 | b71055a42ab7f5621b103608b0819d5d8b3b62b8 | [
"MIT"
] | null | null | null | PL3/Ex2/2.sql | DFTF-PConsole/BD-PLs-PostgreSQL-LEI-2021 | b71055a42ab7f5621b103608b0819d5d8b3b62b8 | [
"MIT"
] | null | null | null | PL3/Ex2/2.sql | DFTF-PConsole/BD-PLs-PostgreSQL-LEI-2021 | b71055a42ab7f5621b103608b0819d5d8b3b62b8 | [
"MIT"
] | null | null | null | SELECT e.nome "NOME", e.sal "SALARIO", e.ndep "N DEP", d.nome "DEPARTAMENTO"
FROM dep AS d, emp AS e
WHERE e.ndep = d.ndep
AND UPPER(e.nome) LIKE 'A% R%'
ORDER BY d.nome ASC, e.nome ASC
; | 32.5 | 76 | 0.641026 |
a3f4620fb2cecc256428a9d18403ebc3bbd37d98 | 885 | sql | SQL | Redgate/Tables/dbo.tbl_stg_Jira_Deployment.sql | ReubenUnruh/PowerJiraSqlRefresh | 18bb8f911eb6244c17ebdac4af335feb9f096099 | [
"MIT"
] | null | null | null | Redgate/Tables/dbo.tbl_stg_Jira_Deployment.sql | ReubenUnruh/PowerJiraSqlRefresh | 18bb8f911eb6244c17ebdac4af335feb9f096099 | [
"MIT"
] | null | null | null | Redgate/Tables/dbo.tbl_stg_Jira_Deployment.sql | ReubenUnruh/PowerJiraSqlRefresh | 18bb8f911eb6244c17ebdac4af335feb9f096099 | [
"MIT"
] | null | null | null | CREATE TABLE [dbo].[tbl_stg_Jira_Deployment]
(
[Display_Name] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Deployment_Url] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[State] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Last_Updated] [datetime] NULL,
[Pipeline_Id] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Pipeline_Display_Name] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Pipeline_Url] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Environment_Id] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Refresh_Id] [int] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_stg_Jira_Deployment] ADD CONSTRAINT [PK_tbl_stg_Jira_Deployment] PRIMARY KEY CLUSTERED ([Deployment_Url]) ON [PRIMARY]
GO
GRANT INSERT ON [dbo].[tbl_stg_Jira_Deployment] TO [JiraRefreshRole]
GO
| 49.166667 | 143 | 0.79209 |
43e0cc71af17b70877204a3fcb476ab59024e3c8 | 1,039 | go | Go | internal/service/storage.go | Sergey1011010/insights-operator-gathering-conditions-service | fa6ba8991a26722ec948ece956291de433d784fa | [
"Apache-2.0"
] | null | null | null | internal/service/storage.go | Sergey1011010/insights-operator-gathering-conditions-service | fa6ba8991a26722ec948ece956291de433d784fa | [
"Apache-2.0"
] | null | null | null | internal/service/storage.go | Sergey1011010/insights-operator-gathering-conditions-service | fa6ba8991a26722ec948ece956291de433d784fa | [
"Apache-2.0"
] | null | null | null | package service
import (
"fmt"
"io/ioutil"
"os"
"github.com/rs/zerolog/log"
)
type StorageInterface interface {
Find(res string) []byte
}
type StorageConfig struct {
RulesPath string `mapstructure:"rules_path" toml:"rules_path"`
}
type Storage struct {
path string
cache map[string][]byte
}
func NewStorage(cfg StorageConfig) *Storage {
return &Storage{
path: cfg.RulesPath,
cache: make(map[string][]byte),
}
}
func (s *Storage) Find(path string) []byte {
// use the in-memory data
data, ok := s.cache[path]
if ok {
return data
}
// or try to load it from the file
data, err := s.readFile(path)
if err != nil {
log.Warn().Msgf("Resource not found: '%s'", path)
return nil
}
return data
}
func (s *Storage) readFile(path string) ([]byte, error) {
f, err := os.Open(fmt.Sprintf("%s/%s", s.path, path))
if err != nil {
return nil, err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
// add the bytes to cache
s.cache[path] = data
return data, nil
}
| 15.984615 | 63 | 0.649663 |
93de60de52e96280b4cbe7186dab78d4d4e7e137 | 1,062 | sql | SQL | INFO/Books Codes/Oracle PLSQL Tips and Techniques/OutputChapter13/13_22.sql | nabeelkhan/Oracle-DBA-Life | 102a3d14cfd102f38968f2f62f4ec3e019d33b21 | [
"MIT"
] | null | null | null | INFO/Books Codes/Oracle PLSQL Tips and Techniques/OutputChapter13/13_22.sql | nabeelkhan/Oracle-DBA-Life | 102a3d14cfd102f38968f2f62f4ec3e019d33b21 | [
"MIT"
] | null | null | null | INFO/Books Codes/Oracle PLSQL Tips and Techniques/OutputChapter13/13_22.sql | nabeelkhan/Oracle-DBA-Life | 102a3d14cfd102f38968f2f62f4ec3e019d33b21 | [
"MIT"
] | null | null | null | -- ***************************************************************************
-- File: 13_22.sql
--
-- Developed By TUSC
--
-- Disclaimer: Neither Osborne/McGraw-Hill, TUSC, nor the author warrant
-- that this source code is error-free. If any errors are
-- found in this source code, please report them to TUSC at
-- (630)960-2909 ext 1011 or trezzoj@tusc.com.
-- ***************************************************************************
SPOOL 13_22.lis
BREAK ON r_name SKIP 1
COLUMN r_name FORMAT a80
COLUMN name FORMAT a80
COLUMN r_link FORMAT a80
SET HEADING OFF
SELECT DECODE(referenced_type, 'NON-EXISTENT', '.....',
referenced_type) || ' ' || referenced_owner ||
'.' || referenced_name r_name, ' is referenced by: ' ||
type || ' ' || owner || '.' || name name,
' Referenced Link: ' || DECODE(referenced_link_name,
NULL, 'none', referenced_link_name) r_link
FROM dba_dependencies
WHERE owner NOT IN ('SYS', 'SYSTEM')
ORDER BY 1,2;
SPOOL OFF
| 35.4 | 78 | 0.532957 |
402a4c9ddce96b9d61a03cca3c7566e9663ce714 | 31,657 | py | Python | python3_codes/utils_scFAN.py | sperfu/scFAN | b5469b4968974e08e6d3aec1be69663916cd32f8 | [
"MIT"
] | 7 | 2020-01-15T20:13:29.000Z | 2021-07-13T14:50:06.000Z | python3_codes/utils_scFAN.py | uci-cbcl/scFAN | b1955c88c6ec97c447c254dc0ebdd33778e09099 | [
"MIT"
] | 3 | 2021-02-12T10:46:44.000Z | 2021-12-31T02:57:19.000Z | python3_codes/utils_scFAN.py | uci-cbcl/scFAN | b1955c88c6ec97c447c254dc0ebdd33778e09099 | [
"MIT"
] | 2 | 2020-01-30T00:49:20.000Z | 2022-01-14T04:18:59.000Z | import numpy as np
from pybedtools import BedTool, Interval
import pyfasta
import parmap
import copy
# Standard library imports
import os
import itertools
from data_iter_scFAN import DataIterator
import pybedtools
import pdb
import subprocess
t_flag = subprocess.getstatusoutput('mkdir tmp_scFAN')
pybedtools.set_tempdir('tmp_scFAN')
batch_size = 100
genome_sizes_file = 'resources/hg19.autoX.chrom.sizes'
genome_fasta_file = 'resources/hg19.fa'
blacklist_file = 'resources/blacklist.bed.gz'
genome_window_size = 200
genome_window_step = 50
shift_size = 20
def set_seed(seed):
np.random.seed(seed)
def chroms_filter(feature, chroms):
if feature.chrom in chroms:
return True
return False
def subset_chroms(chroms, bed):
result = bed.filter(chroms_filter, chroms).saveas()
return BedTool(result.fn)
def get_genome_bed():
genome_sizes_info = np.loadtxt(genome_sizes_file, dtype=str)
chroms = list(genome_sizes_info[:,0])
chroms_sizes = list(genome_sizes_info[:,1].astype(int))
genome_bed = []
for chrom, chrom_size in zip(chroms, chroms_sizes):
genome_bed.append(Interval(chrom, 0, chrom_size))
genome_bed = BedTool(genome_bed)
return chroms, chroms_sizes, genome_bed
def get_bigwig_rc_order(bigwig_names):
assert len(set(bigwig_names)) == len(bigwig_names)
rc_indices = np.arange(len(bigwig_names))
for ind, bigwig_name in enumerate(bigwig_names):
if bigwig_name[-4:] == '_fwd':
bigwig_rc_name = bigwig_name[:-4] + '_rev'
bigwig_rc_index = bigwig_names.index(bigwig_rc_name)
rc_indices[bigwig_rc_index] = ind
if bigwig_name[-4:] == '_rev':
bigwig_rc_name = bigwig_name[:-4] + '_fwd'
bigwig_rc_index = bigwig_names.index(bigwig_rc_name)
rc_indices[bigwig_rc_index] = ind
return rc_indices
def make_features_multiTask(positive_windows, y_positive, nonnegative_regions_bed,
bigwig_files, bigwig_names, genome, epochs, valid_chroms, test_chroms):
chroms, chroms_sizes, genome_bed = get_genome_bed()
train_chroms = chroms
for chrom in valid_chroms + test_chroms:
train_chroms.remove(chrom)
genome_bed_train, genome_bed_valid, genome_bed_test = \
[subset_chroms(chroms_set, genome_bed) for chroms_set in
(train_chroms, valid_chroms, test_chroms)]
positive_windows_train = []
positive_windows_valid = []
positive_windows_test = []
positive_data_train = []
positive_data_valid = []
positive_data_test = []
import pdb
print('Splitting positive windows into training, validation, and testing sets')
for positive_window, target_array in itertools.izip(positive_windows, y_positive):
if len(positive_window.chrom) > 8:
pdb.set_trace()
chrom = positive_window.chrom
start = int(positive_window.start)
stop = int(positive_window.stop)
if chrom in test_chroms:
positive_windows_test.append(positive_window)
positive_data_test.append((chrom, start, stop, shift_size, bigwig_files, [], target_array))
elif chrom in valid_chroms:
positive_windows_valid.append(positive_window)
positive_data_valid.append((chrom, start, stop, shift_size, bigwig_files, [], target_array))
else:
positive_windows_train.append(positive_window)
positive_data_train.append((chrom, start, stop, shift_size, bigwig_files, [], target_array))
positive_windows_train = BedTool(positive_windows_train)
positive_windows_valid = BedTool(positive_windows_valid)
positive_windows_test = BedTool(positive_windows_test)
import pdb
print('Getting negative training examples')
negative_windows_train = BedTool.cat(*(epochs*[positive_windows]), postmerge=False)
#negative_windows_train = BedTool.cat(*(10*[positive_windows]), postmerge=False)
#pdb.set_trace()
negative_windows_train = negative_windows_train.shuffle(g=genome_sizes_file,
incl=genome_bed_train.fn,
excl=nonnegative_regions_bed.fn,
noOverlapping=False,
seed=np.random.randint(-214783648, 2147483647))
#seed=np.random.randint(-21478364, 21474836))
print('Getting negative validation examples')
negative_windows_valid = positive_windows_valid.shuffle(g=genome_sizes_file,
incl=genome_bed_valid.fn,
excl=nonnegative_regions_bed.fn,
noOverlapping=False,
seed=np.random.randint(-214783648, 2147483647))
#seed=np.random.randint(-21478364, 21474836))
print('Getting negative testing examples')
negative_windows_test = positive_windows_test.shuffle(g=genome_sizes_file,
incl=genome_bed_test.fn,
excl=nonnegative_regions_bed.fn,
noOverlapping=False,
seed=np.random.randint(-214783648, 2147483647))
#seed=np.random.randint(-21478364, 21474836))
# Train
print('Extracting data from negative training BEDs')
negative_targets = np.zeros(y_positive.shape[1])
negative_data_train = [(window.chrom, window.start, window.stop, shift_size, bigwig_files, [], negative_targets)
for window in negative_windows_train]
# Validation
print('Extracting data from negative validation BEDs')
negative_data_valid = [(window.chrom, window.start, window.stop, shift_size, bigwig_files, [], negative_targets)
for window in negative_windows_valid]
# Test
print('Extracting data from negative testing BEDs')
negative_data_test = [(window.chrom, window.start, window.stop, shift_size, bigwig_files, [], negative_targets)
for window in negative_windows_test]
num_positive_train_windows = len(positive_data_train)
data_valid = negative_data_valid + positive_data_valid
data_test = negative_data_test + positive_data_test
print('Shuffling training data')
data_train = []
for i in xrange(epochs):
epoch_data = []
epoch_data.extend(positive_data_train)
epoch_data.extend(negative_data_train[i*num_positive_train_windows:(i+1)*num_positive_train_windows])
np.random.shuffle(epoch_data)
data_train.extend(epoch_data)
print('Generating data iterators')
bigwig_rc_order = get_bigwig_rc_order(bigwig_names)
datagen_train = DataIterator(data_train, genome, batch_size, L, bigwig_rc_order)
datagen_valid = DataIterator(data_valid, genome, batch_size, L, bigwig_rc_order)
datagen_test = DataIterator(data_test, genome, batch_size, L, bigwig_rc_order)
print(len(datagen_train), 'training samples')
print(len(datagen_valid), 'validation samples')
print(len(datagen_test), 'test samples')
return datagen_train, datagen_valid, datagen_test, data_test
def data_to_bed(data):
intervals = []
for datum in data:
chrom = datum[0]
start = datum[1]
stop = datum[2]
intervals.append(Interval(chrom, start, stop))
return BedTool(intervals)
def extract_data_from_bed(args, shift, label, gencode):
peaks = args[0]
bigwig_files = args[1]
meta = args[2]
data = []
if gencode:
cpg_bed = BedTool('resources/cpgisland.bed.gz')
cds_bed = BedTool('resources/wgEncodeGencodeBasicV19.cds.merged.bed.gz')
intron_bed = BedTool('resources/wgEncodeGencodeBasicV19.intron.merged.bed.gz')
promoter_bed = BedTool('resources/wgEncodeGencodeBasicV19.promoter.merged.bed.gz')
utr5_bed = BedTool('resources/wgEncodeGencodeBasicV19.utr5.merged.bed.gz')
utr3_bed = BedTool('resources/wgEncodeGencodeBasicV19.utr3.merged.bed.gz')
peaks_cpg_bedgraph = peaks.intersect(cpg_bed, wa=True, c=True)
peaks_cds_bedgraph = peaks.intersect(cds_bed, wa=True, c=True)
peaks_intron_bedgraph = peaks.intersect(intron_bed, wa=True, c=True)
peaks_promoter_bedgraph = peaks.intersect(promoter_bed, wa=True, c=True)
peaks_utr5_bedgraph = peaks.intersect(utr5_bed, wa=True, c=True)
peaks_utr3_bedgraph = peaks.intersect(utr3_bed, wa=True, c=True)
for cpg, cds, intron, promoter, utr5, utr3 in itertools.izip(peaks_cpg_bedgraph,peaks_cds_bedgraph,peaks_intron_bedgraph,peaks_promoter_bedgraph,peaks_utr5_bedgraph,peaks_utr3_bedgraph):
chrom = cpg.chrom
peak_start = cpg.start
peak_stop = cpg.stop
peak_mid = (peak_start + peak_stop)/2
start = peak_mid - genome_window_size/2
stop = peak_mid + genome_window_size/2
if shift:
shift_size = peak_stop - start - 75 - 1
else:
shift_size = 0
gencode = np.array([cpg.count, cds.count, intron.count, promoter.count, utr5.count, utr3.count], dtype=bool)
meta_gencode = np.append(meta, gencode)
data.append((chrom, start, stop, shift_size, bigwig_files, meta_gencode, label))
else:
for peak in peaks:
chrom = peak.chrom
peak_start = peak.start
peak_stop = peak.stop
peak_mid = (peak_start + peak_stop)/2
start = peak_mid - genome_window_size/2
stop = peak_mid + genome_window_size/2
if shift:
shift_size = peak_stop - start - 75 - 1
else:
shift_size = 0
data.append((chrom, start, stop, shift_size, bigwig_files, meta, label))
return data
def valid_test_split_wrapper(bed, valid_chroms, test_chroms):
bed_train = []
bed_valid = []
bed_test = []
for interval in bed:
chrom = interval.chrom
start = interval.start
stop = interval.stop
if chrom in test_chroms:
bed_test.append(interval)
elif chrom in valid_chroms:
bed_valid.append(interval)
else:
bed_train.append(interval)
bed_train = BedTool(bed_train)
bed_valid = BedTool(bed_valid)
bed_test = BedTool(bed_test)
return bed_train, bed_valid, bed_test
def negative_shuffle_wrapper(args, include_bed, num_copies, noOverlapping):
positive_windows = args[0]
nonnegative_regions_bed = args[1]
bigwig_files = args[2]
randomseed = args[3]
if num_copies > 1:
positive_windows = BedTool.cat(*(num_copies * [positive_windows]), postmerge=False)
negative_windows = positive_windows.shuffle(g=genome_sizes_file,
incl=include_bed.fn,
excl=nonnegative_regions_bed.fn,
noOverlapping=noOverlapping,
seed=randomseed)
return negative_windows
def get_onehot_chrom(chrom):
fasta = pyfasta.Fasta(genome_fasta_file)
chr_str = str(fasta[chrom]).upper()
d = np.array(['A','C','G','T'])
y = np.fromstring(chr_str, dtype='|S1')[:, np.newaxis] == d
return y
def load_genome():
chroms = list(np.loadtxt(genome_sizes_file, usecols=[0], dtype=str))
onehot_chroms = parmap.map(get_onehot_chrom, chroms)
genome_dict = dict(zip(chroms, onehot_chroms))
return genome_dict
def intersect_count(chip_bed, windows_file):
windows = BedTool(windows_file)
chip_bedgraph = windows.intersect(chip_bed, wa=True, c=True, f=1.0*(genome_window_size/2+1)/genome_window_size, sorted=True)
bed_counts = [i.count for i in chip_bedgraph]
return bed_counts
def make_blacklist():
blacklist = BedTool(blacklist_file)
blacklist = blacklist.slop(g=genome_sizes_file, b=L)
# Add ends of the chromosomes to the blacklist
genome_sizes_info = np.loadtxt(genome_sizes_file, dtype=str)
chroms = list(genome_sizes_info[:,0])
chroms_sizes = list(genome_sizes_info[:,1].astype(int))
blacklist2 = []
for chrom, size in zip(chroms, chroms_sizes):
blacklist2.append(Interval(chrom, 0, L))
blacklist2.append(Interval(chrom, size - L, size))
blacklist2 = BedTool(blacklist2)
blacklist = blacklist.cat(blacklist2)
return blacklist
def get_chip_beds_multiple(input_dir,process_batch):
chip_info_file = input_dir + '/chip.txt'
chip_info = np.loadtxt(chip_info_file, dtype=str)
if len(chip_info.shape) == 1:
chip_info = np.reshape(chip_info, (-1,len(chip_info)))
tfs = list(chip_info[:, 1])
chip_bed_files = [input_dir + '/' + i for i in chip_info[:,0]]
chip_beds = [BedTool(chip_bed_file) for chip_bed_file in chip_bed_files]
if process_batch:
batch_name_list = list(np.unique(chip_info[:,1]))
batch_list_all_dict = {}
exchange_dict = {}
for index,item in enumerate(batch_name_list):
batch_tmp = [chip_beds[i] for i in list(np.where(chip_info[:,1]==item)[0])]
batch_0 = batch_tmp[0]
batch_tmp = batch_tmp[1:]
print('concatenate batch bedfiles for batch %d...'%(index))
batch_list = batch_0.cat(*batch_tmp,postmerge=False)
if item not in batch_list_all_dict.keys():
batch_list_all_dict[item] = batch_list
batch_name_list_tmp = copy.deepcopy(batch_name_list)
batch_name_list_tmp.remove(item)
if len(batch_name_list_tmp) > 1:
exchange_dict[item] = batch_name_list_tmp
else:
exchange_dict[item] = batch_name_list_tmp[0]
else:
print("Error!!!")
else:
print('No need process batch,continue...')
print('Sorting BED files)'
chip_beds = [chip_bed.sort() for chip_bed in chip_beds]
merged_chip_bed_list = []
for item in chip_beds:
if 1 > 1:
merged_chip_bed = BedTool.cat(*item)
else:
merged_chip_bed = item
merged_chip_bed_list.append(merged_chip_bed)
if process_batch:
return tfs, chip_beds, merged_chip_bed_list,batch_list_all_dict,chip_info[:,1],exchange_dict
else:
return tfs, chip_beds, merged_chip_bed_list
def get_chip_beds(input_dir):
chip_info_file = input_dir + '/chip.txt'
chip_info = np.loadtxt(chip_info_file, dtype=str)
if len(chip_info.shape) == 1:
chip_info = np.reshape(chip_info, (-1,len(chip_info)))
tfs = list(chip_info[:, 1])
chip_bed_files = [input_dir + '/' + i for i in chip_info[:,0]]
pdb.set_trace()
chip_beds = [BedTool(chip_bed_file) for chip_bed_file in chip_bed_files]
print('Sorting BED files')
chip_beds = [chip_bed.sort() for chip_bed in chip_beds]
if len(chip_beds) > 1:
merged_chip_bed = BedTool.cat(*chip_beds)
else:
merged_chip_bed = chip_beds[0]
return tfs, chip_beds, merged_chip_bed
def generate_dict_for_batch_cat(batch_list_all_dict,batch_info,exchange_dict):
batch_tmp_all_dict = {}
for item in np.unique(batch_info):
print('Process batch %s...'%(item))
#pdb.set_trace()
if item not in batch_tmp_all_dict.keys():
batch_list_tmp = exchange_dict[item]
batch_tmp_0 = batch_list_all_dict[batch_list_tmp[0]]
for tmp in batch_list_tmp[1:]:
batch_tmp_all = batch_tmp_0.cat(batch_list_all_dict[tmp],postmerge=False)
batch_tmp_0 = batch_tmp_all
batch_tmp_all_dict[item] = batch_tmp_0
else:
print("duplicate...")
print('Done merge batch...')
return batch_tmp_all_dict
def load_chip_multiTask_multiple(input_dir,process_batch):
if process_batch:
tfs, chip_beds_list, merged_chip_bed_list, batch_list_all_dict, batch_info, exchange_dict = get_chip_beds_multiple(input_dir,process_batch)
else:
tfs, chip_beds_list, merged_chip_bed_list = get_chip_beds_multiple(input_dir,process_batch)
print('Removing peaks outside of X chromosome and autosomes')
chroms, chroms_sizes, genome_bed = get_genome_bed()
blacklist = make_blacklist()
print('Prepare for all the merge batch files')
if process_batch and len(exchange_dict) > 2:
batch_tmp_all_dict = generate_dict_for_batch_cat(batch_list_all_dict,batch_info,exchange_dict)
positive_windows_list = []
print('Windowing genome')
genome_windows = BedTool().window_maker(g=genome_sizes_file, w=genome_window_size,
s=genome_window_step)
for index,merged_chip_bed in enumerate(merged_chip_bed_list):
if process_batch:
print('processing batch peaks...')
#pdb.set_trace()
if len(exchange_dict) == 2:
#merged_chip_bed = merged_chip_bed.intersect(batch_list_all_dict[exchange_dict[batch_info[index]]],wa=True,u=True)
merged_chip_bed = merged_chip_bed.intersect(batch_list_all_dict[exchange_dict[batch_info[index]]])
merged_chip_bed = merged_chip_bed.sort().merge()
merged_chip_bed = merged_chip_bed.intersect(genome_bed, u=True, sorted=True)
else:
merged_chip_bed = merged_chip_bed.intersect(batch_tmp_all_dict[batch_info[index]])
merged_chip_bed = merged_chip_bed.sort().merge()
merged_chip_bed = merged_chip_bed.intersect(genome_bed, u=True, sorted=True)
else:
merged_chip_bed = merged_chip_bed.intersect(genome_bed, u=True, sorted=True)
print('Dataset %d/%d...'%(index+1,len(merged_chip_bed_list)))
print('Extracting windows that overlap at least one ChIP interval')
positive_windows = genome_windows.intersect(merged_chip_bed, u=True, f=1.0*(genome_window_size/2+1)/genome_window_size, sorted=True)
# Exclude all windows that overlap a blacklisted region
print('Removing windows that overlap a blacklisted region')
positive_windows = positive_windows.intersect(blacklist, wa=True, v=True, sorted=True)
# Binary binding target matrix of all positive windows
#pdb.set_trace()
# Generate targets
# Later we want to gather negative windows from the genome that do not overlap
# with a blacklisted or ChIP region
positive_windows_list.append(positive_windows)
return tfs, positive_windows_list
def nonnegative_wrapper(a, bl_file):
bl = BedTool(bl_file)
a_slop = a.slop(g=genome_sizes_file, b=genome_window_size)
return bl.cat(a_slop).fn
def get_chip_bed(input_dir, tf, bl_file):
blacklist = BedTool(bl_file)
chip_info_file = input_dir + '/chip.txt'
chip_info = np.loadtxt(chip_info_file, dtype=str)
if len(chip_info.shape) == 1:
chip_info = np.reshape(chip_info, (-1,len(chip_info)))
tfs = list(chip_info[:, 1])
assert tf in tfs
tf_index = tfs.index(tf)
chip_bed_file = input_dir + '/' + chip_info[tf_index, 0]
chip_bed = BedTool(chip_bed_file)
chip_bed = chip_bed.sort()
#Remove any peaks not in autosomes or X chromosome
chroms, chroms_sizes, genome_bed = get_genome_bed()
chip_bed = chip_bed.intersect(genome_bed, u=True, sorted=True)
#Remove any peaks in blacklist regions
chip_bed = chip_bed.intersect(blacklist, wa=True, v=True, sorted=True)
if chip_info.shape[1] == 3:
relaxed_bed_file = input_dir + '/' + chip_info[tf_index, 2]
relaxed_bed = BedTool(relaxed_bed_file)
relaxed_bed = relaxed_bed.sort()
else:
relaxed_bed = chip_bed
return chip_bed, relaxed_bed
def load_bigwigs_sc(input_dirs,num_pos,bigwig_lists,input_scATAC_dir):
bigwig_names = None
bigwig_files_list = []
for input_dir in input_dirs:
input_bigwig_info_file = input_dir + '/bigwig.txt'
if not os.path.isfile(input_bigwig_info_file):
input_bigwig_names = []
input_bigwig_files_list = []
else:
input_bigwig_info = np.loadtxt(input_bigwig_info_file, dtype=str)
if len(input_bigwig_info.shape) == 1:
input_bigwig_info = np.reshape(input_bigwig_info, (-1,2))
input_bigwig_names = list(input_bigwig_info[:, 1])
### changed here for single cell
input_bigwig_files = [input_dir + '/' + i for i in input_bigwig_info[:,0][:-1]] ## previous_version
#input_bigwig_files = [input_dir + '/' + i for i in input_bigwig_info[:,0]]
input_bigwig_files.append(input_scATAC_dir[0]+'/'+bigwig_lists[num_pos])
#input_bigwig_files.append('/data2/fly/scFAN_data/bigwig_all/'+bigwig_lists[num_pos])
print(input_bigwig_files)
#pdb.set_trace()
if bigwig_names is None:
bigwig_names = input_bigwig_names
else:
assert bigwig_names == input_bigwig_names
bigwig_files_list.append(input_bigwig_files)
return bigwig_names, bigwig_files_list
def load_bigwigs(input_dirs):
bigwig_names = None
bigwig_files_list = []
for input_dir in input_dirs:
input_bigwig_info_file = input_dir + '/bigwig.txt'
if not os.path.isfile(input_bigwig_info_file):
input_bigwig_names = []
input_bigwig_files_list = []
else:
input_bigwig_info = np.loadtxt(input_bigwig_info_file, dtype=str)
if len(input_bigwig_info.shape) == 1:
input_bigwig_info = np.reshape(input_bigwig_info, (-1,2))
input_bigwig_names = list(input_bigwig_info[:, 1])
input_bigwig_files = [input_dir + '/' + i for i in input_bigwig_info[:,0]]
if bigwig_names is None:
bigwig_names = input_bigwig_names
else:
assert bigwig_names == input_bigwig_names
bigwig_files_list.append(input_bigwig_files)
return bigwig_names, bigwig_files_list
def get_output(input_layer, hidden_layers):
output = input_layer
for hidden_layer in hidden_layers:
output = hidden_layer(output)
return output
def scFANet(out,num_recurrent,num_bws):
from keras.models import Sequential
from keras.layers import Flatten, Dense, Dropout, Merge
from keras.layers import Reshape
from keras.layers.core import Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import UpSampling2D
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers.pooling import GlobalMaxPooling2D
from keras.layers.core import Flatten
from keras.optimizers import SGD
from keras import regularizers
from keras.callbacks import ModelCheckpoint
from keras.layers import Concatenate
from keras.models import Model
from keras.layers import Input
forward_input = Input(shape=(1, L, 4 + num_bws*2,))
#reverse_input = Input(shape=(L, 4 + num_bws,))
nkernels = [160,240,480]
in_size = (1,1000,6)
l2_lam = 5e-07
l1_lam = 1e-08
if num_recurrent > 0:
hidden_layers = [
Conv2D(nkernels[0], kernel_size=(1,8), strides=(1,1), padding='same', input_shape=in_size, kernel_regularizer=regularizers.l2(l2_lam)),
BatchNormalization(),
Activation('relu'),
MaxPooling2D(pool_size=(1,4), strides=(1,4)),
Dropout(0.2),
Conv2D(nkernels[1], kernel_size=(1,8), strides=(1,1), padding='same', kernel_regularizer=regularizers.l2(l2_lam)),
BatchNormalization(),
Activation('relu'),
MaxPooling2D(pool_size=(1,4), strides=(1,4)),
Dropout(0.2),
Conv2D(nkernels[1], kernel_size=(1,8), strides=(1,1), padding='same', kernel_regularizer=regularizers.l2(l2_lam)),
BatchNormalization(),
Activation('relu'),
Dropout(0.5),
Flatten(),
Dense(919, kernel_regularizer=regularizers.l1(l1_lam)),
Activation('relu'),
Dense(out, kernel_regularizer=regularizers.l1(l1_lam)),
Activation('sigmoid')
]
else:
pdb.set_trace()
forward_output = get_output(forward_input, hidden_layers)
#reverse_output = get_output(reverse_input, hidden_layers)
#output = merge([forward_output, reverse_output], mode='ave')
output = forward_output
#model = Model(input=[forward_input, reverse_input], output=output)
model = Model(input=forward_input, output=output)
return model
def make_model(num_tfs, num_bws, num_motifs, num_recurrent, num_dense, dropout_rate):
from keras import backend as K
from keras.models import Model
from keras.layers import Dense, Dropout, Activation, Flatten, Layer, merge, Input
from keras.layers.convolutional import Convolution1D, MaxPooling1D
from keras.layers.pooling import GlobalMaxPooling1D
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import Bidirectional, TimeDistributed
'''
import tensorflow as tf
config = tf.ConfigProto(device_count={'gpu':1})
config.gpu_options.allow_growth=True
session = tf.Session(config=config)
'''
forward_input = Input(shape=(L, 4 + num_bws,))
reverse_input = Input(shape=(L, 4 + num_bws,))
if num_recurrent < 0:
hidden_layers = [
Convolution1D(input_dim=4 + num_bws, nb_filter=num_motifs,
filter_length=w, border_mode='valid', activation='relu',
subsample_length=1),
Dropout(0.1),
TimeDistributed(Dense(num_motifs, activation='relu')),
GlobalMaxPooling1D(),
Dropout(dropout_rate),
Dense(num_dense, activation='relu'),
Dropout(dropout_rate),
Dense(num_tfs, activation='sigmoid')
]
elif num_recurrent == 0:
hidden_layers = [
Convolution1D(input_dim=4 + num_bws, nb_filter=num_motifs,
filter_length=w, border_mode='valid', activation='relu',
subsample_length=1),
Dropout(0.1),
TimeDistributed(Dense(num_motifs, activation='relu')),
MaxPooling1D(pool_length=w2, stride=w2),
Dropout(dropout_rate),
Flatten(),
Dense(num_dense, activation='relu'),
Dropout(dropout_rate),
Dense(num_tfs, activation='sigmoid')
]
else:
hidden_layers = [
Convolution1D(input_dim=4 + num_bws, nb_filter=num_motifs,
filter_length=w, border_mode='valid', activation='relu',
subsample_length=1),
Dropout(0.1),
TimeDistributed(Dense(num_motifs, activation='relu')),
MaxPooling1D(pool_length=w2, stride=w2),
Bidirectional(LSTM(num_recurrent, dropout_W=0.1, dropout_U=0.1, return_sequences=True)),
Dropout(dropout_rate),
Flatten(),
Dense(num_dense, activation='relu'),
Dropout(dropout_rate),
Dense(num_tfs, activation='sigmoid')
]
forward_output = get_output(forward_input, hidden_layers)
reverse_output = get_output(reverse_input, hidden_layers)
output = merge([forward_output, reverse_output], mode='ave')
model = Model(input=[forward_input, reverse_input], output=output)
return model
def load_model(modeldir):
tfs_file = modeldir + '/chip.txt'
tfs = np.loadtxt(tfs_file, dtype=str)
if len(tfs.shape) == 0:
tfs = [str(tfs)]
else:
tfs = list(tfs)
bigwig_names_file = modeldir + '/bigwig.txt'
if not os.path.isfile(bigwig_names_file):
bigwig_names = []
else:
bigwig_names = np.loadtxt(bigwig_names_file, dtype=str)
if len(bigwig_names.shape) == 0:
bigwig_names = [str(bigwig_names)]
else:
bigwig_names = list(bigwig_names)
features_file = modeldir + '/feature.txt'
assert os.path.isfile(features_file)
features = np.loadtxt(features_file, dtype=str)
if len(features.shape) == 0:
features = [str(features)]
else:
features = list(features)
from keras.models import model_from_json
model_json_file = open(modeldir + '/model.json', 'r')
model_json = model_json_file.read()
model = model_from_json(model_json)
model.load_weights(modeldir + '/best_model.hdf5')
return tfs, bigwig_names, features, model
def load_bed_data_sc(genome, positive_windows, use_meta, use_gencode, input_dir, is_sorted, big_wig_list, num_pos, input_scATAC_dir, chrom=None):
bed_filtered = positive_windows
print('Generating test data iterator')
bigwig_names, bigwig_files_list = load_bigwigs_sc([input_dir],num_pos,big_wig_list,input_scATAC_dir)
bigwig_files = bigwig_files_list[0]
if use_meta:
meta_names, meta_list = load_meta([input_dir])
meta = meta_list[0]
else:
meta = []
meta_names = None
shift = 0
if use_gencode:
cpg_bed = BedTool('resources/cpgisland.bed.gz')
cds_bed = BedTool('resources/wgEncodeGencodeBasicV19.cds.merged.bed.gz')
intron_bed = BedTool('resources/wgEncodeGencodeBasicV19.intron.merged.bed.gz')
promoter_bed = BedTool('resources/wgEncodeGencodeBasicV19.promoter.merged.bed.gz')
utr5_bed = BedTool('resources/wgEncodeGencodeBasicV19.utr5.merged.bed.gz')
utr3_bed = BedTool('resources/wgEncodeGencodeBasicV19.utr3.merged.bed.gz')
peaks_cpg_bedgraph = bed_filtered.intersect(cpg_bed, wa=True, c=True)
peaks_cds_bedgraph = bed_filtered.intersect(cds_bed, wa=True, c=True)
peaks_intron_bedgraph = bed_filtered.intersect(intron_bed, wa=True, c=True)
peaks_promoter_bedgraph = bed_filtered.intersect(promoter_bed, wa=True, c=True)
peaks_utr5_bedgraph = bed_filtered.intersect(utr5_bed, wa=True, c=True)
peaks_utr3_bedgraph = bed_filtered.intersect(utr3_bed, wa=True, c=True)
data_bed = [(window.chrom, window.start, window.stop, 0, bigwig_files, np.append(meta, np.array([cpg.count, cds.count, intron.count, promoter.count, utr5.count, utr3.count], dtype=bool)))
for window, cpg, cds, intron, promoter, utr5, utr3 in
itertools.izip(bed_filtered, peaks_cpg_bedgraph,peaks_cds_bedgraph,peaks_intron_bedgraph,peaks_promoter_bedgraph,peaks_utr5_bedgraph,peaks_utr3_bedgraph)]
else:
data_bed = [(window.chrom, window.start, window.stop, shift, bigwig_files, meta)
for window in bed_filtered]
#from data_iter import DataIterator
from data_iter_scFAN import DataIterator
#pdb.set_trace()
#tmpp = bed_filtered.saveas('/data1/fly/FactorNet/draw_plot/heatmap_plot/merge_heatmap/H1_bed/%d_bed.bed'%(num_pos))
bigwig_rc_order = get_bigwig_rc_order(bigwig_names)
datagen_bed = DataIterator(data_bed, genome, 100, L, bigwig_rc_order, shuffle=False)
return bigwig_names, datagen_bed
| 43.907074 | 195 | 0.656032 |
c14635494da02a8f75fa1e12483eaa3aa6eb05a4 | 1,431 | rs | Rust | dbcrossbarlib/src/drivers/gs/local_data.rs | faradayio/schemaconv | eeb808354af7d58f1782927eaa9e754d59544011 | [
"Apache-2.0",
"MIT"
] | 29 | 2019-03-14T06:43:01.000Z | 2020-03-14T16:15:26.000Z | dbcrossbarlib/src/drivers/gs/local_data.rs | faradayio/schemaconv | eeb808354af7d58f1782927eaa9e754d59544011 | [
"Apache-2.0",
"MIT"
] | 71 | 2019-02-18T13:26:46.000Z | 2020-03-28T14:37:15.000Z | dbcrossbarlib/src/drivers/gs/local_data.rs | faradayio/schemaconv | eeb808354af7d58f1782927eaa9e754d59544011 | [
"Apache-2.0",
"MIT"
] | 1 | 2019-04-22T12:59:06.000Z | 2019-04-22T12:59:06.000Z | //! Reading data from Google Cloud Storage.
use super::GsLocator;
use crate::clouds::gcloud::storage;
use crate::common::*;
use crate::csv_stream::csv_stream_name;
/// Implementation of `local_data`, but as a real `async` function.
#[instrument(
level = "trace",
name = "gs::local_data",
skip_all,
fields(url = %url)
)]
pub(crate) async fn local_data_helper(
ctx: Context,
url: Url,
shared_args: SharedArguments<Unverified>,
source_args: SourceArguments<Unverified>,
) -> Result<Option<BoxStream<CsvStream>>> {
let _shared_args = shared_args.verify(GsLocator::features())?;
let _source_args = source_args.verify(GsLocator::features())?;
debug!("getting CSV files from {}", url);
let file_urls = storage::ls(&ctx, &url).await?;
let csv_streams = file_urls.and_then(move |item| {
let url = url.clone();
async move {
// Stream the file from the cloud.
let file_url = item.to_url_string();
let name = csv_stream_name(url.as_str(), &file_url)?;
let data = storage::download_file(&item)
.instrument(trace_span!("stream_from_gs", stream = %name))
.await?;
// Assemble everything into a CSV stream.
Ok(CsvStream {
name: name.to_owned(),
data,
})
}
.boxed()
});
Ok(Some(csv_streams.boxed()))
}
| 29.8125 | 74 | 0.600978 |
9ba77eec2bd47e7ee92f6cd82f3d92f4db84d154 | 2,346 | js | JavaScript | comparisons/react/todo.js | HorizonShadow/todo-compare | fee49393da1746d992038de34624c8539f54aa89 | [
"MIT"
] | 5 | 2019-03-28T18:57:13.000Z | 2019-08-02T18:28:11.000Z | comparisons/react/todo.js | HorizonShadow/todo-compare | fee49393da1746d992038de34624c8539f54aa89 | [
"MIT"
] | null | null | null | comparisons/react/todo.js | HorizonShadow/todo-compare | fee49393da1746d992038de34624c8539f54aa89 | [
"MIT"
] | 3 | 2019-03-30T19:48:10.000Z | 2019-04-09T08:54:16.000Z | import React, {Component} from 'react';
import './ToDo.css';
import ToDoItem from './components/ToDoItem';
import Logo from './assets/logo.png';
class ToDo extends Component {
constructor(props) {
super(props);
this.state = {
// this is where the data goes
list: [
{
'todo': 'clean the house'
},
{
'todo': 'buy milk'
}
],
todo: ''
};
};
createNewToDoItem = () => {
this.setState(({ list, todo }) => ({
list: [
...list,
{
todo
}
],
todo: ''
}));
};
handleKeyPress = e => {
if (e.target.value !== '') {
if (e.key === 'Enter') {
this.createNewToDoItem();
}
}
};
handleInput = e => {
this.setState({
todo: e.target.value
});
};
// this is now being emitted back to the parent from the child component
deleteItem = indexToDelete => {
this.setState(({ list }) => ({
list: list.filter((toDo, index) => index !== indexToDelete)
}));
};
render() {
return (
<div className="ToDo">
<img className="Logo" src={Logo} alt="React logo"/>
<h1 className="ToDo-Header">React To Do</h1>
<div className="ToDo-Container">
<div className="ToDo-Content">
{this.state.list.map((item, key) => {
return <ToDoItem
key={key}
item={item.todo}
deleteItem={this.deleteItem.bind(this, key)}
/>
}
)}
</div>
<div>
<input type="text" value={this.state.todo} onChange={this.handleInput} onKeyPress={this.handleKeyPress}/>
<button className="ToDo-Add" onClick={this.createNewToDoItem}>+</button>
</div>
</div>
</div>
);
}
}
export default ToDo;
| 26.066667 | 128 | 0.390878 |
590a9c53537fac2d169eac044a15dfbb0670a0f2 | 4,284 | swift | Swift | IMSDK/IMSDK/Classes/View/Expand/ToolView/BottomSelectView/FZMBottomSelectView.swift | 33cn/chat33-ios | 4537fb62e3515801047b4df708f31e40c3d9ed74 | [
"BSD-3-Clause"
] | null | null | null | IMSDK/IMSDK/Classes/View/Expand/ToolView/BottomSelectView/FZMBottomSelectView.swift | 33cn/chat33-ios | 4537fb62e3515801047b4df708f31e40c3d9ed74 | [
"BSD-3-Clause"
] | null | null | null | IMSDK/IMSDK/Classes/View/Expand/ToolView/BottomSelectView/FZMBottomSelectView.swift | 33cn/chat33-ios | 4537fb62e3515801047b4df708f31e40c3d9ed74 | [
"BSD-3-Clause"
] | 3 | 2020-07-22T11:53:21.000Z | 2021-05-29T13:38:55.000Z | //
// FZMBottomSelectView.swift
// IM_SocketIO_Demo
//
// Created by 吴文拼 on 2018/9/12.
// Copyright © 2018年 Wang. All rights reserved.
//
import UIKit
import RxSwift
class FZMBottomSelectView: UIView {
let disposeBag = DisposeBag()
private let cancelBtn : UIButton = {
let btn = UIButton(type: .custom)
btn.backgroundColor = FZM_BackgroundColor
btn.layer.cornerRadius = 20
btn.clipsToBounds = true
btn.setAttributedTitle(NSAttributedString(string: "取消", attributes: [.foregroundColor:FZM_BlackWordColor,.font:UIFont.regularFont(16)]), for: .normal)
return btn
}()
init(with titleArr:[FZMBottomOption]) {
super.init(frame: ScreenBounds)
self.backgroundColor = UIColor(white: 0, alpha: 0.5)
let tap = UITapGestureRecognizer()
tap.rx.event.subscribe(onNext:{[weak self] (_) in
self?.hide()
}).disposed(by: disposeBag)
self.addGestureRecognizer(tap)
cancelBtn.rx.controlEvent(.touchUpInside).subscribe(onNext:{[weak self] (_) in
self?.hide()
}).disposed(by: disposeBag)
self.addSubview(cancelBtn)
cancelBtn.snp.makeConstraints { (m) in
m.left.equalToSuperview().offset(30)
m.right.equalToSuperview().offset(-30)
m.bottom.equalToSuperview().offset(300)
m.height.equalTo(40)
}
var lastBtn = cancelBtn
titleArr.forEach { (option) in
let btn = UIButton(type: .custom)
btn.backgroundColor = FZM_BackgroundColor
btn.layer.cornerRadius = 20
btn.clipsToBounds = true
var height = 40
let attStr = NSMutableAttributedString(string: option.title, attributes: [.foregroundColor:option.textColor,.font:UIFont.regularFont(16)])
if let content = option.content, content.count > 0 {
height = 60
btn.titleLabel?.numberOfLines = 0
btn.titleLabel?.textAlignment = .center
attStr.append(NSAttributedString(string: "\n"))
attStr.append(NSAttributedString(string: content, attributes: [.foregroundColor:option.contentColor,.font:UIFont.regularFont(14)]))
}
btn.setAttributedTitle(attStr, for: .normal)
btn.rx.controlEvent(.touchUpInside).subscribe(onNext:{[weak self] (_) in
option.clickBlock?()
self?.hide()
}).disposed(by: disposeBag)
self.addSubview(btn)
btn.snp.makeConstraints { (m) in
m.left.equalToSuperview().offset(30)
m.right.equalToSuperview().offset(-30)
m.bottom.equalTo(lastBtn.snp.top).offset(-10)
m.height.equalTo(height)
}
lastBtn = btn
}
}
func show(){
UIApplication.shared.keyWindow?.addSubview(self)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.updateConstraints(with: 0.3) {
self.cancelBtn.snp.updateConstraints({ (m) in
m.bottom.equalToSuperview().offset(-30)
})
}
}
}
func hide(){
self.updateConstraints(with: 0.3, updateBlock: {
self.cancelBtn.snp.updateConstraints({ (m) in
m.bottom.equalToSuperview().offset(300)
})
}) {
self.removeFromSuperview()
}
}
class func show(with arr:[FZMBottomOption]){
let view = FZMBottomSelectView(with: arr)
view.show()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class FZMBottomOption: NSObject {
var title = ""
var content : String?
var textColor : UIColor
var contentColor : UIColor
var clickBlock : (()->())?
init(title : String , titleColor : UIColor = FZM_BlackWordColor, content: String? = nil, contentColor: UIColor = FZM_GrayWordColor, block:(()->())?) {
self.title = title
self.content = content
self.textColor = titleColor
self.contentColor = contentColor
self.clickBlock = block
super.init()
}
}
| 34.829268 | 158 | 0.586835 |
7289f0cf2fb0caff6c254d340596a7027c6cba75 | 48 | sql | SQL | ViewEnterpriseEditionFeatures.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null | ViewEnterpriseEditionFeatures.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null | ViewEnterpriseEditionFeatures.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null | SELECT *
FROM sys.dm_db_persisted_sku_features | 24 | 37 | 0.854167 |
2a8cb2144dc4a6de6ad9f7649f710303842a1fdb | 3,079 | java | Java | test/cz/vutbr/stud/fit/xsimon13/whoowns/java/typeresolver/ScopeUtilsTest.java | Strix-CZ/whoowns_simple | fac771ba1c76086e60f2727b91a6ade70715f245 | [
"Apache-2.0"
] | 1 | 2017-03-26T16:48:10.000Z | 2017-03-26T16:48:10.000Z | test/cz/vutbr/stud/fit/xsimon13/whoowns/java/typeresolver/ScopeUtilsTest.java | Strix-CZ/whoowns_simple | fac771ba1c76086e60f2727b91a6ade70715f245 | [
"Apache-2.0"
] | null | null | null | test/cz/vutbr/stud/fit/xsimon13/whoowns/java/typeresolver/ScopeUtilsTest.java | Strix-CZ/whoowns_simple | fac771ba1c76086e60f2727b91a6ade70715f245 | [
"Apache-2.0"
] | null | null | null | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package cz.vutbr.stud.fit.xsimon13.whoowns.java.typeresolver;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.InitializerDeclaration;
import com.github.javaparser.ast.stmt.BlockStmt;
import cz.vutbr.stud.fit.xsimon13.whoowns.Factory;
import cz.vutbr.stud.fit.xsimon13.whoowns.TestUtils;
import cz.vutbr.stud.fit.xsimon13.whoowns.java.ParsedClassProvider;
import org.junit.Assert;
import org.junit.Test;
public class ScopeUtilsTest {
@Test
public void testWithoutBlocks() throws Exception {
ScopePath s = new ScopePath("a.b.[0].c.[1].[2]");
Assert.assertEquals(s.withoutTrailingBlocks(), new ScopePath("a.b.[0].c"));
}
@Test
public void scopeInsideNodeTest() throws Exception {
ParsedClassProvider classProvider = Factory.createParsedClassProvider(TestUtils.getTestProjectRoot());
CompilationUnit cu = classProvider.get(new ScopePath("scopeutils.SUTest")).getAst();
// Class declaration in VariableDeclarator
ScopePath methodScope = new ScopePath("SUTest.method.[0]");
Node method = ScopeUtils.locateNode(cu, methodScope);
BlockStmt block = (BlockStmt)method.getChildrenNodes().get(0).getChildrenNodes().get(0).getChildrenNodes().get(1).getChildrenNodes().get(1).getChildrenNodes().get(1).getChildrenNodes().get(0);
Assert.assertEquals(ScopeUtils.getScopeInsideNode(methodScope, block), ScopePath.append(methodScope, "[0]"));
// Constructor
ScopePath constructorScope = new ScopePath("SUTest.SUTest");
Node constructor = ScopeUtils.locateNode(cu, constructorScope);
Assert.assertEquals(ScopeUtils.getScopeInsideNode(constructorScope, constructor.getChildrenNodes().get(0)), ScopePath.append(constructorScope, "[0]"));
// Enum + Initializer inside
ScopePath initializerScope = new ScopePath("SUTest.testEnum.initializer");
Node initializer = ScopeUtils.locateNode(cu, initializerScope);
Assert.assertTrue(initializer instanceof InitializerDeclaration);
Assert.assertEquals(ScopeUtils.getScopeInsideNode(initializerScope, initializer.getChildrenNodes().get(0)), ScopePath.append(initializerScope, "[0]"));
}
}
| 49.66129 | 200 | 0.744398 |
5fe2cd6ceff935ff0b9697c94c62ef9430c17626 | 952 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PLDImageHandler.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PLDImageHandler.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PLDImageHandler.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
#import "PLDImageProtocol-Protocol.h"
@class NSString;
@interface PLDImageHandler : NSObject <PLDImageProtocol>
{
}
- (_Bool)isDataUrl:(id)arg1;
- (_Bool)isMultiMediaTaskId:(id)arg1;
- (void)cancel:(id)arg1;
- (id)sendRequestForLocalImageUrl:(id)arg1 ckAppId:(id)arg2 ckViewId:(id)arg3 size:(struct CGSize)arg4 completionHandler:(CDUnknownBlockType)arg5;
- (id)fetchRemoteImage:(id)arg1 option:(id)arg2 callback:(CDUnknownBlockType)arg3;
- (id)getImageFromSrc:(id)arg1 appId:(id)arg2 callback:(CDUnknownBlockType)arg3;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 29.75 | 146 | 0.755252 |
477cda84d4fca0ead18c49a4abbe5a6429e0b2fe | 2,285 | htm | HTML | partials/shop-checkout-pay.htm | lambospeed/lscloud-theme-meyer | 4a5b0829f558cf96d7a880250d99133d642d63d0 | [
"MIT"
] | 2 | 2017-09-24T07:55:19.000Z | 2019-06-05T01:48:29.000Z | partials/shop-checkout-pay.htm | lambospeed/lscloud-theme-meyer | 4a5b0829f558cf96d7a880250d99133d642d63d0 | [
"MIT"
] | 73 | 2017-05-25T04:59:18.000Z | 2018-05-23T21:08:20.000Z | partials/shop-checkout-pay.htm | lambospeed/lscloud-theme-meyer | 4a5b0829f558cf96d7a880250d99133d642d63d0 | [
"MIT"
] | 4 | 2017-06-23T01:11:32.000Z | 2017-11-02T03:31:15.000Z | ---
description: '3 page checkout paystep.'
---
<div layout="column" id="checkout-paymentMethod">
<div layout="column">
{{ open_form({'class': 'custom'}) }}
{{ partial('shop-checkout-edit-discount') }}
{{ close_form() }}
{% if paymentMethods | length == 1 %}
<span class="input-hidden" ng-init="autoUpdateSinglePaymentMethod();"></span>
{% endif %}
<!-- Pay with stored cards shown in dropdown -->
{% if cards is defined %}
<h3 class="ls-heading letter-spacing-2 padding-y-medium">Pay with a Saved Card</h3>
<div class="row">
<form class="custom saved-card-form" method="post" data-ajax-handler="shop:onPay">
<label class="ls-subheading font-16">Credit Card</label>
<input type='hidden' name='payment_method_id' id='payment_method_id' value=''>
<select name="payment_method_token" class="md-select saved-card-selector" id="saved_card_option" style="margin-bottom: 15px;">
<option disabled selected value=''>Select Saved Card</option>
{% for card in cards %}
<option id="token-{{ card.token }}" value="{{ card.token }}" card-method="{{ card.paymentMethod.id }}">{{ card.paymentMethod.name }}: {{ card.cardAndBrand }}</option>
{% endfor %}
</select>
<br>
<input type="submit" class="ls-button no-margin-x ls-button-wide md-button md-ink-ripple flex-order-xs-1" value="Pay with Saved Card">
</form>
</div>
{% endif %}
{{ open_form({'class': 'custom'}) }}
<!-- Payment Method(s) -->
<h3 class="ls-heading letter-spacing-2 padding-y-medium">Payment method</h3>
<div layout="row">
<md-input-container class="md-input-has-placeholder hide-errors">
<label class="ls-subheading font-16">Payment method</label>
<select name="paymentMethodId" id="payment_method">
<option disabled selected value=''> - Select a payment method - </option>
{% for method in paymentMethods %}
<option value="{{ method.id }}">{{ method.name }}</option>
{% endfor %}
</select>
</md-input-container>
</div>
{{ close_form() }}
<div id="payment_form">
{{ partial('partial-paymentform') }}
</div>
</div>
</div> | 45.7 | 178 | 0.597812 |
175a0cfe56b266a93d95c51c88f998c3bbf71e12 | 6,439 | xhtml | HTML | data/tika-parsed/separated/296.xhtml | Anthonyive/DSCI-550-Assignment-2 | 65bba4cb22ab90dbc469d40c66f4495022924eb2 | [
"MIT"
] | 1 | 2021-06-24T19:53:01.000Z | 2021-06-24T19:53:01.000Z | data/tika-parsed/separated/296.xhtml | Anthonyive/DSCI-550-Assignment-2 | 65bba4cb22ab90dbc469d40c66f4495022924eb2 | [
"MIT"
] | null | null | null | data/tika-parsed/separated/296.xhtml | Anthonyive/DSCI-550-Assignment-2 | 65bba4cb22ab90dbc469d40c66f4495022924eb2 | [
"MIT"
] | 1 | 2021-04-09T17:30:13.000Z | 2021-04-09T17:30:13.000Z | <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="subject" content="Proposal" />
<meta name="dc:creator" content=""Mr.Bom Uche" <mrbom@fastermail.com>" />
<meta name="dc:creator" content="Mr.Bom Uche <mrbom@fastermail.com>" />
<meta name="MboxParser-status" content="O" />
<meta name="Message:From-Email" content="mrbom@fastermail.com" />
<meta name="dcterms:created" content="2003-06-29T08:35:04Z" />
<meta name="Message-To" content="R@S" />
<meta name="Message-To" content="R@S" />
<meta name="dc:format" content="text/plain; charset="us-ascii"" />
<meta name="Message-Recipient-Address" content="R@S" />
<meta name="Message:Raw-Header:Status" content="O" />
<meta name="MboxParser-reply-to" content="mrbom@fastermail.com" />
<meta name="Message:Raw-Header:MIME-Version" content="1.0" />
<meta name="Message:Raw-Header:Reply-To" content="mrbom@fastermail.com" />
<meta name="dc:title" content="Proposal" />
<meta name="Content-Type-Override" content="message/rfc822" />
<meta name="Content-Type" content="message/rfc822" />
<meta name="MboxParser-content-transfer-encoding" content="quoted-printable" />
<meta name="identifier" content="<200306290648.h5T6moe10003@foxfire.mr.itd.UM>" />
<meta name="creator" content=""Mr.Bom Uche" <mrbom@fastermail.com>" />
<meta name="creator" content="Mr.Bom Uche <mrbom@fastermail.com>" />
<meta name="X-Parsed-By" content="org.apache.tika.parser.DefaultParser" />
<meta name="X-Parsed-By" content="org.apache.tika.parser.mail.RFC822Parser" />
<meta name="Message:Raw-Header:Content-Type" content="text/plain; charset="us-ascii"" />
<meta name="meta:author" content=""Mr.Bom Uche" <mrbom@fastermail.com>" />
<meta name="meta:author" content="Mr.Bom Uche <mrbom@fastermail.com>" />
<meta name="meta:creation-date" content="2003-06-29T08:35:04Z" />
<meta name="format" content="text/plain; charset="us-ascii"" />
<meta name="Creation-Date" content="2003-06-29T08:35:04Z" />
<meta name="Message:Raw-Header:Content-Transfer-Encoding" content="quoted-printable" />
<meta name="Message:Raw-Header:Return-Path" content="<mrbom@fastermail.com>" />
<meta name="MboxParser-x-mailer" content="Microsoft Outlook Express 5.00.2919.6900 DM" />
<meta name="MboxParser-from" content="r Sun Jun 29 02:49:01 2003" />
<meta name="MboxParser-return-path" content="<mrbom@fastermail.com>" />
<meta name="Message:Raw-Header:Message-Id" content="<200306290648.h5T6moe10003@foxfire.mr.itd.UM>" />
<meta name="MboxParser-mime-version" content="1.0" />
<meta name="Message:From-Name" content="Mr.Bom Uche" />
<meta name="X-TIKA:embedded_depth" content="1" />
<meta name="Author" content=""Mr.Bom Uche" <mrbom@fastermail.com>" />
<meta name="Author" content="Mr.Bom Uche <mrbom@fastermail.com>" />
<meta name="Message:Raw-Header:X-Mailer" content="Microsoft Outlook Express 5.00.2919.6900 DM" />
<meta name="X-TIKA:embedded_resource_path" content="/embedded-293" />
<meta name="Message-From" content="Mr.Bom Uche <mrbom@fastermail.com>" />
<meta name="dc:identifier" content="<200306290648.h5T6moe10003@foxfire.mr.itd.UM>" />
<title>Proposal</title>
</head>
<body><p>DEAR SIR,
FIRST,I MUST SOLICIT YOUR CONFIDENCE IN THIS
TRANSACTION;THIS IS BY VIRTUE OF ITS NATURE AS BEING
UTTERLY CONFIDENTIAL AND TOP SECRET.THOUGH I KNOW THAT
A TRANSACTION OF THIS MAGNITUDE WILL MAKE ANY ONE
APPREHENSIVE AND WORRIED,BUT I AM ASSURING YOU THAT
ALL WILL BE WELL AT THE END OF THE DAY.
WE HAVE DECIDED TO CONTACT YOU DUE TO THE URGENCY OF
THIS TRANSACTION,AS WE HAVE BEEN RELIABLY INFORMED OF
YOUR DISCRETNESS AND ABILITY IN TRANSACTION OF THIS
NATURE.
LET ME START BY INTRODUCING MYSELF PROPERLY TO YOU.I
AM MR.BOM UCHE,CREDIT OFFICER WITH THE UNION BANK
OF NIGERIA PLC,LAGOS. I CAME TO KNOW YOU IN MY PRIVATE
SEARCH FOR A RELIABLE AND REPUTABLE PERSON TO HANDLE
THIS CONFIDENTIAL TRANSACTION,WHICH INVOLVES THE
TRANSFER OF HUGE SUM OF MONEY TO A FOREIGN ACCOUNT
REQUIRING MAXIMUM CONFIDENCE.
THE PROPOSITION:
A FOREIGNER AN AMERICAN,LATE ENGR JOHN CREEK (SNR) AN
OIL MERCHANT WITH THE FEDERAL GOVERNMENT OF
NIGERIA,UNTIL HIS DEATH IN KENYA AIR BUS (A310-300)
FLIGHT KQ430,BANKED WIH US AT UNION BANK OF NIGERIA
PLC LAGOS AND HAD A CLOSING BALANCE AS AT THE END OF
JANUARY,2000 WORTH USD20, 000,000.00(TWENTY MILLION
UNITED STATE DOLLAR),THE BANK NOW EXPECTS A NEXT OF
KIN AS BENEFICIARY.VALUABLE EFFORTS ARE BEING MADE BY
THE UNION BANK OF NIGERIA TO GET IN TOUCH WITH ANY OF
THE CREEK'S FAMILY OR RELATIVES BUT TO NO SUCCESS.
IT IS BECAUSE OF THE PERCEIVED POSSIBILITY OF NOT
BEING ABLE TO LOCATE ANY OF LATE ENGR.JOHN
CREEK(SNR)'S NEXT OF KIN(HE HAD NO WIFE OR CHILDREN
THAT IS KNOWN TO US).THE MANAGEMENT UNDER THE
INFLUENCE OF OUR CHAIRMAN AND MEMBERS OF THE BOARD OF
DIRECTORS,THAT ARANGE HAS BEEN MADE FOR THE FUND TO BE
DECLEARED "UNCLAINMED" AND SUBSEQUENTLY BE DONATED TO
THE TRUST FUND FOR ARMS AND AMMUNITION TO FURTHER
ENHANCE THE COURSE OF WAR IN AFRICA AND THE WORLD IN
GENERAL.
IN ORDER TO AVERT THIS NEGATIVE DEVELOPMENT, SOME OF
MY TRUSTED COLLEAGUES AND I NOW SEEK YOUR PERMISSION
TO HAVE YOU STAND AS NEXT OF KIN TO LATE ENGR. JOHN
CREEK(SNR) SO THAT THE FUND USD20MILLION WILL BE
RELEASED AND PAID INTO YOUR ACCOUNT AS THE
BENEFICIARY'S NEXT OF KIN. ALL DOCUMENTS AND PROVES TO
ENABLE YOU GET THIS FUND WILL BE CAREFULLY WORKED OUT.
WE HAVE SECURE FROM THE PROBATE AN ORDER OF MADAMUS TO
LOCATE ANY OF DECEASED BENEFICIARIES,AND MORE SO WE
ARE ASSURING YOU THAT THIS BUSINESS IS 100% RISK FREE
INVOLVEMENT.YOUR SHARE STAYS WHILE THE REST BE FOR
MYSELF AND MY COLLEAGUES FOR INVESTMENT PURPOSE.
ACCORDING TO AGGREMENT WITHIN BOTH PARTIES AS SOON AS
WE RECIEVE AN ACKNOWLEDGEMENT OF RECEIPT OF THIS
MESSAGE IN ACCEPTANCE OF OUR MUTUAL BUSINESS PROPOSAL,
WE WOULD FURNISH YOU WITH THE NECCESSARY MODALITIES
AND DISBURSEMENT RATIO TO SUITE BOTH PARTIES WITHOUT
ANY CONFLICT.
IF THIS PROPOSAL IS ACCEPTABLE BY YOU DO NOT MAKE
UNDUE ADVANTAGE OF THE TRUST WE HAVE BESTOWED IN YOU
AND YOUR COMPANY,THEN KINDLY GET TO ME IMMEDIATELY VIA
MAIL ABOVE OR FAX:234-1-7599853.
PLEASE FURNISH ME WITH YOUR MOST CONFIDENTIAL
TELEPHONE,FAX NUMBERS SO THAT I CAN USE THIS
INFORMATION TO APPLY FOR THE RELEASE AND SUBSEQUENT
TRANSFER OF THE FUND IN YOUR FAVOUR.
THANK YOU IN ADVANCE FOR YOUR ANTICIPATED CORPORATION.
YOURS FAITHFULLY,
MR.BOM UCHE.
</p>
</body></html> | 52.778689 | 107 | 0.763628 |
6d19e0a7333ac54ac823e389b9ba4855f7d566f4 | 1,889 | kt | Kotlin | app/src/main/java/info/codive/sample/viewpager2/MainActivity.kt | Codive/ViewPager2Sample | 5a06cc05bf5e0e9ce87756059ea2d6a7a922da29 | [
"MIT"
] | null | null | null | app/src/main/java/info/codive/sample/viewpager2/MainActivity.kt | Codive/ViewPager2Sample | 5a06cc05bf5e0e9ce87756059ea2d6a7a922da29 | [
"MIT"
] | null | null | null | app/src/main/java/info/codive/sample/viewpager2/MainActivity.kt | Codive/ViewPager2Sample | 5a06cc05bf5e0e9ce87756059ea2d6a7a922da29 | [
"MIT"
] | 1 | 2021-06-26T02:24:21.000Z | 2021-06-26T02:24:21.000Z | package info.codive.sample.viewpager2
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
private const val PAGE_MAX: Int = 5
class MainActivity : AppCompatActivity() {
private lateinit var viewPager: ViewPager2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//テストデータ作成
val listItem = createTestData()
viewPager = findViewById(R.id.sample_view_pager2)
val pagerAdapter2 = MainPagerAdapter2(
listItem,
onBackButtonClicked,
onNextButtonClicked,
onEndButtonClicked
)
viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
viewPager.adapter = pagerAdapter2
// viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
// override fun onPageScrolled(
// position: Int,
// positionOffset: Float,
// positionOffsetPixels: Int
// ) {}
// })
}
//BACKボタンのイベント処理
private val onBackButtonClicked = {
viewPager.setCurrentItem(viewPager.currentItem - 1, true) //Pageを移動
}
//NEXTボタンのイベント処理
private val onNextButtonClicked = {
viewPager.setCurrentItem(viewPager.currentItem + 1, true) //Pageを移動
}
//FragmentのENDボタンのイベント処理
private val onEndButtonClicked = {
Toast.makeText(this, "Last Fragment", Toast.LENGTH_SHORT).show()
}
// テストデータ作成
private fun createTestData(): MutableList<SampleData> {
val listItem = mutableListOf<SampleData>()
for (i in 1..PAGE_MAX) {
listItem.add(SampleData("Title $i"))
}
return listItem
}
} | 29.515625 | 93 | 0.660667 |
c46a9d0ead75ece838e49aaa97c3591a9313f8f8 | 2,621 | h | C | code/dtslam_ui/shaders/TextRenderer.h | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 144 | 2015-01-15T03:38:44.000Z | 2022-02-17T09:07:52.000Z | code/dtslam_ui/shaders/TextRenderer.h | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 9 | 2015-09-09T06:51:46.000Z | 2020-06-17T14:10:10.000Z | code/dtslam_ui/shaders/TextRenderer.h | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 58 | 2015-01-14T23:43:49.000Z | 2021-11-15T05:19:08.000Z | /*
* TextRenderer.h
*
* Copyright(C) 2014, University of Oulu, all rights reserved.
* Copyright(C) 2014, NVIDIA Corporation, all rights reserved.
* Third party copyrights are property of their respective owners.
* Contact: Daniel Herrera C. (dherrera@ee.oulu.fi),
* Kihwan Kim(kihwank@nvidia.com)
* Author : Daniel Herrera C.
*/
#ifndef TEXTRENDERER_H_
#define TEXTRENDERER_H_
#include <opencv2/core/core.hpp>
#include <sstream>
#include <memory>
#include "../TextureHelper.h"
#include "TextShader.h"
namespace dtslam
{
class TextRenderer;
class TextRendererStream
{
public:
TextRendererStream(TextRenderer &renderer): mRenderer(renderer)
{
}
~TextRendererStream();
void flush();
void setColor(const cv::Vec4f &color);
template<class T>
TextRendererStream &operator <<(const T &value);
protected:
TextRenderer &mRenderer;
std::stringstream mStream;
};
class TextRenderer
{
public:
TextRenderer();
~TextRenderer();
/**
* @brief Builds the texture used for text rendering.
*/
bool init(TextShader *shader);
void setActiveFontSmall() {mActiveFont = &mFontData[0];}
void setActiveFontBig() {mActiveFont = &mFontData[1];}
void setMVPMatrix(const cv::Matx44f &mvp) {mShader->setMVPMatrix(mvp);}
void setRenderCharHeight(float height) {mRenderCharHeight = height;}
void setCaret(const cv::Vec4f &caret) {mRenderCaret = mRenderCaret0 = caret;}
void setCaret(const cv::Point2f &caret) {setCaret(cv::Vec4f(caret.x, caret.y, 1, 1));}
void setColor(const cv::Vec4f &color) {mActiveColor = color;}
void renderText(const std::string &str)
{
std::stringstream ss(str);
renderText(ss);
}
void renderText(std::stringstream &str);
protected:
class TextFontData
{
public:
static const int kCharCount = 255;
TextureHelper mTexture;
float mCharAspect[kCharCount];
float mCharTexStart[kCharCount+1];
float mCharTexEnd[kCharCount+1];
};
TextShader *mShader;
std::vector<TextFontData> mFontData;
TextFontData *mActiveFont;
cv::Vec4f mActiveColor;
float mRenderCharHeight;
cv::Vec4f mRenderCaret0;
cv::Vec4f mRenderCaret;
void prepareFontData(TextFontData &data, int face, double scale, int thickness, int lineType);
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implementation
template<class T>
TextRendererStream &TextRendererStream::operator <<(const T &value)
{
mStream << value;
return *this;
}
}
#endif /* TEXTRENDERER_H_ */
| 23.401786 | 112 | 0.661198 |
cb2dfe26e742f02d6a2f0ca74e457bf3192e45a0 | 1,363 | h | C | Client/src/lua_util.h | ruuuubi/corsairs-client | ddbcd293d6ef3f58ff02290c02382cbb7e0939a2 | [
"Apache-2.0"
] | 1 | 2021-06-14T09:34:08.000Z | 2021-06-14T09:34:08.000Z | Client/src/lua_util.h | ruuuubi/corsairs-client | ddbcd293d6ef3f58ff02290c02382cbb7e0939a2 | [
"Apache-2.0"
] | null | null | null | Client/src/lua_util.h | ruuuubi/corsairs-client | ddbcd293d6ef3f58ff02290c02382cbb7e0939a2 | [
"Apache-2.0"
] | null | null | null | #include <strstream>
inline int lua_MsgBox(lua_State *L)
{
const char *pszContent = lua_tostring(L, 1);
MessageBox(NULL, pszContent, "msg", 0);
return 0;
}
inline int lua_GetTickCount(lua_State *L)
{
lua_pushnumber(L, GetTickCount());
return 1;
}
inline int lua_Rand(lua_State *L)
{
BOOL bValid = (lua_gettop(L)==1 && lua_isnumber(L, 1));
if(!bValid)
{
PARAM_ERROR;
}
int nRange = (int)lua_tonumber(L, 1);
int nRand = rand()%nRange;
lua_pushnumber(L, nRand);
return 1;
}
inline int lua_LG(lua_State *L)
{
int count = lua_gettop(L);
if( count<=1 )
{
PARAM_ERROR;
}
const char *pszFile = lua_tostring(L, 1);
char szBuf[2048] = { 0 };
std::ostrstream str( szBuf, sizeof(szBuf) );
str << lua_tostring(L, 2);
for( int i=3; i<=count; i++ )
{
str << ", " << lua_tostring(L, i);
}
str << ends;
LG( (char*)pszFile, str.str() );
return 0;
}
inline int lua_SysInfo(lua_State *L)
{
int count = lua_gettop(L);
if( count<=0 )
{
PARAM_ERROR;
}
char szBuf[2048] = { 0 };
std::ostrstream str( szBuf, sizeof(szBuf) );
for( int i=1; i<=count; i++ )
{
str << " " << lua_tostring(L, i);
}
str << ends;
g_pGameApp->SysInfo( "luaSysInfo:%s", str.str() );
return 0;
}
//lua_dofile
| 19.197183 | 59 | 0.557594 |
2190f7c969607b681926952e3a8f718a5891efe4 | 701 | rs | Rust | examples/city.rs | pontuslaestadius/pathfinder | a62adb58c90474fffb6ae33e7fe93d3a858f72a5 | [
"MIT"
] | 4 | 2020-08-10T11:16:36.000Z | 2021-02-27T15:23:48.000Z | examples/city.rs | pontuslaestadius/pathfinder | a62adb58c90474fffb6ae33e7fe93d3a858f72a5 | [
"MIT"
] | 26 | 2018-08-07T15:52:41.000Z | 2020-03-10T10:19:06.000Z | examples/city.rs | pontuslae/pathfinder | a62adb58c90474fffb6ae33e7fe93d3a858f72a5 | [
"MIT"
] | null | null | null | extern crate pathtracer;
use pathtracer::*;
use std::path::Path;
fn main() -> Result<(), std::io::Error> {
let mut pos = Vec::new();
let city_size = 30;
let spread = 15;
for y in 0..city_size / 2 {
for x in 0..city_size * 2 {
let mut node = node!(spread * x, spread * y);
node.color = tools::seed_rgba((city_size * x + spread * y) as u64);
pos.push(node);
}
}
pos = Node::linked_list_predicate(pos, &|a, b| {
let abs = (a - b).abs();
let d = abs.x + abs.y;
d < spread * 3
});
Map::new()
.map_filter(&pos, &|node: &Node| node.hl(0).is_ok())
.save(&Path::new("out.png"))
}
| 23.366667 | 79 | 0.496434 |
9527ece00547ca63aa303c05bc1c4ff8bdeded7a | 1,576 | css | CSS | haxe/ui/_module/styles/dark/tableview.css | radiatoryang/haxeui-core | 761205141f58a837ef6af9ef212613f91bb21d00 | [
"MIT"
] | null | null | null | haxe/ui/_module/styles/dark/tableview.css | radiatoryang/haxeui-core | 761205141f58a837ef6af9ef212613f91bb21d00 | [
"MIT"
] | null | null | null | haxe/ui/_module/styles/dark/tableview.css | radiatoryang/haxeui-core | 761205141f58a837ef6af9ef212613f91bb21d00 | [
"MIT"
] | null | null | null | /************************************************************************
** HEADER
*************************************************************************/
.column.sortable {
icon: "haxeui-core/styles/default/sortable_arrows.png";
icon-position: far-right;
}
.column.sort-asc {
icon: "haxeui-core/styles/default/sortable_asc.png";
}
.column.sort-desc {
icon: "haxeui-core/styles/default/sortable_desc.png";
}
/************************************************************************
** TABLEVIEW
*************************************************************************/
.tableview {
border: 1px solid #181a1b;
border-radius: 1px;
padding: 1px;
width: auto;
height: auto;
background-color: #252728;
spacing: 0;
}
.tableview .tableview-contents {
spacing: 0;
width: 100%;
padding: 0px;
}
.tableview .even {
background-color: #252728;
cursor: pointer;
}
.tableview .odd {
background-color: #2a2c2d;
cursor: pointer;
}
.tableview .compounditemrenderer .itemrenderer {
height: auto;
padding: 5px;
}
.tableview .even:hover {
background-color: #2f3746;
}
.tableview .odd:hover {
background-color: #2f3746;
}
.tableview .compounditemrenderer .label {
color: #d4d4d4;
}
.tableview .compounditemrenderer:selected {
background-color: #415982;
color: white;
}
.tableview .compounditemrenderer:selected .label {
color: white;
}
.tableview .compounditemrenderer:disabled {
color: #595959;
}
.tableview .compounditemrenderer:disabled .label {
color: #595959;
}
| 19.949367 | 74 | 0.543782 |
402330dd75deff5aebac3b8552e3fec70c1bdf41 | 991 | py | Python | jupyterStyle/StyleHelper.py | RobertOlechowski/Jupyter-Style | 1e5901d7e514920e855ff23c3f515b3712b677c7 | [
"MIT"
] | 2 | 2021-05-05T16:20:24.000Z | 2021-09-28T18:05:52.000Z | jupyterStyle/StyleHelper.py | RobertOlechowski/Jupyter-Style | 1e5901d7e514920e855ff23c3f515b3712b677c7 | [
"MIT"
] | null | null | null | jupyterStyle/StyleHelper.py | RobertOlechowski/Jupyter-Style | 1e5901d7e514920e855ff23c3f515b3712b677c7 | [
"MIT"
] | null | null | null | import sys
if sys.version_info < (3, 5):
raise Exception("Python 3.5 required")
class StyleHelper(object):
template_file_name = "style_template.css_template"
def __init__(self):
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
file_name = os.path.join(dir_path, self.template_file_name)
self.styles_template = open(file_name, "r").read()
def _generate_style_text(self, **kwargs):
from string import Template
template = Template(self.styles_template)
default_values = {
"selector": "",
"col_header_color": "antiquewhite",
"row_header_color": "cornsilk"
}
values = {**default_values, **kwargs}
return template.substitute(values)
def emit_style(self, **kwargs):
from IPython.display import HTML, display
style_text = "<style > {} </style>".format(self._generate_style_text(**kwargs))
display(HTML(style_text))
| 30.030303 | 87 | 0.638749 |
18e6ae330af1834f8aecf8d8a0f8b45fcab15068 | 134 | rb | Ruby | db/migrate/20200214173335_rename_type_to_comment_type.rb | stef-codes/booktap-backend | c0259162d1052b28958cddd559dab9529f4263c2 | [
"Unlicense"
] | 1 | 2020-02-14T23:44:57.000Z | 2020-02-14T23:44:57.000Z | db/migrate/20200214173335_rename_type_to_comment_type.rb | stef-codes/booktap-backend | c0259162d1052b28958cddd559dab9529f4263c2 | [
"Unlicense"
] | 6 | 2021-05-19T19:17:31.000Z | 2022-03-31T00:41:58.000Z | db/migrate/20200214173335_rename_type_to_comment_type.rb | stef-codes/booktap-backend | c0259162d1052b28958cddd559dab9529f4263c2 | [
"Unlicense"
] | null | null | null | class RenameTypeToCommentType < ActiveRecord::Migration[6.0]
def change
rename_column :comments, :type, :comment_type
end
end
| 22.333333 | 60 | 0.768657 |
a4d848ee3bc69e62be2fbe5ea408dbe46acf6edd | 3,298 | kt | Kotlin | src/main/kotlin/hu/adamsan/gitdb/dao/RepoDao.kt | adamsan/git-db | f280da5116103af22c23e9c920d3e64344b8c529 | [
"MIT"
] | null | null | null | src/main/kotlin/hu/adamsan/gitdb/dao/RepoDao.kt | adamsan/git-db | f280da5116103af22c23e9c920d3e64344b8c529 | [
"MIT"
] | null | null | null | src/main/kotlin/hu/adamsan/gitdb/dao/RepoDao.kt | adamsan/git-db | f280da5116103af22c23e9c920d3e64344b8c529 | [
"MIT"
] | null | null | null | package hu.adamsan.gitdb.dao
import org.jdbi.v3.core.Jdbi
import org.jdbi.v3.core.mapper.RowMapper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
data class Repo(
val id: Int,
val name: String,
val path: String,
var favorite: Boolean,
var commits: Int,
var lastCommitted: Date?,
var hasRemote: Boolean = false
)
class RepoDao(val jdbi: Jdbi) {
private val log: Logger = LoggerFactory.getLogger(this.javaClass)
private val mapper: RowMapper<Repo> = RowMapper { rs, _ ->
Repo(
rs.getInt("ID"),
rs.getString("NAME"),
rs.getString("PATH"),
rs.getBoolean("FAVORITE"),
rs.getInt("COMMITS"),
if (rs.getLong("LAST_COMMITTED") != 0L)
Date(rs.getLong("LAST_COMMITTED"))
else
null,
rs.getBoolean("HAS_REMOTE")
)
}
fun getUnusedIndex(): Int {
return 1 + jdbi.withHandle<Int, Exception> { h ->
h.select("SELECT MAX(ID) FROM REPO")
.mapTo(Int::class.java)
.one()
}
}
fun getAll(): List<Repo> {
return jdbi.withHandle<List<Repo>, Exception> { h ->
h.select("SELECT * FROM REPO")
.map(mapper)
.list()
}
}
fun findById(id: Int): Optional<Repo> {
val sql = "SELECT * FROM REPO WHERE id=:id"
return jdbi.withHandle<Optional<Repo>, Exception> { h ->
h.createQuery(sql)
.bind("id", id)
.map(mapper)
.findFirst()
}
}
fun insert(repo: Repo) {
log.info("insert $repo to db")
val sql = "INSERT INTO REPO VALUES (:id, :name, :path, :favorite, :commits, :lastCommitted, :hasRemote)"
jdbi.withHandle<Int, Exception> { h ->
h.createUpdate(sql)
.bindBean(repo)
.execute()
}
}
fun update(repo: Repo) {
val sql = "UPDATE REPO " +
"SET name=:name, path=:path, favorite=:favorite, commits=:commits, last_committed= :lastCommitted, has_remote=:hasRemote " +
"WHERE id= :id"
jdbi.withHandle<Int, Exception> { h ->
h.createUpdate(sql)
.bindBean(repo)
.execute()
}
}
fun delete(repoId: Int) {
var sql = "DELETE FROM REPO WHERE id=:id"
jdbi.withHandle<Int, Exception> { h ->
h.createUpdate(sql)
.bind("id", repoId)
.execute()
}
}
fun deleteAll() {
log.info("deleting all records from REPO table")
var sql = "DELETE FROM REPO"
jdbi.withHandle<Int, Exception> { h ->
h.createUpdate(sql)
.execute()
}
}
fun findByPath(path: String): Optional<Repo> {
val sql = "SELECT * FROM REPO WHERE path=:path"
return jdbi.withHandle<Optional<Repo>, Exception> { h ->
h.createQuery(sql)
.bind("path", path)
.map(mapper)
.findFirst()
}
}
}
| 29.711712 | 140 | 0.494239 |
dd4d945cddf27abf38fb20958a64f127b8c1fe06 | 698 | go | Go | exerise/struct-1.go | fossabot/how_to_go | a7ce2c4aaa8ee997b63f581c4e30055c80b68002 | [
"MIT"
] | null | null | null | exerise/struct-1.go | fossabot/how_to_go | a7ce2c4aaa8ee997b63f581c4e30055c80b68002 | [
"MIT"
] | null | null | null | exerise/struct-1.go | fossabot/how_to_go | a7ce2c4aaa8ee997b63f581c4e30055c80b68002 | [
"MIT"
] | null | null | null | package main
import (
"fmt"
"reflect"
)
type TZ int
type A struct {
Name string
}
type User struct {
Id int
Name string
Age int
}
type B struct {
Name string
}
func (a *A) Print() {
a.Name = "AA"
fmt.Println("A")
}
func (u User) Hello() {
fmt.Println("hello world")
}
func Info(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(("Type",t.Name()))
v : = reflect.ValueOf(o)
fmt.Println("Fields")
for i:=0;i<t.NumField();i++{
f :=t.Field(i)
val = v.Field(i).Interface()
fmt.Printf("%s :%v= %v", f.Na)
}
}
func (a *TZ) Print() {
fmt.Println("TZ")
}
func main() {
a := A{}
a.Print()
fmt.Println(a.Name)
var b TZ
b.Print()
}
| 11.830508 | 38 | 0.551576 |
3be03f032079499afce19c68f70f8d12ff1a4cf5 | 1,371 | c | C | src/uart.c | LukasJaeger307/easymsp | bc9b07f94ec34492468d22e2f4bec2e13c7cba2c | [
"WTFPL"
] | null | null | null | src/uart.c | LukasJaeger307/easymsp | bc9b07f94ec34492468d22e2f4bec2e13c7cba2c | [
"WTFPL"
] | null | null | null | src/uart.c | LukasJaeger307/easymsp | bc9b07f94ec34492468d22e2f4bec2e13c7cba2c | [
"WTFPL"
] | null | null | null | /*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*/
#include "easymsp/uart.h"
#if defined(EASYMSP_UART) || defined(EASYMSP_FULL)
#define RXD BIT1 //Check your launchpad rev to make sure this is the case. Set jumpers to hardware uart.
#define TXD BIT2 // TXD with respect to what your sending to the computer. Sent data will appear on this line
void uart_setup(){
//TODO: Add frequency
P1SEL = RXD + TXD ; // Select TX and RX functionality for P1.1 & P1.2
P1SEL2 = RXD + TXD ; //
UCA0CTL1 |= UCSSEL_2; // Have USCI use System Master Clock: AKA core clk 1MHz
UCA0BR0 = 104; // 1MHz 9600, see user manual
UCA0BR1 = 0; //
UCA0MCTL = UCBRS0; // Modulation UCBRSx = 1
UCA0CTL1 &= ~UCSWRST; // Start USCI state machine
}
void uart_tx(char c){
while (UCA0STAT & UCBUSY);
UCA0TXBUF = c;
}
void uart_tx_string(char const * const s){
size_t i = 0;
while(s[i] != 0x00) {
while (UCA0STAT & UCBUSY);
UCA0TXBUF = s[i];
i++;
}
}
#endif // EASYMSP_UART
| 31.159091 | 116 | 0.624362 |
053f6ba8e23ff731bb4a9fdf63c82459c2675a39 | 948 | kt | Kotlin | template-vertx-basic/src/main/kotlin/cc/chordflower/template/basic/application/config/MailConfiguration.kt | fossabot/template-3 | 54a32cb686105265079f1b8d68a75993edffce4b | [
"Apache-2.0"
] | null | null | null | template-vertx-basic/src/main/kotlin/cc/chordflower/template/basic/application/config/MailConfiguration.kt | fossabot/template-3 | 54a32cb686105265079f1b8d68a75993edffce4b | [
"Apache-2.0"
] | 38 | 2021-01-04T12:06:04.000Z | 2021-07-21T06:21:09.000Z | template-vertx-basic/src/main/kotlin/cc/chordflower/template/basic/application/config/MailConfiguration.kt | fossabot/template-3 | 54a32cb686105265079f1b8d68a75993edffce4b | [
"Apache-2.0"
] | 1 | 2021-02-20T05:40:19.000Z | 2021-02-20T05:40:19.000Z | package cc.chordflower.template.basic.application.config
import cc.chordflower.template.basic.application.config.base.BaseMailConfiguration
import cc.chordflower.template.basic.application.utils.ValidatedObject
import io.vertx.core.json.JsonObject
import java.math.BigInteger
import java.util.*
import javax.validation.Validator
class MailConfiguration : BaseMailConfiguration, ValidatedObject {
constructor() : super()
constructor( it : JsonObject? ) : super() {
Objects.requireNonNull(it)
if(it != null) {
this.address = it.getString("address", this.address)
this.from = it.getString("from", this.from)
this.password = it.getString("password", this.password)
this.secure = it.getBoolean("secure", this.secure)
this.port = BigInteger.valueOf(it.getLong("port", this.port.toLong()))
}
}
override fun valid(validator: Validator): Boolean {
return validator.validate(this).isNotEmpty()
}
}
| 33.857143 | 82 | 0.739451 |
8332184ac9f6b24a963315414794466567bafe4f | 2,447 | kt | Kotlin | app/src/main/java/com/yz/books/utils/ImageLoaderUtils.kt | zhangkari/yzlauncher | 90784936a9ec75e702120941fbfac6f1b40b93d5 | [
"Apache-2.0"
] | 1 | 2021-08-07T13:18:45.000Z | 2021-08-07T13:18:45.000Z | app/src/main/java/com/yz/books/utils/ImageLoaderUtils.kt | zhangkari/yzlauncher | 90784936a9ec75e702120941fbfac6f1b40b93d5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yz/books/utils/ImageLoaderUtils.kt | zhangkari/yzlauncher | 90784936a9ec75e702120941fbfac6f1b40b93d5 | [
"Apache-2.0"
] | 2 | 2020-10-12T13:26:59.000Z | 2020-11-25T20:43:14.000Z | package com.yz.books.utils
import android.graphics.Bitmap
import android.widget.ImageView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.yz.books.R
import com.yz.books.common.glide.GlideApp
/**
* @author lilin
* @time on 2019-12-29 16:05
*/
object ImageLoaderUtils {
fun withLogo(url: String,
imageView: ImageView) {
GlideApp.with(imageView.context)
.load(url)
//.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.placeholder(R.drawable.img_default_logo)
.error(R.drawable.img_default_logo)
.into(imageView)
}
fun withBookCover(url: String,
imageView: ImageView,
scaleType: ImageView.ScaleType? = null) {
imageView.scaleType = scaleType ?: ImageView.ScaleType.CENTER_CROP
GlideApp.with(imageView.context)
.asBitmap()
.load(url)
//.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
//.placeholder(R.mipmap.ic_photo)
//.error(R.mipmap.ic_photo)
.into(object : BitmapImageViewTarget(imageView) {
override fun setResource(resource: Bitmap?) {
val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(imageView.resources, resource)
circularBitmapDrawable.cornerRadius = 10f
imageView.setImageDrawable(circularBitmapDrawable)
}
})
}
fun withUserHead(url: String,
imageView: ImageView) {
GlideApp.with(imageView.context)
.asBitmap()
.load(url)
//.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
//.placeholder(R.mipmap.ic_photo)
//.error(R.mipmap.ic_photo)
.into(object : BitmapImageViewTarget(imageView) {
override fun setResource(resource: Bitmap?) {
val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(imageView.resources, resource)
circularBitmapDrawable.cornerRadius = 20f
imageView.setImageDrawable(circularBitmapDrawable)
}
})
}
} | 36.522388 | 115 | 0.617082 |
96b62e1d945112ed12bb32663b42bafbc6f57867 | 1,365 | kt | Kotlin | graphql-kotlin-schema-generator/src/test/kotlin/com/expedia/graphql/extensions/DeepNameKtTest.kt | tobias-f/graphql-kotlin | 0cc8c31edb77038373b50c7946a45760b0fbc1bd | [
"Apache-2.0"
] | 2 | 2020-07-01T03:36:23.000Z | 2020-07-24T07:12:04.000Z | graphql-kotlin-schema-generator/src/test/kotlin/com/expedia/graphql/extensions/DeepNameKtTest.kt | tobias-f/graphql-kotlin | 0cc8c31edb77038373b50c7946a45760b0fbc1bd | [
"Apache-2.0"
] | null | null | null | graphql-kotlin-schema-generator/src/test/kotlin/com/expedia/graphql/extensions/DeepNameKtTest.kt | tobias-f/graphql-kotlin | 0cc8c31edb77038373b50c7946a45760b0fbc1bd | [
"Apache-2.0"
] | null | null | null | package com.expedia.graphql.extensions
import graphql.schema.GraphQLList
import graphql.schema.GraphQLNonNull
import graphql.schema.GraphQLType
import graphql.schema.GraphQLTypeVisitor
import graphql.util.TraversalControl
import graphql.util.TraverserContext
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
internal class DeepNameKtTest {
private class BasicType : GraphQLType {
override fun getName() = "BasicType"
override fun accept(context: TraverserContext<GraphQLType>, visitor: GraphQLTypeVisitor): TraversalControl =
context.thisNode().accept(context, visitor)
}
private val basicType = BasicType()
@Test
fun `deepname of basic type`() {
assertEquals(expected = "BasicType", actual = basicType.deepName)
}
@Test
fun `deepname of list`() {
val list = GraphQLList(basicType)
assertEquals(expected = "[BasicType]", actual = list.deepName)
}
@Test
fun `deepname of non null`() {
val nonNull = GraphQLNonNull(basicType)
assertEquals(expected = "BasicType!", actual = nonNull.deepName)
}
@Test
fun `deepname of non null list of non nulls`() {
val complicated = GraphQLNonNull(GraphQLList(GraphQLNonNull(basicType)))
assertEquals(expected = "[BasicType!]!", actual = complicated.deepName)
}
}
| 29.673913 | 116 | 0.704029 |
135d02bb61e14fde67e59571f4efcb27e05ebcc0 | 885 | h | C | buildTools/win32-x64/gbdk/include/gbdk/console.h | DeerTears/gb-studio | e5d2a295d9623b2a30ac39e9b518ca48c239959c | [
"MIT"
] | 7 | 2021-11-03T08:18:40.000Z | 2022-03-07T01:39:05.000Z | buildTools/win32-x64/gbdk/include/gbdk/console.h | DeerTears/gb-studio | e5d2a295d9623b2a30ac39e9b518ca48c239959c | [
"MIT"
] | null | null | null | buildTools/win32-x64/gbdk/include/gbdk/console.h | DeerTears/gb-studio | e5d2a295d9623b2a30ac39e9b518ca48c239959c | [
"MIT"
] | 1 | 2022-03-01T03:19:34.000Z | 2022-03-01T03:19:34.000Z | /** @file gbdk/console.h
Console functions that work like Turbo C's.
The font is 8x8, making the screen 20x18 characters.
*/
#ifndef _CONSOLE_H
#define _CONSOLE_H
#include <types.h>
#include <stdint.h>
/** Move the cursor to an absolute position at __x, y__.
__x__ and __y__ have units of tiles (8 pixels per unit)
@see setchar()
*/
void gotoxy(uint8_t x, uint8_t y) OLDCALL;
/** Returns the current X position of the cursor.
@see gotoxy()
*/
uint8_t posx() OLDCALL;
/** Returns the current Y position of the cursor.
@see gotoxy()
*/
uint8_t posy() OLDCALL;
/** Writes out a single character at the current cursor
position.
Does not update the cursor or interpret the character.
@see gotoxy()
*/
void setchar(char c) OLDCALL;
/** Clears the screen
*/
void cls();
#endif /* _CONSOLE_H */
| 19.23913 | 60 | 0.646328 |
cf6b1b2560933dda4b89a50a9ef0c10a88c57491 | 2,824 | kt | Kotlin | workflows/src/main/kotlin/com/carlocoins/workflows/flows/cars/IssueCars.kt | Condition01/carlocoin | 30047cc08def1c85bc95a805a8e26bc34b27cd25 | [
"Apache-2.0"
] | null | null | null | workflows/src/main/kotlin/com/carlocoins/workflows/flows/cars/IssueCars.kt | Condition01/carlocoin | 30047cc08def1c85bc95a805a8e26bc34b27cd25 | [
"Apache-2.0"
] | null | null | null | workflows/src/main/kotlin/com/carlocoins/workflows/flows/cars/IssueCars.kt | Condition01/carlocoin | 30047cc08def1c85bc95a805a8e26bc34b27cd25 | [
"Apache-2.0"
] | null | null | null | package com.carlocoins.workflows.flows.cars
import co.paralleluniverse.fibers.Suspendable
import com.carlocoins.contracts.contracts.CarContract
import com.carlocoins.contracts.states.CarState
import net.corda.core.contracts.Command
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.flows.*
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
@StartableByRPC
object IssueCars {
@InitiatingFlow
class IssueCarsInitiating(
val brand: String,
val model: String,
val dollarPrice: Double
): FlowLogic<String>() {
@Suspendable
override fun call(): String {
val notary = serviceHub.networkMapCache.notaryIdentities[0]
val participants = serviceHub.networkMapCache.allNodes
var parties = participants.map {
it.legalIdentities.first()
}.filter { it != notary }
val me = serviceHub.myInfo.legalIdentities.first()
val carState = CarState(
brand = brand,
model = model,
dollarPrice = dollarPrice,
carloCoinsPaidValue = 0.0,
carloCoinLinearID = "",
owner = me,
seller = me,
linearId = UniqueIdentifier(),
participants = parties
)
val signers = parties.map { it.owningKey }
val command = Command(CarContract.Commands.Issue(), signers)
val txBuilder = TransactionBuilder(notary = notary).apply {
addOutputState(carState)
addCommand(command)
}
val counterpartySessions = parties.filter {
ourIdentity != it
}.map {
initiateFlow(it)
}
val signedTransaction = serviceHub.signInitialTransaction(txBuilder)
val fullySignedTx = subFlow(CollectSignaturesFlow(signedTransaction, counterpartySessions))
subFlow(FinalityFlow(fullySignedTx, counterpartySessions))
return carState.linearId.toString()
}
}
@InitiatedBy(IssueCarsInitiating::class)
class IssueCarsResponder(val counterpartySession: FlowSession) : FlowLogic<Unit>() {
@Suspendable
override fun call() {
val signTransactionFlow = object : SignTransactionFlow(counterpartySession) {
override fun checkTransaction(stx: SignedTransaction) {
val ledgerTx = stx.toLedgerTransaction(serviceHub, false)
}
}
val txId = subFlow(signTransactionFlow).id
subFlow(ReceiveFinalityFlow(counterpartySession, txId))
}
}
}
| 31.377778 | 103 | 0.606941 |
3cc9391dc0cae12fd45314898283feea7c13a188 | 475 | swift | Swift | Classes/Repository/RepositoryIssueSummaryType.swift | ashleyng/GitHawk | a5ed67a924ab7f102788755ae05dccc983238d31 | [
"MIT"
] | 8 | 2018-03-19T14:51:35.000Z | 2019-04-05T14:25:06.000Z | Classes/Repository/RepositoryIssueSummaryType.swift | ashleyng/GitHawk | a5ed67a924ab7f102788755ae05dccc983238d31 | [
"MIT"
] | 1 | 2018-07-19T21:21:36.000Z | 2018-07-19T21:24:05.000Z | Classes/Repository/RepositoryIssueSummaryType.swift | ashleyng/GitHawk | a5ed67a924ab7f102788755ae05dccc983238d31 | [
"MIT"
] | 2 | 2018-09-28T03:40:29.000Z | 2019-07-07T15:45:40.000Z | //
// RepositoryIssueSummaryType.swift
// Freetime
//
// Created by Sherlock, James on 29/07/2017.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import IGListKit
protocol RepositoryIssueSummaryType {
var number: Int { get }
var id: String { get }
var status: IssueStatus { get }
var repoEventFields: RepoEventFields { get }
var labelableFields: LabelableFields { get }
var pullRequest: Bool { get }
var title: String { get }
}
| 21.590909 | 55 | 0.68 |
877bdd5a2157f24f0a858624dfd510673e719d02 | 18,748 | html | HTML | posts/index.html | VueJunkie/vuejunkie.github.io | 258ca41bafd93a3b3410f28c2814295c7e0baf20 | [
"MIT"
] | null | null | null | posts/index.html | VueJunkie/vuejunkie.github.io | 258ca41bafd93a3b3410f28c2814295c7e0baf20 | [
"MIT"
] | null | null | null | posts/index.html | VueJunkie/vuejunkie.github.io | 258ca41bafd93a3b3410f28c2814295c7e0baf20 | [
"MIT"
] | null | null | null | <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/favicon.ico"><title>vuejunkie.github.io</title><script>window.__INITIAL_STATE__= {{site.github}};</script><link href="/assets/css/posts.959c1101.css" rel="prefetch"><link href="/assets/js/chunk-2d0ddd68.9e492fe4.js" rel="prefetch"><link href="/assets/js/chunk-2d0e977f.408a4e86.js" rel="prefetch"><link href="/assets/js/markdown.3668f13e.js" rel="prefetch"><link href="/assets/js/posts.1cebf789.js" rel="prefetch"><link href="/assets/css/app.76e7e79d.css" rel="preload" as="style"><link href="/assets/css/chunk-vendors.7544100d.css" rel="preload" as="style"><link href="/assets/js/app.96baf760.js" rel="preload" as="script"><link href="/assets/js/chunk-vendors.97596147.js" rel="preload" as="script"><link href="/assets/css/chunk-vendors.7544100d.css" rel="stylesheet"><link href="/assets/css/app.76e7e79d.css" rel="stylesheet"><style type="text/css" id="vuetify-theme-stylesheet">.v-application a { color: #1976d2; }
.v-application .primary {
background-color: #1976d2 !important;
border-color: #1976d2 !important;
}
.v-application .primary--text {
color: #1976d2 !important;
caret-color: #1976d2 !important;
}
.v-application .primary.lighten-5 {
background-color: #c7fdff !important;
border-color: #c7fdff !important;
}
.v-application .primary--text.text--lighten-5 {
color: #c7fdff !important;
caret-color: #c7fdff !important;
}
.v-application .primary.lighten-4 {
background-color: #a8e0ff !important;
border-color: #a8e0ff !important;
}
.v-application .primary--text.text--lighten-4 {
color: #a8e0ff !important;
caret-color: #a8e0ff !important;
}
.v-application .primary.lighten-3 {
background-color: #8ac5ff !important;
border-color: #8ac5ff !important;
}
.v-application .primary--text.text--lighten-3 {
color: #8ac5ff !important;
caret-color: #8ac5ff !important;
}
.v-application .primary.lighten-2 {
background-color: #6aaaff !important;
border-color: #6aaaff !important;
}
.v-application .primary--text.text--lighten-2 {
color: #6aaaff !important;
caret-color: #6aaaff !important;
}
.v-application .primary.lighten-1 {
background-color: #488fef !important;
border-color: #488fef !important;
}
.v-application .primary--text.text--lighten-1 {
color: #488fef !important;
caret-color: #488fef !important;
}
.v-application .primary.darken-1 {
background-color: #005eb6 !important;
border-color: #005eb6 !important;
}
.v-application .primary--text.text--darken-1 {
color: #005eb6 !important;
caret-color: #005eb6 !important;
}
.v-application .primary.darken-2 {
background-color: #00479b !important;
border-color: #00479b !important;
}
.v-application .primary--text.text--darken-2 {
color: #00479b !important;
caret-color: #00479b !important;
}
.v-application .primary.darken-3 {
background-color: #003180 !important;
border-color: #003180 !important;
}
.v-application .primary--text.text--darken-3 {
color: #003180 !important;
caret-color: #003180 !important;
}
.v-application .primary.darken-4 {
background-color: #001e67 !important;
border-color: #001e67 !important;
}
.v-application .primary--text.text--darken-4 {
color: #001e67 !important;
caret-color: #001e67 !important;
}
.v-application .secondary {
background-color: #424242 !important;
border-color: #424242 !important;
}
.v-application .secondary--text {
color: #424242 !important;
caret-color: #424242 !important;
}
.v-application .secondary.lighten-5 {
background-color: #c1c1c1 !important;
border-color: #c1c1c1 !important;
}
.v-application .secondary--text.text--lighten-5 {
color: #c1c1c1 !important;
caret-color: #c1c1c1 !important;
}
.v-application .secondary.lighten-4 {
background-color: #a6a6a6 !important;
border-color: #a6a6a6 !important;
}
.v-application .secondary--text.text--lighten-4 {
color: #a6a6a6 !important;
caret-color: #a6a6a6 !important;
}
.v-application .secondary.lighten-3 {
background-color: #8b8b8b !important;
border-color: #8b8b8b !important;
}
.v-application .secondary--text.text--lighten-3 {
color: #8b8b8b !important;
caret-color: #8b8b8b !important;
}
.v-application .secondary.lighten-2 {
background-color: #727272 !important;
border-color: #727272 !important;
}
.v-application .secondary--text.text--lighten-2 {
color: #727272 !important;
caret-color: #727272 !important;
}
.v-application .secondary.lighten-1 {
background-color: #595959 !important;
border-color: #595959 !important;
}
.v-application .secondary--text.text--lighten-1 {
color: #595959 !important;
caret-color: #595959 !important;
}
.v-application .secondary.darken-1 {
background-color: #2c2c2c !important;
border-color: #2c2c2c !important;
}
.v-application .secondary--text.text--darken-1 {
color: #2c2c2c !important;
caret-color: #2c2c2c !important;
}
.v-application .secondary.darken-2 {
background-color: #171717 !important;
border-color: #171717 !important;
}
.v-application .secondary--text.text--darken-2 {
color: #171717 !important;
caret-color: #171717 !important;
}
.v-application .secondary.darken-3 {
background-color: #000000 !important;
border-color: #000000 !important;
}
.v-application .secondary--text.text--darken-3 {
color: #000000 !important;
caret-color: #000000 !important;
}
.v-application .secondary.darken-4 {
background-color: #000000 !important;
border-color: #000000 !important;
}
.v-application .secondary--text.text--darken-4 {
color: #000000 !important;
caret-color: #000000 !important;
}
.v-application .accent {
background-color: #82b1ff !important;
border-color: #82b1ff !important;
}
.v-application .accent--text {
color: #82b1ff !important;
caret-color: #82b1ff !important;
}
.v-application .accent.lighten-5 {
background-color: #ffffff !important;
border-color: #ffffff !important;
}
.v-application .accent--text.text--lighten-5 {
color: #ffffff !important;
caret-color: #ffffff !important;
}
.v-application .accent.lighten-4 {
background-color: #f8ffff !important;
border-color: #f8ffff !important;
}
.v-application .accent--text.text--lighten-4 {
color: #f8ffff !important;
caret-color: #f8ffff !important;
}
.v-application .accent.lighten-3 {
background-color: #daffff !important;
border-color: #daffff !important;
}
.v-application .accent--text.text--lighten-3 {
color: #daffff !important;
caret-color: #daffff !important;
}
.v-application .accent.lighten-2 {
background-color: #bce8ff !important;
border-color: #bce8ff !important;
}
.v-application .accent--text.text--lighten-2 {
color: #bce8ff !important;
caret-color: #bce8ff !important;
}
.v-application .accent.lighten-1 {
background-color: #9fccff !important;
border-color: #9fccff !important;
}
.v-application .accent--text.text--lighten-1 {
color: #9fccff !important;
caret-color: #9fccff !important;
}
.v-application .accent.darken-1 {
background-color: #6596e2 !important;
border-color: #6596e2 !important;
}
.v-application .accent--text.text--darken-1 {
color: #6596e2 !important;
caret-color: #6596e2 !important;
}
.v-application .accent.darken-2 {
background-color: #467dc6 !important;
border-color: #467dc6 !important;
}
.v-application .accent--text.text--darken-2 {
color: #467dc6 !important;
caret-color: #467dc6 !important;
}
.v-application .accent.darken-3 {
background-color: #2364aa !important;
border-color: #2364aa !important;
}
.v-application .accent--text.text--darken-3 {
color: #2364aa !important;
caret-color: #2364aa !important;
}
.v-application .accent.darken-4 {
background-color: #004c90 !important;
border-color: #004c90 !important;
}
.v-application .accent--text.text--darken-4 {
color: #004c90 !important;
caret-color: #004c90 !important;
}
.v-application .error {
background-color: #ff5252 !important;
border-color: #ff5252 !important;
}
.v-application .error--text {
color: #ff5252 !important;
caret-color: #ff5252 !important;
}
.v-application .error.lighten-5 {
background-color: #ffe4d5 !important;
border-color: #ffe4d5 !important;
}
.v-application .error--text.text--lighten-5 {
color: #ffe4d5 !important;
caret-color: #ffe4d5 !important;
}
.v-application .error.lighten-4 {
background-color: #ffc6b9 !important;
border-color: #ffc6b9 !important;
}
.v-application .error--text.text--lighten-4 {
color: #ffc6b9 !important;
caret-color: #ffc6b9 !important;
}
.v-application .error.lighten-3 {
background-color: #ffa99e !important;
border-color: #ffa99e !important;
}
.v-application .error--text.text--lighten-3 {
color: #ffa99e !important;
caret-color: #ffa99e !important;
}
.v-application .error.lighten-2 {
background-color: #ff8c84 !important;
border-color: #ff8c84 !important;
}
.v-application .error--text.text--lighten-2 {
color: #ff8c84 !important;
caret-color: #ff8c84 !important;
}
.v-application .error.lighten-1 {
background-color: #ff6f6a !important;
border-color: #ff6f6a !important;
}
.v-application .error--text.text--lighten-1 {
color: #ff6f6a !important;
caret-color: #ff6f6a !important;
}
.v-application .error.darken-1 {
background-color: #df323b !important;
border-color: #df323b !important;
}
.v-application .error--text.text--darken-1 {
color: #df323b !important;
caret-color: #df323b !important;
}
.v-application .error.darken-2 {
background-color: #bf0025 !important;
border-color: #bf0025 !important;
}
.v-application .error--text.text--darken-2 {
color: #bf0025 !important;
caret-color: #bf0025 !important;
}
.v-application .error.darken-3 {
background-color: #9f0010 !important;
border-color: #9f0010 !important;
}
.v-application .error--text.text--darken-3 {
color: #9f0010 !important;
caret-color: #9f0010 !important;
}
.v-application .error.darken-4 {
background-color: #800000 !important;
border-color: #800000 !important;
}
.v-application .error--text.text--darken-4 {
color: #800000 !important;
caret-color: #800000 !important;
}
.v-application .info {
background-color: #2196f3 !important;
border-color: #2196f3 !important;
}
.v-application .info--text {
color: #2196f3 !important;
caret-color: #2196f3 !important;
}
.v-application .info.lighten-5 {
background-color: #d4ffff !important;
border-color: #d4ffff !important;
}
.v-application .info--text.text--lighten-5 {
color: #d4ffff !important;
caret-color: #d4ffff !important;
}
.v-application .info.lighten-4 {
background-color: #b5ffff !important;
border-color: #b5ffff !important;
}
.v-application .info--text.text--lighten-4 {
color: #b5ffff !important;
caret-color: #b5ffff !important;
}
.v-application .info.lighten-3 {
background-color: #95e8ff !important;
border-color: #95e8ff !important;
}
.v-application .info--text.text--lighten-3 {
color: #95e8ff !important;
caret-color: #95e8ff !important;
}
.v-application .info.lighten-2 {
background-color: #75ccff !important;
border-color: #75ccff !important;
}
.v-application .info--text.text--lighten-2 {
color: #75ccff !important;
caret-color: #75ccff !important;
}
.v-application .info.lighten-1 {
background-color: #51b0ff !important;
border-color: #51b0ff !important;
}
.v-application .info--text.text--lighten-1 {
color: #51b0ff !important;
caret-color: #51b0ff !important;
}
.v-application .info.darken-1 {
background-color: #007cd6 !important;
border-color: #007cd6 !important;
}
.v-application .info--text.text--darken-1 {
color: #007cd6 !important;
caret-color: #007cd6 !important;
}
.v-application .info.darken-2 {
background-color: #0064ba !important;
border-color: #0064ba !important;
}
.v-application .info--text.text--darken-2 {
color: #0064ba !important;
caret-color: #0064ba !important;
}
.v-application .info.darken-3 {
background-color: #004d9f !important;
border-color: #004d9f !important;
}
.v-application .info--text.text--darken-3 {
color: #004d9f !important;
caret-color: #004d9f !important;
}
.v-application .info.darken-4 {
background-color: #003784 !important;
border-color: #003784 !important;
}
.v-application .info--text.text--darken-4 {
color: #003784 !important;
caret-color: #003784 !important;
}
.v-application .success {
background-color: #4caf50 !important;
border-color: #4caf50 !important;
}
.v-application .success--text {
color: #4caf50 !important;
caret-color: #4caf50 !important;
}
.v-application .success.lighten-5 {
background-color: #dcffd6 !important;
border-color: #dcffd6 !important;
}
.v-application .success--text.text--lighten-5 {
color: #dcffd6 !important;
caret-color: #dcffd6 !important;
}
.v-application .success.lighten-4 {
background-color: #beffba !important;
border-color: #beffba !important;
}
.v-application .success--text.text--lighten-4 {
color: #beffba !important;
caret-color: #beffba !important;
}
.v-application .success.lighten-3 {
background-color: #a2ff9e !important;
border-color: #a2ff9e !important;
}
.v-application .success--text.text--lighten-3 {
color: #a2ff9e !important;
caret-color: #a2ff9e !important;
}
.v-application .success.lighten-2 {
background-color: #85e783 !important;
border-color: #85e783 !important;
}
.v-application .success--text.text--lighten-2 {
color: #85e783 !important;
caret-color: #85e783 !important;
}
.v-application .success.lighten-1 {
background-color: #69cb69 !important;
border-color: #69cb69 !important;
}
.v-application .success--text.text--lighten-1 {
color: #69cb69 !important;
caret-color: #69cb69 !important;
}
.v-application .success.darken-1 {
background-color: #2d9437 !important;
border-color: #2d9437 !important;
}
.v-application .success--text.text--darken-1 {
color: #2d9437 !important;
caret-color: #2d9437 !important;
}
.v-application .success.darken-2 {
background-color: #00791e !important;
border-color: #00791e !important;
}
.v-application .success--text.text--darken-2 {
color: #00791e !important;
caret-color: #00791e !important;
}
.v-application .success.darken-3 {
background-color: #006000 !important;
border-color: #006000 !important;
}
.v-application .success--text.text--darken-3 {
color: #006000 !important;
caret-color: #006000 !important;
}
.v-application .success.darken-4 {
background-color: #004700 !important;
border-color: #004700 !important;
}
.v-application .success--text.text--darken-4 {
color: #004700 !important;
caret-color: #004700 !important;
}
.v-application .warning {
background-color: #fb8c00 !important;
border-color: #fb8c00 !important;
}
.v-application .warning--text {
color: #fb8c00 !important;
caret-color: #fb8c00 !important;
}
.v-application .warning.lighten-5 {
background-color: #ffff9e !important;
border-color: #ffff9e !important;
}
.v-application .warning--text.text--lighten-5 {
color: #ffff9e !important;
caret-color: #ffff9e !important;
}
.v-application .warning.lighten-4 {
background-color: #fffb82 !important;
border-color: #fffb82 !important;
}
.v-application .warning--text.text--lighten-4 {
color: #fffb82 !important;
caret-color: #fffb82 !important;
}
.v-application .warning.lighten-3 {
background-color: #ffdf67 !important;
border-color: #ffdf67 !important;
}
.v-application .warning--text.text--lighten-3 {
color: #ffdf67 !important;
caret-color: #ffdf67 !important;
}
.v-application .warning.lighten-2 {
background-color: #ffc24b !important;
border-color: #ffc24b !important;
}
.v-application .warning--text.text--lighten-2 {
color: #ffc24b !important;
caret-color: #ffc24b !important;
}
.v-application .warning.lighten-1 {
background-color: #ffa72d !important;
border-color: #ffa72d !important;
}
.v-application .warning--text.text--lighten-1 {
color: #ffa72d !important;
caret-color: #ffa72d !important;
}
.v-application .warning.darken-1 {
background-color: #db7200 !important;
border-color: #db7200 !important;
}
.v-application .warning--text.text--darken-1 {
color: #db7200 !important;
caret-color: #db7200 !important;
}
.v-application .warning.darken-2 {
background-color: #bb5900 !important;
border-color: #bb5900 !important;
}
.v-application .warning--text.text--darken-2 {
color: #bb5900 !important;
caret-color: #bb5900 !important;
}
.v-application .warning.darken-3 {
background-color: #9d4000 !important;
border-color: #9d4000 !important;
}
.v-application .warning--text.text--darken-3 {
color: #9d4000 !important;
caret-color: #9d4000 !important;
}
.v-application .warning.darken-4 {
background-color: #802700 !important;
border-color: #802700 !important;
}
.v-application .warning--text.text--darken-4 {
color: #802700 !important;
caret-color: #802700 !important;
}</style><link rel="stylesheet" type="text/css" href="/assets/css/posts.959c1101.css"><script charset="utf-8" src="/assets/js/posts.1cebf789.js"></script></head><body><noscript><strong>We're sorry but vuejunkie.github.io doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app" data-app="true" class="v-application v-application--is-ltr theme--light" data-server-rendered="true"><div class="v-application--wrap"><header class="v-sheet theme--light v-toolbar v-app-bar v-app-bar--fixed" data-booted="true" style="height: 56px; margin-top: 0px; transform: translateY(0px); left: 0px; right: 0px;"><div class="v-toolbar__content" style="height: 56px;"><div class="spacer"></div><div class="v-tabs v-tabs--fixed-tabs v-tabs--icons-and-text theme--light"><div role="tablist" class="v-item-group theme--light v-slide-group v-tabs-bar v-tabs-bar--is-mobile primary--text" data-booted="true"><div class="v-slide-group__prev v-slide-group__prev--disabled"><!----></div><div class="v-slide-group__wrapper"><div class="v-slide-group__content v-tabs-bar__content"><div class="v-tabs-slider-wrapper" style="height: 2px; left: 388px; width: 360px;"><div class="v-tabs-slider"></div></div><a href="/" class="v-tab" tabindex="0" aria-selected="false" role="tab"> Home </a><a href="/posts" class="v-tab--active v-tab" tabindex="0" aria-selected="true" role="tab" aria-current="page"> Posts </a></div></div><div class="v-slide-group__next v-slide-group__next--disabled"><!----></div></div></div></div></header><div class="v-window v-item-group theme--light v-tabs-items"><div class="v-window__container"><main class="v-main" id="v-posts-view" style="padding: 56px 0px 0px;" data-booted="true"><div class="v-main__wrap"><div class="v-card v-sheet theme--light"><div>{{content}}</div></div></div></main></div></div></div></div><script src="/assets/js/chunk-vendors.97596147.js"></script><script src="/assets/js/app.96baf760.js"></script></body></html> | 33.418895 | 1,987 | 0.713569 |
9ee7d200e0493bc683b1ea2dd49fc316fcc1f09c | 194 | kt | Kotlin | core/src/commonMain/kotlin/com/algolia/instantsearch/core/subscription/SubscriptionEvent.kt | fobo66/instantsearch-android | eede3c5c02571b5a9e388de92372f65ee99af0c7 | [
"Apache-2.0"
] | null | null | null | core/src/commonMain/kotlin/com/algolia/instantsearch/core/subscription/SubscriptionEvent.kt | fobo66/instantsearch-android | eede3c5c02571b5a9e388de92372f65ee99af0c7 | [
"Apache-2.0"
] | null | null | null | core/src/commonMain/kotlin/com/algolia/instantsearch/core/subscription/SubscriptionEvent.kt | fobo66/instantsearch-android | eede3c5c02571b5a9e388de92372f65ee99af0c7 | [
"Apache-2.0"
] | null | null | null | package com.algolia.instantsearch.core.subscription
public class SubscriptionEvent<T> : Subscription<T>() {
public fun send(event: T) {
subscriptions.forEach { it(event) }
}
} | 21.555556 | 55 | 0.690722 |
2a420ef5edf986497fa07f5bbad764c499bf3fad | 1,363 | java | Java | aliyun-java-sdk-workbench-ide/src/main/java/com/aliyuncs/workbench_ide/transform/v20210121/GetAppRepositoryResponseUnmarshaller.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | 1 | 2022-02-12T06:01:36.000Z | 2022-02-12T06:01:36.000Z | aliyun-java-sdk-workbench-ide/src/main/java/com/aliyuncs/workbench_ide/transform/v20210121/GetAppRepositoryResponseUnmarshaller.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-workbench-ide/src/main/java/com/aliyuncs/workbench_ide/transform/v20210121/GetAppRepositoryResponseUnmarshaller.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.workbench_ide.transform.v20210121;
import com.aliyuncs.workbench_ide.model.v20210121.GetAppRepositoryResponse;
import java.util.Map;
import com.aliyuncs.transform.UnmarshallerContext;
public class GetAppRepositoryResponseUnmarshaller {
public static GetAppRepositoryResponse unmarshall(GetAppRepositoryResponse getAppRepositoryResponse, UnmarshallerContext _ctx) {
getAppRepositoryResponse.setRequestId(_ctx.stringValue("GetAppRepositoryResponse.RequestId"));
getAppRepositoryResponse.setCode(_ctx.stringValue("GetAppRepositoryResponse.Code"));
getAppRepositoryResponse.setMessage(_ctx.stringValue("GetAppRepositoryResponse.Message"));
getAppRepositoryResponse.setData(_ctx.mapValue("GetAppRepositoryResponse.Data"));
return getAppRepositoryResponse;
}
} | 41.30303 | 129 | 0.805576 |
3397eddb232d7ac39bfcc99a4abab0e4ab672052 | 1,845 | kt | Kotlin | lib/src/test/kotlin/com/raybritton/jsonquery/unit/parsers/KeywordParserTests.kt | raybritton/json-query | 17f6629c9ce5259d85aabf1e857fb38ba4adff8d | [
"Apache-2.0"
] | null | null | null | lib/src/test/kotlin/com/raybritton/jsonquery/unit/parsers/KeywordParserTests.kt | raybritton/json-query | 17f6629c9ce5259d85aabf1e857fb38ba4adff8d | [
"Apache-2.0"
] | null | null | null | lib/src/test/kotlin/com/raybritton/jsonquery/unit/parsers/KeywordParserTests.kt | raybritton/json-query | 17f6629c9ce5259d85aabf1e857fb38ba4adff8d | [
"Apache-2.0"
] | 3 | 2019-01-21T07:07:21.000Z | 2019-08-29T14:41:43.000Z | package com.raybritton.jsonquery.unit.parsers
import com.raybritton.jsonquery.parsing.tokens.CharParser
import com.raybritton.jsonquery.parsing.tokens.Keyword
import com.raybritton.jsonquery.parsing.tokens.KeywordParser
import org.junit.Assert.*
import org.junit.Test
import java.util.*
class KeywordParserTests {
@Test
fun `test can parse`() {
val valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
val invalid = "1234567890-=!@£$%^&*()#_+[]{};'\\:\"|,./<>?`~"
for (char in valid) {
assertTrue(char.toString(), KeywordParser.canParse(char))
}
for (char in invalid) {
assertFalse(char.toString(), KeywordParser.canParse(char))
}
}
@Test
fun `test simple upper case keyword detection`() {
val keywords = Keyword.values()
for (word in keywords) {
val reader = CharParser(word.name)
val result = KeywordParser.parse(reader)
assertEquals(word.name, word, result.value)
}
}
@Test
fun `test simple lower case keyword detection`() {
val keywords = Keyword.values()
for (word in keywords) {
val reader = CharParser(word.name.toLowerCase(Locale.US))
val result = KeywordParser.parse(reader)
assertEquals(word.name, word, result.value)
}
}
@Test
fun `test simple mixed case keyword detection`() {
val mixer: (String) -> String = {
it.mapIndexed { i, c -> if (i % 2 == 0) c.toUpperCase() else c }.joinToString("")
}
val keywords = Keyword.values()
for (word in keywords) {
val reader = CharParser(mixer(word.name))
val result = KeywordParser.parse(reader)
assertEquals(word.name, word, result.value)
}
}
} | 30.245902 | 93 | 0.606504 |
017ee011dd8fae28947c0075cfdf80517defa24d | 20,328 | lua | Lua | src/button.lua | SMG233/Undertale-Battle-Engine | 37ec4522edd7c059f36022a0384b77906dffe1ac | [
"MIT"
] | 1 | 2020-02-13T01:50:54.000Z | 2020-02-13T01:50:54.000Z | src/button.lua | SMG233/Undertale-Battle-Engine | 37ec4522edd7c059f36022a0384b77906dffe1ac | [
"MIT"
] | null | null | null | src/button.lua | SMG233/Undertale-Battle-Engine | 37ec4522edd7c059f36022a0384b77906dffe1ac | [
"MIT"
] | null | null | null |
local function CutImage( image, w, h )
local q = {}
for i = 1, h do
for j = 1, w do
local nq = love.graphics.newQuad(
(j-1)*image:getWidth()/w, (i-1)*image:getHeight()/h,
image:getWidth()/w, image:getHeight()/h,
image:getWidth(), image:getHeight()
)
table.insert( q, nq )
end
end
image:release()
return q
end
local Button = {}
function Button.Reset()
Button.TargetChoiceState = 1
Button.Pressed = false
Button.TargetX1 = 0
Button.TargetValue = 0
Button.TargetDir = love.math.random(1, 2)
if Button.TargetDir == 1 then
Button.TargetX = 610-10
else
Button.TargetX = 30
end
Button.SliceState = 1
Button.Sin = 0
Button.TargetWidth = 1
Button.TargetY = 0
Button.x = 0
Button.y = 0
Button.Choice = 1
Button.MenuChoice = 1
Button.MenuSecChoice = 1
Button.MenuState = 1
for k, v in pairs(Button.Button) do
v.CurFrame = 1
end
end
Button.Pressed = false
Button.Target = love.graphics.newImage("res/spr_target_0.png")
Button.TargetChoiceState = 1
Button.TargetValue = 0
Button.TargetDir = love.math.random(1, 2)
if Button.TargetDir == 1 then
Button.TargetX = 610-10
else
Button.TargetX = 30
end
Button.Slice = {
love.graphics.newImage("res/spr_slice_o_0.png"),
love.graphics.newImage("res/spr_slice_o_1.png"),
love.graphics.newImage("res/spr_slice_o_2.png"),
love.graphics.newImage("res/spr_slice_o_3.png"),
love.graphics.newImage("res/spr_slice_o_4.png"),
love.graphics.newImage("res/spr_slice_o_5.png")
}
Button.SliceState = 1
Button.TargetWidth = 1
Button.TargetY = 0
Button.Damage = love.graphics.newFont("res/damage.TTF", 40)
Button.TargetChoice = {love.graphics.newImage("res/spr_targetchoice_0.png"), love.graphics.newImage("res/spr_targetchoice_1.png")}
Button.Button = {
{
Image = love.graphics.newImage( "res/spr_fight_strip2.png" ),
ImageFrame = 2,
CurFrame = 2,
Quad = CutImage( love.graphics.newImage( "res/spr_fight_strip2.png" ), 2, 1 )
},
{
Image = love.graphics.newImage( "res/spr_act_strip2.png" ),
ImageFrame = 2,
CurFrame = 1,
Quad = CutImage( love.graphics.newImage( "res/spr_act_strip2.png" ), 2, 1 )
},
{
Image = love.graphics.newImage( "res/spr_item_strip2.png" ),
ImageFrame = 2,
CurFrame = 1,
Quad = CutImage( love.graphics.newImage( "res/spr_item_strip2.png" ), 2, 1 )
},
{
Image = love.graphics.newImage( "res/spr_mercy_strip2.png" ),
ImageFrame = 2,
CurFrame = 1,
Quad = CutImage( love.graphics.newImage( "res/spr_mercy_strip2.png" ), 2, 1 )
}
}
Button.AllButtons = #Button.Button
Button.x = 0
Button.y = 0
Button.Choice = 1
Button.MenuChoice = 1
Button.MenuSecChoice = 1
Button.MenuState = 1
Button.Sin = 0
Button.DamageValue = "MISS"
Button.DamageColor = {.9,.9,.9,1}
Button.TargetX1 = 0
Button.List = {
"Fight",
"Act",
"Item",
"Mercy"
}
Button.Fight = {
Update = function( dt )
local h = GLOBAL_UT_BATTLE.Heart
if Button.MenuState == 1 then
h.x = 60
h.y = (Button.MenuChoice - 1)*40 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice + 1 <= #GLOBAL_UT_BATTLE.Boss.Boss then
Button.MenuChoice = Button.MenuChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Up then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice - 1 >= 1 then
Button.MenuChoice = Button.MenuChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuState = 2
end
elseif Button.MenuState == 2 then
h.x, h.y = Button.x + 32 + (46+Button.Button[Button.Choice].Image:getWidth()/Button.Button[Button.Choice].ImageFrame) * (Button.Choice-1) + 8,
Button.y + 430 + 12
Button.TargetValue = Button.TargetValue + dt*20
if Button.TargetDir == 1 then
Button.TargetX = Button.TargetX - Button.TargetValue
else
Button.TargetX = Button.TargetX + Button.TargetValue
end
if Button.TargetX > 610 or Button.TargetX < 10 then
Button.DamageValue = "MISS"
Button.DamageColor = {.9,.9,.9,1}
Button.MenuState = 4
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice]:MissEvent()
end
if GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
Button.MenuState = 3
if GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].CanMiss then
Button.DamageValue = "MISS"
Button.DamageColor = {.9,.9,.9,1}
else
Button.DamageValue = Player.Damage
Button.DamageColor = {1,0,0,1}
end
GLOBAL_UT_BATTLE.PressedKey = nil
end
elseif Button.MenuState == 3 then
Button.TargetChoiceState = Button.TargetChoiceState + dt*10
if Button.TargetChoiceState > 3 then
Button.TargetChoiceState = 1
end
if Button.SliceState >= #Button.Slice+1 then
Button.MenuState = 4
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice]:FightEvent()
end
Button.SliceState = Button.SliceState + dt*10
elseif Button.MenuState == 4 then
local b = GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice]
if not tonumber(Button.DamageValue) then
b:Hurt(0)
else
Button.DamageValue = math.max(Player.MinDamage, math.floor(Player.Damage * math.abs(1-math.abs(Button.TargetX-290)/580)))
b:Hurt(Button.DamageValue)
end
b:Shake()
Button.TargetY = b.OriY
Button.TargetValue = 0
Button.TargetX1 = b.OriX
Button.MenuState = 5
elseif Button.MenuState == 5 then
Button.TargetChoiceState = Button.TargetChoiceState + dt*20
if Button.TargetChoiceState > 3 then
Button.TargetChoiceState = 1
end
if Button.TargetValue >= dt*30 then
Button.TargetValue = Button.TargetValue + dt
if Button.TargetWidth <= 0 then
Button.Reset()
Turn = false
end
Button.TargetWidth = Button.TargetWidth - dt*1.5
else
if Button.TargetY > GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].OriY then else
Button.Sin = Button.Sin + dt*2
Button.TargetY = GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].OriY+1 - math.abs(math.sin(Button.Sin)*50)
end
if GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].State == "Idle" then
Button.TargetValue = Button.TargetValue + dt*2
end
end
end
end,
Draw = function ()
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setFont( GLOBAL_UT_BATTLE.Font )
if Button.MenuState == 1 then
for k,v in pairs( GLOBAL_UT_BATTLE.Boss.Boss ) do
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 96, 230 + k*40 )
love.graphics.setColor(1, 0, 0, 1)
love.graphics.rectangle('fill', 280, 240+k*40-3, v.MaxHealth, 20)
love.graphics.setColor(0, 1, 0, 1)
love.graphics.rectangle('fill', 280, 240+k*40-3, v.Health, 20)
love.graphics.setColor(1, 1, 1, 1)
end
elseif Button.MenuState >= 2 then
love.graphics.setColor(1, 1, 1, Button.TargetWidth)
love.graphics.draw(Button.Target, 320-Button.Target:getWidth()*Button.TargetWidth/2, GLOBAL_UT_BATTLE.Box.y+GLOBAL_UT_BATTLE.Box.LineWidth*2.5, 0, Button.TargetWidth, 1)
love.graphics.setColor(1, 1, 1, 1)
if Button.MenuState <= 5 then
love.graphics.draw(Button.TargetChoice[math.min(#Button.TargetChoice+1, math.floor(Button.TargetChoiceState))], Button.TargetX, GLOBAL_UT_BATTLE.Box.y+GLOBAL_UT_BATTLE.Box.LineWidth)
end
end
if Button.MenuState == 3 then
love.graphics.draw(Button.Slice[math.min(#Button.Slice, math.floor(Button.SliceState))], GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].OriX-19, GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].OriY-77, 0, 1.5)
end
if Button.MenuState == 5 then
love.graphics.setFont(Button.Damage)
love.graphics.setColor(unpack(Button.DamageColor))
GLOBAL_UT_BATTLE.Print(Button.DamageValue, Button.TargetX1-Button.Damage:getWidth("a")*#tostring(Button.DamageValue)/2, Button.TargetY)
end
end
}
Button.Act = {
Update = function( dt )
local h = GLOBAL_UT_BATTLE.Heart
if Button.MenuState == 1 then
h.x = 60
h.y = (Button.MenuChoice - 1)*40 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice + 1 <= #GLOBAL_UT_BATTLE.Boss.Boss then
Button.MenuChoice = Button.MenuChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Up then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice - 1 >= 1 then
Button.MenuChoice = Button.MenuChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuState = 2
end
elseif Button.MenuState == 2 then
if Button.MenuSecChoice % 2 == 0 then
h.x = 320
else
h.x = 60
end
h.y = (math.ceil(Button.MenuSecChoice/2)-1)*40 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Up then
if Button.MenuSecChoice - 2 >= 1 then
Button.MenuSecChoice = Button.MenuSecChoice - 2
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuSecChoice + 2 <= #GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption then
Button.MenuSecChoice = Button.MenuSecChoice + 2
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Left then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuSecChoice - 1 >= 1 then
Button.MenuSecChoice = Button.MenuSecChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Right then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuSecChoice + 1 <= #GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption then
Button.MenuSecChoice = Button.MenuSecChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
h.x, h.y = Button.x + 32 + (46+Button.Button[Button.Choice].Image:getWidth()/Button.Button[Button.Choice].ImageFrame) * (Button.Choice-1) + 8,
Button.y + 430 + 12
GLOBAL_DIALOGUE:Init( GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption[Button.MenuSecChoice].Dialogue() )
GLOBAL_DIALOGUE.x,GLOBAL_DIALOGUE.y = 40, 270
GLOBAL_DIALOGUE:Reset()
Button.MenuState = 3
end
elseif Button.MenuState == 3 then
if GLOBAL_DIALOGUE.Done then
GLOBAL_DIALOGUE:Init( GLOBAL_BATTLE_DIALOGUE )
GLOBAL_DIALOGUE.x,GLOBAL_DIALOGUE.y = 40, 270
GLOBAL_DIALOGUE:Reset()
GLOBAL_DIALOGUE.Done = true
GLOBAL_DIALOGUE.Char = {}
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption[Button.MenuSecChoice].Time = GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption[Button.MenuSecChoice].Time + 1
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption[Button.MenuSecChoice].Event()
Turn = false
Button.Reset()
end
end
end,
Draw = function ()
love.graphics.setFont( GLOBAL_UT_BATTLE.Font )
if Button.MenuState == 1 then
for k,v in pairs( GLOBAL_UT_BATTLE.Boss.Boss ) do
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 96, 230 + k*40 )
end
elseif Button.MenuState == 2 then
for k,v in ipairs( GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].ActOption ) do
if k % 2 == 0 then
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 356, (math.ceil(k/2)-1)*40 + 270 )
else
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 96, (math.ceil(k/2)-1)*40 + 270 )
end
end
end
end
}
Button.Item = {
Update = function( dt )
if #Player.Item == 0 then
Button.Reset()
end
local h = GLOBAL_UT_BATTLE.Heart
if Button.MenuState == 1 then
if Button.MenuChoice % 2 == 0 then
h.x = 320
else
h.x = 60
end
h.y = (math.ceil(Button.MenuChoice/2)-1)*40 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Up then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice - 2 >= 1 then
Button.MenuChoice = Button.MenuChoice - 2
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice + 2 <= #Player.Item then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuChoice = Button.MenuChoice + 2
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Left then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice - 1 >= 1 then
Button.MenuChoice = Button.MenuChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Right then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice + 1 <= #Player.Item then
Button.MenuChoice = Button.MenuChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
h.x, h.y = Button.x + 32 + (46+Button.Button[Button.Choice].Image:getWidth()/Button.Button[Button.Choice].ImageFrame) * (Button.Choice-1) + 8,
Button.y + 430 + 12
local str
if Player.Health + Player.ItemHealth[Button.MenuChoice] >= Player.MaxHealth then
str = "* Your hp maxs out!"
else
str = "* You recovered " .. Player.ItemHealth[Button.MenuChoice] .. " hps!"
end
GLOBAL_DIALOGUE:Init( "* You ate " .. Player.Item[Button.MenuChoice] .. "./" .. str )
GLOBAL_DIALOGUE.x,GLOBAL_DIALOGUE.y = 40, 270
GLOBAL_DIALOGUE:Reset()
Button.MenuState = 3
end
elseif Button.MenuState == 3 then
if GLOBAL_DIALOGUE.Done then
GLOBAL_DIALOGUE:Init( GLOBAL_BATTLE_DIALOGUE )
GLOBAL_DIALOGUE.x,GLOBAL_DIALOGUE.y = 40, 270
GLOBAL_DIALOGUE:Reset()
GLOBAL_DIALOGUE.Done = true
GLOBAL_DIALOGUE.Char = {}
Button.Reset()
Button.Pressed = false
for k,v in pairs( GLOBAL_UT_BATTLE.Boss.Boss ) do
v.Item = v.Item + 1
v:ItemEvent()
end
if Player.Health + Player.ItemHealth[Button.MenuChoice] >= Player.MaxHealth then
Player.Health = Player.MaxHealth
else
Player.Health = Player.Health + Player.ItemHealth[Button.MenuChoice]
end
table.remove( Player.Item, Button.MenuChoice )
Turn = false
end
end
end,
Draw = function()
love.graphics.setFont( GLOBAL_UT_BATTLE.Font )
love.graphics.setColor( 1, 1, 1, 1 )
if Button.MenuState == 1 then
for k,v in ipairs( Player.Item ) do
if k % 2 == 0 then
GLOBAL_UT_BATTLE.Print( "* " .. v, 356, (math.ceil(k/2)-1)*40 + 270 )
else
GLOBAL_UT_BATTLE.Print( "* " .. v, 96, (math.ceil(k/2)-1)*40 + 270 )
end
end
end
end
}
Button.Mercy = {
Update = function ( dt )
local h = GLOBAL_UT_BATTLE.Heart
if Button.MenuState == 1 then
h.x = 60
h.y = (Button.MenuChoice - 1)*40 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice + 1 <= #GLOBAL_UT_BATTLE.Boss.Boss then
Button.MenuChoice = Button.MenuChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Up then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuChoice - 1 >= 1 then
Button.MenuChoice = Button.MenuChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuState = 2
end
elseif Button.MenuState == 2 then
h.x = 60
h.y = (Button.MenuSecChoice - 1)*20 + 278
if GLOBAL_UT_BATTLE.PressedKey == Key.Down then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuSecChoice + 1 <= #GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].MercyOption then
Button.MenuSecChoice = Button.MenuSecChoice + 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Up then
GLOBAL_UT_BATTLE.PressedKey = nil
if Button.MenuSecChoice - 1 >= 1 then
Button.MenuSecChoice = Button.MenuSecChoice - 1
end
elseif GLOBAL_UT_BATTLE.PressedKey == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
Turn = false
Button.Reset()
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].MercyOption[Button.MenuSecChoice].Event()
GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].MercyOption[Button.MenuSecChoice].Time = GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].MercyOption[Button.MenuSecChoice].Time + 1
end
end
end,
Draw = function ()
love.graphics.setFont( GLOBAL_UT_BATTLE.Font )
if Button.MenuState == 1 then
for k,v in pairs( GLOBAL_UT_BATTLE.Boss.Boss ) do
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 96, 230 + k*40 )
end
elseif Button.MenuState == 2 then
for k,v in pairs( GLOBAL_UT_BATTLE.Boss.Boss[Button.MenuChoice].MercyOption ) do
GLOBAL_UT_BATTLE.Print( "* " .. v.Name, 96, 230 + k*40 )
end
end
end
}
function Button.Update( dt )
if Turn then
GLOBAL_UT_BATTLE.Heart.CanMove = false
local h = GLOBAL_UT_BATTLE.Heart
if not Button.Pressed then
h.x, h.y = Button.x + 32 + (46+Button.Button[Button.Choice].Image:getWidth()/Button.Button[Button.Choice].ImageFrame) * (Button.Choice-1) + 8,
Button.y + 430 + 12
else
Button[Button.List[Button.Choice]].Update( dt )
end
else
GLOBAL_UT_BATTLE.Heart.CanMove = true
for i = 1, Button.AllButtons do
Button.Button[i].CurFrame = 1
end
end
end
function Button.Draw()
love.graphics.setColor( 1, 1, 1, 1 )
for i = 1, Button.AllButtons do
love.graphics.draw( Button.Button[i].Image, Button.Button[i].Quad[Button.Button[i].CurFrame],
Button.x + 32 + (46+Button.Button[i].Image:getWidth()/Button.Button[i].ImageFrame) * (i-1),
Button.y + 430 )
end
love.graphics.setColor(1, 1, 1, 1)
if Button.Pressed then
Button[Button.List[Button.Choice]].Draw()
end
end
function Button.KeyPressed( k )
if Turn then
if not Button.Pressed then
if k == Key.Enter then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuChoice, Button.MenuSecChoice, Button.MenuState = 1, 1, 1
GLOBAL_DIALOGUE.Char = {}
GLOBAL_DIALOGUE.Done = true
Button.Pressed = true
elseif k == Key.Left then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.Choice = Button.Choice - 1
if Button.Choice < 1 then
Button.Choice = #Button.Button
end
for k,v in pairs( Button.Button ) do
v.CurFrame = 1
end
Button.Button[Button.Choice].CurFrame = 2
elseif k == Key.Right then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.Choice = Button.Choice + 1
if Button.Choice > #Button.Button then
Button.Choice = 1
end
for k,v in pairs( Button.Button ) do
v.CurFrame = 1
end
Button.Button[Button.Choice].CurFrame = 2
end
else
if k == Key.Exit and Button.MenuState == 1 then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.Pressed = false
Button.MenuChoice = 1
GLOBAL_DIALOGUE:Reset()
elseif k == Key.Exit and Button.MenuState == 2 then
GLOBAL_UT_BATTLE.PressedKey = nil
Button.MenuState = 1
Button.MenuSecChoice = 1
end
end
end
end
return Button | 37.162706 | 213 | 0.621606 |
40fb57d2e7a001152acf4f7d19add4d0ba65f5d1 | 560 | py | Python | pyquilted/builder/contacts.py | cocoroutine/pyquilted | dd8644043deec17608e00f46e3ac4562b8879603 | [
"MIT"
] | 1 | 2019-02-21T20:10:37.000Z | 2019-02-21T20:10:37.000Z | pyquilted/builder/contacts.py | cocoroutine/pyquilted | dd8644043deec17608e00f46e3ac4562b8879603 | [
"MIT"
] | null | null | null | pyquilted/builder/contacts.py | cocoroutine/pyquilted | dd8644043deec17608e00f46e3ac4562b8879603 | [
"MIT"
] | null | null | null | from pyquilted.quilted.contact_factory import ContactFactory
from pyquilted.quilted.contacts_list import ContactsList
class ContactsBuilder:
"""Contacts data mapper object"""
def __init__(self, contacts_odict):
self.contacts = ContactsList()
self.odict = contacts_odict
def deserialize(self):
for key, val in self.odict.items():
self._add_contact(ContactFactory.create(key, val))
return self.contacts
def _add_contact(self, contact):
if contact:
self.contacts.append(contact)
| 29.473684 | 62 | 0.694643 |
679fbd37eeb365307dbeb2d2000a21ed2d16e33e | 219 | sql | SQL | src/main/resources/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_update.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 742 | 2015-02-03T02:02:15.000Z | 2022-03-15T16:54:25.000Z | src/main/resources/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_update.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 760 | 2015-02-01T11:40:05.000Z | 2022-01-21T23:22:06.000Z | src/main/resources/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_update.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 285 | 2015-02-23T08:02:29.000Z | 2022-03-25T02:48:31.000Z | UPDATE SERVICE_CONFIGS
SET
SERVICE_LABEL = ?
, SERVICE_ICON = ?
, SERVICE_IMAGE = ?
, INSERT_USER = ?
, INSERT_DATETIME = ?
, UPDATE_USER = ?
, UPDATE_DATETIME = ?
, DELETE_FLAG = ?
WHERE
SERVICE_NAME = ?
;
| 15.642857 | 22 | 0.648402 |
f38549ac14c4dac32d4543e15c6e56460aa10fbc | 250 | kt | Kotlin | src/main/kotlin/dev/lunarcoffee/beanly/exts/commands/utility/GuildOverrides.kt | LunarCoffee/Beanly | 8f428aa32dd7b69903bf57dab67e248fdbda688d | [
"MIT"
] | 3 | 2019-05-03T04:44:47.000Z | 2019-05-08T04:18:56.000Z | src/main/kotlin/dev/lunarcoffee/beanly/exts/commands/utility/GuildOverrides.kt | LunarCoffee/Beanly | 8f428aa32dd7b69903bf57dab67e248fdbda688d | [
"MIT"
] | null | null | null | src/main/kotlin/dev/lunarcoffee/beanly/exts/commands/utility/GuildOverrides.kt | LunarCoffee/Beanly | 8f428aa32dd7b69903bf57dab67e248fdbda688d | [
"MIT"
] | null | null | null | package dev.lunarcoffee.beanly.exts.commands.utility
class GuildOverrides(val id: String, val noPayRespects: Boolean, val noSuggestCommands: Boolean)
// Use this when referring to properties with typed KMongo queries.
typealias GO = GuildOverrides
| 35.714286 | 96 | 0.82 |
b33ed21011c1baec4735f7cc73eddfe6e0b9f221 | 335 | rb | Ruby | rb/convert_pm2md.rb | dohliam/pmdown | 9e565ba0f793fbd489788b81d37f8c3191465fb6 | [
"MIT"
] | null | null | null | rb/convert_pm2md.rb | dohliam/pmdown | 9e565ba0f793fbd489788b81d37f8c3191465fb6 | [
"MIT"
] | null | null | null | rb/convert_pm2md.rb | dohliam/pmdown | 9e565ba0f793fbd489788b81d37f8c3191465fb6 | [
"MIT"
] | null | null | null | #!/usr/bin/env ruby
# convert Markdown (.md) files to PmWiki (.pmwiki) format
require_relative 'libpm2md.rb'
filename = ARGF
if !filename
abort("Please specify a file to convert.")
elsif !File.exist?(filename)
abort("Specified file does not exist.")
end
md_file = filename.read
# puts md_to_pm(md_file)
puts pm_to_md(md_file)
| 18.611111 | 57 | 0.737313 |
16fbfcfdc055d52e7102e95808da82e285dfc130 | 1,643 | ts | TypeScript | angular_fichajesPi/src/app/shared/components/chart/chart.component.ts | alejandroferrin/fichajespi | b7aa30b452041408a49bd3cc375e96c77b85cc3f | [
"MIT"
] | null | null | null | angular_fichajesPi/src/app/shared/components/chart/chart.component.ts | alejandroferrin/fichajespi | b7aa30b452041408a49bd3cc375e96c77b85cc3f | [
"MIT"
] | null | null | null | angular_fichajesPi/src/app/shared/components/chart/chart.component.ts | alejandroferrin/fichajespi | b7aa30b452041408a49bd3cc375e96c77b85cc3f | [
"MIT"
] | null | null | null | import { Component, Input, OnInit } from '@angular/core';
import { ChartDataService } from '../../interfaces/ChartDataService';
//https://primefaces.org/primeng/showcase/#/
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
@Input() service: ChartDataService | null = null;
@Input() serieName: string = 'serie';
@Input() chartTitle: string = 'chart title';
basicData: any;
basicOptions: any;
constructor() {
}
ngOnInit(): void {
this.service?.getChartData().subscribe(
data => {
this.initChart(data.fechas, data.cantidades);
}
)
}
initChart(labels: any[], cantidades: any[]) {
this.basicData = {
//labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
labels: labels,
datasets: [
{
label: this.serieName,
data: cantidades,
fill: true,
//borderColor: '#42A5F5',
borderColor: '#D21757',
backgroundColor: '#D7EBED',
//tension: .4
tension: 0.2
},
]
};
this.basicOptions = {
plugins: {
legend: {
labels: {
color: '#495057'
}
}
},
scales: {
x: {
ticks: {
color: '#495057'
},
grid: {
color: '#ebedef'
}
},
y: {
ticks: {
color: '#495057'
},
grid: {
color: '#ebedef'
}
}
}
};
}
}
| 19.104651 | 81 | 0.48448 |
70d6b826451c296f11e78b822a4e429171ad2aa2 | 1,037 | h | C | NHXLS/DHxls/DHFont.h | nenhall/NHXLS | 4d23612f1d9b68ae5bda425d4939f529fbc94649 | [
"MIT"
] | null | null | null | NHXLS/DHxls/DHFont.h | nenhall/NHXLS | 4d23612f1d9b68ae5bda425d4939f529fbc94649 | [
"MIT"
] | null | null | null | NHXLS/DHxls/DHFont.h | nenhall/NHXLS | 4d23612f1d9b68ae5bda425d4939f529fbc94649 | [
"MIT"
] | null | null | null | //
// DHFont.h
// DHxls
//
// Created by David Hoerl on 10/7/08.
// Copyright 2008-2013 David Hoerl. All rights reserved.
//
@interface DHFont : NSObject
//+(DHFont *)fontWithName:(NSString *)fontName;
-(id)initWithFont:(void *)ft; // xlslib_core::CFont *
-(void *)font;
-(void)setName:(NSString *)name;
-(NSString *)name;
-(void)setHeight:(unsigned short)fntheight;
-(unsigned short)height;
-(void)setBoldStyle:(boldness_option_t)fntboldness;
-(unsigned short)boldStyle;
-(void)setUnderlineStyle:(underline_option_t)fntunderline;
-(unsigned char)underlineStyle;
-(void)SetScriptStyle:(script_option_t)fntscript;
-(unsigned short)scriptStyle;
-(void)setColorName:(color_name_t)fntcolor;
-(void)setColorIndex:(unsigned8_t)fntcolor;
-(unsigned short)colorIndex;
-(void)setItalic:(BOOL)italic;
-(BOOL)italic;
-(void)setStrikeout:(BOOL)so;
-(BOOL)strikeOut;
-(void)setOutline:(BOOL)ol;
-(BOOL)outline;
-(void)setFamily:(unsigned char)fam;
-(unsigned char)family;
-(void)setCharset:(unsigned char)fam;
-(unsigned char)charset;
@end
| 24.690476 | 58 | 0.744455 |
96863e601ebda8d6541f3b53682396629e6cdcc8 | 5,680 | php | PHP | app/Http/Controllers/Kaoshi/GoodsController.php | zhanghaowei0620/week | 2c485470ef0a44e7e53dc61a92bf1bfd9e92fa99 | [
"MIT"
] | null | null | null | app/Http/Controllers/Kaoshi/GoodsController.php | zhanghaowei0620/week | 2c485470ef0a44e7e53dc61a92bf1bfd9e92fa99 | [
"MIT"
] | null | null | null | app/Http/Controllers/Kaoshi/GoodsController.php | zhanghaowei0620/week | 2c485470ef0a44e7e53dc61a92bf1bfd9e92fa99 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Kaoshi;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class GoodsController extends Controller
{
public function index() //首页展示
{
return view('kaoshi.index');
}
public function lis() //商品列表
{
$arr = DB::table('kao_goods')->where('is_del',1)->get();
return view('kaoshi.goods',['arr'=>$arr]);
}
public function add(Request $request) //商品添加展示
{
$cookie_id = $request->cookie('id');
if ($cookie_id){
return view('kaoshi.add');
}else{
header('Refresh:3;url=log');
die("请先登录,自动跳转至登录页面");
}
}
public function add_goods(Request $request) //商品添加执行
{
$goods_name = $request->input('goods_name');
$goods_img = $this->upload($request,'goods_img');
$info = [
'goods_name' => $goods_name,
'goods_img' => $goods_img,
];
// print_r($info);die;
$cart_json = json_encode($info);
// print_r($cart_json);die;
$k = openssl_pkey_get_private('file://'.storage_path('app/key/private.pem'));
openssl_private_encrypt($cart_json,$enc_data,$k);
$arr = base64_encode($enc_data);
$url='http://vm.lianxi.com/add_goods_do'; //重定向地址
//创建一个新curl资源 初始化
$ch = curl_init();
//设置URL和对应的选项
curl_setopt($ch,CURLOPT_URL,$url);
//为post请求
curl_setopt($ch,CURLOPT_POST,1);
//发送数据
curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
//禁止浏览器输出,用变量接收
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁止 cURL 验证对等证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否检测服务器的域名与证书上的是否一致
//抓取URL并传给浏览器
$data = curl_exec($ch);
echo $data;
//查看错误码
$err_code = curl_errno($ch);
if ($err_code > 0){
echo "CURL错误码:".$err_code;
exit;
}
//关闭curl资源,并释放系统内存
curl_close($ch);
}
public function add_goods_do() //商品添加执行
{
$str = file_get_contents("php://input");
$arr = base64_decode($str); //base64解开
// print_r($arr);
$pk = openssl_get_publickey('file://'.storage_path('app/key/public.pem')); //公钥解开
openssl_public_decrypt($arr,$dec_data,$pk);
echo '<hr>';
// echo '明文:'.$dec_data;
$arr = json_decode($dec_data);
// print_r($arr);die;
$goods_name = $arr->goods_name;
$goods_img = $arr->goods_img;
$info = [
'goods_name' => $goods_name,
'goods_img' => $goods_img,
];
// print_r($info);die;
$res = DB::table('kao_goods')->insert($info);
if ($res){
$response = [
'errno' => 50006,
'msg' => '成功',
];
die(json_encode($response,JSON_UNESCAPED_UNICODE));
// header('Refresh:3;url=log');
}else{
$response = [
'errno' => 50005,
'msg' => '添加失败',
];
die(json_encode($response,JSON_UNESCAPED_UNICODE));
}
}
public function updata(Request $request) //修改展示
{
$goods_id = $request->input('goods_id');
$arr = DB::table('kao_goods')->where('goods_id','=',$goods_id)->first();
return view('kaoshi.updata',['arr'=>$arr]);
}
public function updata_do(Request $request) //修改
{
$goods_id = $request->input('goods_id');
// print_r($goods_id);die;
$data = $request->input();
$cookie_id = $request->cookie('id');
if ($cookie_id){
$info = [
'goods_name' => $data['goods_name'],
'goods_img' => $data['goods_img'],
];
// print_r($info);die;
$res = DB::table('kao_goods')->where('goods_id',$goods_id)->update($info);
if($res){
$arr = ['status'=>50007,'msg'=>'修改成功'];
return $arr;
}else{
$arr = ['status'=>50008,'msg'=>'修改失败'];
return $arr;
}
}else{
header('Refresh:3;url=log');
die("请先登录,自动跳转至登录页面");
}
}
public function del(Request $request) //删除
{
$goods_id = $request->input('goods_id');
$cookie_id = $request->cookie('id');
if ($cookie_id){
$info = [
'is_del' => 2,
];
$arr = DB::table('kao_goods')->where('goods_id',$goods_id)->update($info);
if($arr){
$arr = ['status'=>50009,'msg'=>'删除成功'];
die(json_encode($arr,JSON_UNESCAPED_UNICODE));
return $arr;
}else{
$arr = ['status'=>50010,'msg'=>'删除失败'];
die(json_encode($arr,JSON_UNESCAPED_UNICODE));
return $arr;
}
}else{
header('Refresh:3;url=log');
die("请先登录,自动跳转至登录页面");
}
}
public function upload(Request $request,$filename) //文件上传
{
if ($request->hasFile($filename) && $request->file($filename)->isValid()) {
$photo = $request->file($filename);
// $extension = $photo->extension();
// $store_result = $photo->store('photo');
$store_result = $photo->store('uploads/'.date('Ymd'));
return $store_result;
}
exit('未获取到上传文件或上传过程出错');
}
}
| 28.686869 | 90 | 0.502289 |
e74c46b6486b4f756c2e19bb4b7a4fc55d7c12d3 | 191 | js | JavaScript | lib/remove.js | garbados/spare | aabda94f90e774fab369d064d77d6b84efc1d20d | [
"MIT"
] | 2 | 2016-11-08T15:12:51.000Z | 2018-01-18T22:08:21.000Z | lib/remove.js | garbados/spare | aabda94f90e774fab369d064d77d6b84efc1d20d | [
"MIT"
] | null | null | null | lib/remove.js | garbados/spare | aabda94f90e774fab369d064d77d6b84efc1d20d | [
"MIT"
] | null | null | null | var PouchDB = require('pouchdb'),
util = require('./util');
module.exports = function (remote, target, date, done) {
PouchDB.destroy(target || util.get_db_name(remote, date), done);
}; | 31.833333 | 66 | 0.675393 |
e76902050e44c79f66218da7eea48f0407a77132 | 6,084 | js | JavaScript | app/tests/unit/components/validators/validators.customValidators.spec.js | parc-jason/common-logging | 9c658fb4f326e8d5af9614a35d9004405d7b5587 | [
"Apache-2.0"
] | null | null | null | app/tests/unit/components/validators/validators.customValidators.spec.js | parc-jason/common-logging | 9c658fb4f326e8d5af9614a35d9004405d7b5587 | [
"Apache-2.0"
] | 4 | 2020-11-04T21:41:11.000Z | 2021-03-18T21:47:04.000Z | app/tests/unit/components/validators/validators.customValidators.spec.js | parc-jason/common-logging | 9c658fb4f326e8d5af9614a35d9004405d7b5587 | [
"Apache-2.0"
] | 4 | 2020-01-28T15:57:30.000Z | 2020-01-29T00:50:42.000Z | const helper = require('../../../common/helper');
const { customValidators } = require('../../../../src/components/validators');
helper.logHelper();
describe('customValidators.logging', () => {
const loggingEntryBase = {
level: 'info',
pattern: '%{GREEDYDATA:data}',
retention: 'default'
};
it('should return an error when input is undefined', () => {
const body = undefined;
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(body);
expect(result[0].message).toMatch('Invalid value `logging`. Expect an array of logging entries.');
});
it('should return an error when input is not array', () => {
const body = {};
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(body);
expect(result[0].message).toMatch('Invalid value `logging`. Expect an array of logging entries.');
});
it('should return an error when input is empty array', () => {
const body = [];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(body);
expect(result[0].message).toMatch('Invalid value `logging`. Array must not be empty.');
});
it('should return an error when data is invalid', () => {
const data = 4;
const body = [
Object.assign({}, loggingEntryBase, {
data: data
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(data);
expect(result[0].message).toMatch('Invalid value `data`.');
});
it('should return an error when level is invalid', () => {
const level = 4;
const body = [
Object.assign({}, loggingEntryBase, {
data: {},
level: level
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(level);
expect(result[0].message).toMatch('Invalid value `level`.');
});
it('should return an error when message is invalid', () => {
const message = 4;
const body = [
Object.assign({}, loggingEntryBase, {
message: message
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(message);
expect(result[0].message).toMatch('Invalid value `message`.');
});
it('should return an error when pattern is invalid', () => {
const pattern = 4;
const body = [
Object.assign({}, loggingEntryBase, {
data: {},
pattern: pattern
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(pattern);
expect(result[0].message).toMatch('Invalid value `pattern`.');
});
it('should return an error when retention is invalid', () => {
const retention = 4;
const body = [
Object.assign({}, loggingEntryBase, {
data: {},
retention: retention
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toEqual(retention);
expect(result[0].message).toMatch('Invalid value `retention`.');
});
it('should return an error when data and message is missing', () => {
const body = [loggingEntryBase];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toBeUndefined();
expect(result[0].message).toMatch('`message` or `data` is required.');
});
it('should return an error when data and message are both invalid', () => {
const data = 4;
const message = 5;
const body = [
Object.assign({}, loggingEntryBase, {
data: data,
message: message
})
];
const result = customValidators.logging(body);
const values = result.map(r => r.value);
const messages = result.map(r => r.message);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(3);
expect(values).toEqual(expect.arrayContaining([
data, message, undefined
]));
expect(messages).toEqual(expect.arrayContaining([
'Invalid value `data`.',
'Invalid value `message`.',
'`message` or `data` is required.'
]));
});
it('should return an error when both data and message are defined', () => {
const body = [
Object.assign({}, loggingEntryBase, {
data: {},
message: 'message'
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(1);
expect(result[0].value).toBeUndefined();
expect(result[0].message).toMatch('Only one of `message` or `data` should be defined.');
});
it('should return an empty error array when body is valid', () => {
const body = [
Object.assign({}, loggingEntryBase, {
data: {}
}),
Object.assign({}, loggingEntryBase, {
message: 'message'
})
];
const result = customValidators.logging(body);
expect(result).toBeTruthy();
expect(Array.isArray(result)).toBeTruthy();
expect(result).toHaveLength(0);
});
});
| 30.118812 | 102 | 0.629684 |
40d164f39b9c2e8f759f040ddc52014d35869d1f | 4,454 | py | Python | keras_textclassification/keras_layers/attention_dot.py | wyq0706/Keras-TextClassification | 595468120feacb9b3b037a57f80425b408685298 | [
"MIT"
] | 1 | 2020-06-22T09:49:44.000Z | 2020-06-22T09:49:44.000Z | keras_textclassification/keras_layers/attention_dot.py | wyq0706/Keras-TextClassification | 595468120feacb9b3b037a57f80425b408685298 | [
"MIT"
] | null | null | null | keras_textclassification/keras_layers/attention_dot.py | wyq0706/Keras-TextClassification | 595468120feacb9b3b037a57f80425b408685298 | [
"MIT"
] | null | null | null | # !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/3/31 19:10
# @author : Mo
# @function:
from keras.regularizers import L1L2, Regularizer
# from keras.engine.topology import Layer
from keras.layers import Layer
from keras import backend as K
import tensorflow as tf
class AttentionDot(Layer):
def __init__(self, **kwargs):
super().__init__(** kwargs)
def build(self, input_shape):
self.W = self.add_weight(name='Attention_Dot_Weight',
shape=(input_shape[1], input_shape[1]),
regularizer=L1L2(0.0000032),
initializer='uniform',
trainable=True)
self.b = self.add_weight(name='Attention_Dot_Bias',
regularizer=L1L2(0.00032),
shape=(input_shape[1],),
initializer='uniform',
trainable=True)
super().build(input_shape)
def call(self, input):
x_transpose = K.permute_dimensions(input, (0, 2, 1))
x_tanh_softmax = K.softmax(K.tanh(K.dot(x_transpose, self.W) + self.b))
outputs = K.permute_dimensions(x_tanh_softmax * x_transpose, (0, 2, 1))
# outputs = K.sum(outputs, axis=1)
return outputs
def compute_output_shape(self, input_shape):
return input_shape[0], input_shape[1], input_shape[2]
class CVG_Layer(Layer):
def __init__(self, embed_size, filter, label, **kwargs):
self.embed_size = embed_size
self.filter = filter
self.label = label
super().__init__(** kwargs)
def build(self, input_shape):
self._filter = self.add_weight(name=f'filter_{self.filter}',
shape=(self.filter, self.label, 1, 1),
regularizer=L1L2(0.00032),
initializer='uniform',
trainable=True)
self.class_w = self.add_weight(name='class_w',
shape=(self.label, self.embed_size),
regularizer=L1L2(0.0000032),
initializer='uniform',
trainable=True)
self.b = self.add_weight(name='bias',
shape=(1,),
regularizer=L1L2(0.00032),
initializer='uniform',
trainable=True)
super().build(input_shape)
def call(self, input):
# C * V / G
# l2_normalize of x, y
input_norm = tf.nn.l2_normalize(input) # b * s * e
class_w_relu = tf.nn.relu(self.class_w) # c * e
label_embedding_reshape = tf.transpose(class_w_relu, [1, 0]) # e * c
label_embedding_reshape_norm = tf.nn.l2_normalize(label_embedding_reshape) # e * c
# C * V
G = tf.contrib.keras.backend.dot(input_norm, label_embedding_reshape_norm) # b * s * c
G_transpose = tf.transpose(G, [0, 2, 1]) # b * c * s
G_expand = tf.expand_dims(G_transpose, axis=-1) # b * c * s * 1
# text_cnn
conv = tf.nn.conv2d(name='conv', input=G_expand, filter=self._filter,
strides=[1, 1, 1, 1], padding='SAME')
pool = tf.nn.relu(name='relu', features=tf.nn.bias_add(conv, self.b)) # b * c * s * 1
# pool = tf.nn.max_pool(name='pool', value=h, ksize=[1, int((self.filters[0]-1)/2), 1, 1],
# strides=[1, 1, 1, 1], padding='SAME')
# max_pool
pool_squeeze = tf.squeeze(pool, axis=-1) # b * c * s
pool_squeeze_transpose = tf.transpose(pool_squeeze, [0, 2, 1]) # b * s * c
G_max_squeeze = tf.reduce_max(input_tensor=pool_squeeze_transpose, axis=-1, keepdims=True) # b * s * 1
# divide of softmax
exp_logits = tf.exp(G_max_squeeze)
exp_logits_sum = tf.reduce_sum(exp_logits, axis=1, keepdims=True)
att_v_max = tf.div(exp_logits, exp_logits_sum)
# β * V
x_att = tf.multiply(input, att_v_max)
x_att_sum = tf.reduce_sum(x_att, axis=1)
return x_att_sum
def compute_output_shape(self, input_shape):
return None, K.int_shape(self.class_w)[1]
if __name__=="__main__":
att = AttentionDot()
| 42.419048 | 111 | 0.534351 |
9bd490a3b70c9fd61a357f6fbfb8171507945619 | 4,487 | js | JavaScript | app-web/src/pages/index.js | dkelsey/devhub-app-web | c1198c117e45d24b4013547d6e2471ef08c2eb4a | [
"Apache-2.0"
] | null | null | null | app-web/src/pages/index.js | dkelsey/devhub-app-web | c1198c117e45d24b4013547d6e2471ef08c2eb4a | [
"Apache-2.0"
] | null | null | null | app-web/src/pages/index.js | dkelsey/devhub-app-web | c1198c117e45d24b4013547d6e2471ef08c2eb4a | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import queryString from 'query-string';
import intersectionBy from 'lodash/intersectionBy';
import isNull from 'lodash/isNull';
import styled from '@emotion/styled';
import { Alert } from 'reactstrap';
import { MAIN_NAV_ROUTES } from '../constants/routes';
import { flattenGatsbyGraphQL } from '../utils/dataHelpers';
import { SEARCH } from '../messages';
import Layout from '../hoc/Layout';
import { ResourcePreview, Masthead, CollectionsContainer } from '../components/Home';
import withResourceQuery from '../hoc/withResourceQuery';
import Aux from '../hoc/auxillary';
import { useSearch } from '../utils/hooks';
import {
selectCollectionsWithResourcesGroupedByType,
selectResourcesGroupedByType,
} from '../utils/selectors';
import { isQueryEmpty } from '../utils/search';
import { SEARCH_QUERY_PARAM } from '../constants/search';
import { SPACING } from '../constants/designTokens';
const Main = styled.main`
margin-bottom: ${SPACING['1x']};
margin-top: ${SPACING['2x']};
padding: 0 ${SPACING['2x']};
`;
/**
* returns collection container component so aslong as a search is not being done
* @param {Array} collections list of collections
* @param {Boolean} searchResultsExist
*/
const getCollectionPreviews = (collections, searchResultsExist) => {
const collectionsSelector = selectCollectionsWithResourcesGroupedByType();
return (
!searchResultsExist && (
<CollectionsContainer
collections={collectionsSelector(collections)}
link={MAIN_NAV_ROUTES.COLLECTIONS}
/>
)
);
};
/**
* returns a resource preview components
* @param {Array} resources the list of siphon resources
* @param {Array} results the list of searched resources
*/
const getResourcePreviews = (resources, results = []) => {
const resourcesSelector = selectResourcesGroupedByType();
let resourcesToGroup = resources;
if (!isNull(results) && results.length > 0) {
// diff out resources by id
resourcesToGroup = intersectionBy(resources, results, 'id');
}
// select resources grouped by type using relesect memoization https://github.com/reduxjs/reselect/issues/30
const resourcesByType = resourcesSelector(resourcesToGroup);
const siphonResources = Object.keys(resourcesByType).map(resourceType => {
if (resourcesByType[resourceType].length > 0) {
return (
<ResourcePreview
key={resourceType}
title={resourceType}
resources={resourcesByType[resourceType]}
link={MAIN_NAV_ROUTES[resourceType]}
/>
);
}
return null;
});
return siphonResources;
};
export const TEST_IDS = {
alert: 'home-test-alert',
};
export const Index = ({
data: {
allDevhubCollection,
allDevhubSiphon,
siteSearchIndex: { index },
},
location,
}) => {
const queryParam = queryString.parse(location.search);
let query = [];
let results = [];
let windowHasQuery = Object.prototype.hasOwnProperty.call(queryParam, SEARCH_QUERY_PARAM);
if (windowHasQuery) {
query = decodeURIComponent(queryParam[SEARCH_QUERY_PARAM]);
} else {
query = '';
}
results = useSearch(query, index);
// this is defined by ?q='' or ?q=''&q=''..etc
// if query is empty we prevent the search results empty from being rendered
// in addition the collections container is prevented from not rendering because
// the query is present
const queryIsEmpty = isQueryEmpty(query);
let content = null;
const siphonResources = getResourcePreviews(flattenGatsbyGraphQL(allDevhubSiphon.edges), results);
const resourcesNotFound = !queryIsEmpty && (!results || (results.length === 0 && windowHasQuery));
if (queryIsEmpty) {
content = (
<Aux>
{getCollectionPreviews(
flattenGatsbyGraphQL(allDevhubCollection.edges),
windowHasQuery && !queryIsEmpty,
)}
</Aux>
);
} else if (resourcesNotFound) {
content = (
<Alert style={{ margin: '10px auto' }} color="info" data-testid={TEST_IDS.alert}>
{SEARCH.results.empty.defaultMessage}
</Alert>
);
} else {
content = (
<Aux>
{getCollectionPreviews(
flattenGatsbyGraphQL(allDevhubCollection.edges),
windowHasQuery && !queryIsEmpty,
)}
{siphonResources}
</Aux>
);
}
return (
<Layout showHamburger>
<Masthead query={query} />
<Main>{content}</Main>
</Layout>
);
};
export default withResourceQuery(Index)();
| 29.519737 | 110 | 0.680856 |
906c97ada7fe717c3af6eaf4e4cefedc965b6847 | 656 | py | Python | src/masonite/notification/drivers/MailDriver.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 35 | 2018-01-08T01:20:16.000Z | 2018-02-06T02:37:14.000Z | src/masonite/notification/drivers/MailDriver.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 55 | 2018-01-03T02:42:03.000Z | 2018-02-06T13:35:54.000Z | src/masonite/notification/drivers/MailDriver.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 4 | 2018-01-08T13:13:14.000Z | 2018-01-12T19:35:32.000Z | """Mail notification driver."""
from .BaseDriver import BaseDriver
class MailDriver(BaseDriver):
def __init__(self, application):
self.application = application
self.options = {}
def set_options(self, options):
self.options = options
return self
def send(self, notifiable, notification):
"""Used to send the email."""
mailable = self.get_data("mail", notifiable, notification)
if not mailable._to:
recipients = notifiable.route_notification_for("mail")
mailable = mailable.to(recipients)
return self.application.make("mail").mailable(mailable).send()
| 29.818182 | 70 | 0.653963 |
9c2f4741e474a70ec60444ee6a954c6823c658c7 | 1,237 | js | JavaScript | client/src/components/Posts/PostCard/LikesContent.js | FMI-Projects/jitter | e7edccb4552ff4739d1a90779ec7b04c39c63e4f | [
"Apache-2.0"
] | 1 | 2020-07-27T20:00:48.000Z | 2020-07-27T20:00:48.000Z | client/src/components/Posts/PostCard/LikesContent.js | FMI-Projects/jitter | e7edccb4552ff4739d1a90779ec7b04c39c63e4f | [
"Apache-2.0"
] | 11 | 2020-07-16T03:56:31.000Z | 2022-02-17T15:50:58.000Z | client/src/components/Posts/PostCard/LikesContent.js | FMI-Projects/jitter | e7edccb4552ff4739d1a90779ec7b04c39c63e4f | [
"Apache-2.0"
] | null | null | null | import React from "react";
import PropTypes from "prop-types";
import IconButton from "material-ui/IconButton";
import ThumbUpIcon from "@material-ui/icons/ThumbUp";
import ThumbDownIcon from "@material-ui/icons/ThumbDown";
import { withStyles } from "material-ui/styles";
import styles from "./LikesContent.styles";
const LikesContent = props => {
const {
handleLikeClick,
userReaction,
likesCount,
dislikesCount,
classes
} = props;
return (
<div className={classes.base}>
<IconButton onClick={e => handleLikeClick("Like")} aria-label="Like">
<ThumbUpIcon color={userReaction === "Like" ? "primary" : "inherit"} />
</IconButton>
{likesCount}
<IconButton onClick={e => handleLikeClick("Dislike")} aria-label="Like">
<ThumbDownIcon
color={userReaction === "Dislike" ? "secondary" : "inherit"}
/>
</IconButton>
{dislikesCount}
</div>
);
};
LikesContent.propTypes = {
handleLikeClick: PropTypes.func.isRequired,
likesCount: PropTypes.number.isRequired,
dislikesCount: PropTypes.number.isRequired,
userReaction: PropTypes.string,
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(LikesContent);
| 27.488889 | 79 | 0.683913 |
131095c467c6fc0e2e98e4444ff9bd6b07ba4392 | 469 | h | C | StatTag/View Controllers/WordDocProperty.h | StatTag/StatTagMac | 5b5b9affe86db01a759ad063055a6c7ebead6b8b | [
"MIT"
] | 2 | 2018-05-24T17:44:00.000Z | 2020-07-15T16:07:00.000Z | StatTag/View Controllers/WordDocProperty.h | StatTag/StatTagMac | 5b5b9affe86db01a759ad063055a6c7ebead6b8b | [
"MIT"
] | 41 | 2019-09-06T07:01:44.000Z | 2021-10-18T07:42:08.000Z | StatTag/View Controllers/WordDocProperty.h | StatTag/StatTagMac | 5b5b9affe86db01a759ad063055a6c7ebead6b8b | [
"MIT"
] | 1 | 2020-06-24T16:54:47.000Z | 2020-06-24T16:54:47.000Z | //
// WordDocProperty.h
// StatTag
//
// Created by Eric Whitley on 2/27/19.
// Copyright © 2019 StatTag. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface WordDocProperty : NSObject
@property NSString* propertyName;
@property NSString* propertyValue;
@property NSString* propertyType;
@property NSString* propertyData;
-(instancetype)init;
-(instancetype)initWithName:(NSString*)name andValue:(NSString*)value forType:(NSString*)type;
@end
| 21.318182 | 94 | 0.754797 |
ad8af7beceff3d29e8652e4031006a51307d19e2 | 1,376 | kt | Kotlin | android/app/src/main/java/com/algorand/android/ui/accounts/RenameAccountNameViewModel.kt | MikeOwino/algorand-wallet | fbf93582d06dd1c46d7114a1ee686bfecca4ec18 | [
"Apache-2.0"
] | 14 | 2022-02-20T12:14:39.000Z | 2022-03-28T11:05:19.000Z | android/app/src/main/java/com/algorand/android/ui/accounts/RenameAccountNameViewModel.kt | perawallet/pera-wallet | fbf93582d06dd1c46d7114a1ee686bfecca4ec18 | [
"Apache-2.0"
] | 10 | 2022-02-23T08:48:52.000Z | 2022-03-31T08:49:11.000Z | android/app/src/main/java/com/algorand/android/ui/accounts/RenameAccountNameViewModel.kt | perawallet/algorand-wallet | ecacd9f00dd49bce912e0961c50fe77d2d071dce | [
"Apache-2.0"
] | 3 | 2022-03-03T14:19:38.000Z | 2022-03-13T14:34:47.000Z | /*
* Copyright 2022 Pera Wallet, LDA
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
package com.algorand.android.ui.accounts
import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.algorand.android.core.AccountManager
class RenameAccountNameViewModel @ViewModelInject constructor(
private val accountManager: AccountManager,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
// TODO: 16.08.2021 Find the way to use safeArgs in viewModel.
private val publicKey by lazy { savedStateHandle.get<String>(PUBLIC_KEY) }
fun changeAccountName(accountName: String) {
accountManager.changeAccountName(publicKey, accountName)
}
companion object {
private const val PUBLIC_KEY = "publicKey"
}
}
| 36.210526 | 85 | 0.766715 |
51672df2e6ca991adfc235b7c53888caf436b38e | 9,759 | swift | Swift | Tests/CommandLineTests.swift | Lukasz2891/SwiftFormat | c313f469c5fe1038afde25034305bc123f26e59a | [
"MIT"
] | 1 | 2020-05-29T14:57:02.000Z | 2020-05-29T14:57:02.000Z | Tests/CommandLineTests.swift | Lukasz2891/SwiftFormat | c313f469c5fe1038afde25034305bc123f26e59a | [
"MIT"
] | null | null | null | Tests/CommandLineTests.swift | Lukasz2891/SwiftFormat | c313f469c5fe1038afde25034305bc123f26e59a | [
"MIT"
] | null | null | null | //
// CommandLineTests.swift
// SwiftFormat
//
// Created by Nick Lockwood on 10/01/2017.
// Copyright 2017 Nick Lockwood
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
@testable import SwiftFormat
import XCTest
private var readme: String = {
let directoryURL = URL(fileURLWithPath: #file).deletingLastPathComponent().deletingLastPathComponent()
let readmeURL = directoryURL.appendingPathComponent("README.md")
return try! String(contentsOf: readmeURL, encoding: .utf8)
}()
class CommandLineTests: XCTestCase {
// MARK: arg parser
func testParseSimpleArguments() {
let input = "hello world"
let output = ["", "hello", "world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedSpace() {
let input = "hello\\ world"
let output = ["", "hello world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedN() {
let input = "hello\\nworld"
let output = ["", "hellonworld"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseQuoteArguments() {
let input = "\"hello world\""
let output = ["", "hello world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedQuote() {
let input = "hello \\\"world\\\""
let output = ["", "hello", "\"world\""]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedQuoteInString() {
let input = "\"hello \\\"world\\\"\""
let output = ["", "hello \"world\""]
XCTAssertEqual(parseArguments(input), output)
}
func testParseQuotedEscapedN() {
let input = "\"hello\\nworld\""
let output = ["", "hello\\nworld"]
XCTAssertEqual(parseArguments(input), output)
}
// MARK: arg preprocessor
func testPreprocessArguments() {
let input = ["", "foo", "bar", "-o", "baz", "-i", "4", "-l", "cr", "-s", "inline"]
let output = ["0": "", "1": "foo", "2": "bar", "output": "baz", "indent": "4", "linebreaks": "cr", "semicolons": "inline"]
XCTAssertEqual(try preprocessArguments(input, [
"output",
"indent",
"linebreaks",
"semicolons",
]), output)
}
func testEmptyArgsAreRecognized() {
let input = ["", "--help", "--version"]
let output = ["0": "", "help": "", "version": ""]
XCTAssertEqual(try preprocessArguments(input, [
"help",
"version",
]), output)
}
// MARK: format options to arguments
func testCommandLineArgumentsHaveValidNames() {
let arguments = commandLineArguments(for: FormatOptions())
for key in arguments.keys {
XCTAssertTrue(commandLineArguments.contains(key), "\(key) is not a valid argument name")
}
}
func testCommandLineArgumentsAreCorrect() {
let options = FormatOptions()
let output = ["allman": "false", "wraparguments": "disabled", "wrapelements": "beforefirst", "self": "remove", "header": "ignore", "binarygrouping": "4,8", "octalgrouping": "4,8", "patternlet": "hoist", "indentcase": "false", "trimwhitespace": "always", "decimalgrouping": "3,6", "commas": "always", "semicolons": "inline", "indent": "4", "exponentcase": "lowercase", "operatorfunc": "spaced", "elseposition": "same-line", "empty": "void", "ranges": "spaced", "hexliteralcase": "uppercase", "linebreaks": "lf", "hexgrouping": "4,8", "comments": "indent", "ifdef": "indent", "stripunusedargs": "always"]
XCTAssertEqual(commandLineArguments(for: options), output)
}
// MARK: format arguments to options
func testFormatArgumentsAreAllImplemented() {
CLI.print = { _, _ in }
for key in formatArguments {
guard let value = commandLineArguments(for: FormatOptions())[key] else {
XCTAssert(deprecatedArguments.contains(key))
continue
}
XCTAssert(!deprecatedArguments.contains(key))
do {
_ = try formatOptionsFor([key: value])
} catch {
XCTFail("\(error)")
}
}
}
func testFileHeaderYearReplacement() {
do {
let options = try formatOptionsFor(["header": " Copyright 1981 - {year}"])
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let year = formatter.string(from: Date())
XCTAssertEqual(options.fileHeader, "//Copyright 1981 - \(year)")
} catch {
XCTFail("\(error)")
}
}
// MARK: pipe
func testPipe() {
CLI.print = { message, _ in
XCTAssertEqual(message, "func foo() {\n bar()\n}\n")
}
var readCount = 0
CLI.readLine = {
readCount += 1
switch readCount {
case 1:
return "func foo()\n"
case 2:
return "{\n"
case 3:
return "bar()\n"
case 4:
return "}"
default:
return nil
}
}
processArguments([""], in: "")
}
// MARK: input paths
func testExpandPathWithRelativePath() {
XCTAssertEqual(
expandPath("relpath/to/file.swift", in: "/dir").path,
"/dir/relpath/to/file.swift"
)
}
func testExpandPathWithFullPath() {
XCTAssertEqual(
expandPath("/full/path/to/file.swift", in: "/dir").path,
"/full/path/to/file.swift"
)
}
func testExpandPathWithUserPath() {
XCTAssertEqual(
expandPath("~/file.swift", in: "/dir").path,
NSString(string: "~/file.swift").expandingTildeInPath
)
}
// MARK: help
func testHelpLineLength() {
CLI.print = { message, _ in
XCTAssertLessThanOrEqual(message.count, 80, message)
}
printHelp()
}
func testHelpOptionsImplemented() {
CLI.print = { message, _ in
if message.hasPrefix("--") {
let name = String(message["--".endIndex ..< message.endIndex]).components(separatedBy: " ")[0]
XCTAssertTrue(commandLineArguments.contains(name), name)
}
}
printHelp()
}
func testHelpOptionsDocumented() {
var arguments = Set(commandLineArguments)
deprecatedArguments.forEach { arguments.remove($0) }
CLI.print = { message, _ in
if message.hasPrefix("--") {
let name = String(message["--".endIndex ..< message.endIndex]).components(separatedBy: " ")[0]
arguments.remove(name)
}
}
printHelp()
XCTAssert(arguments.isEmpty, "\(arguments.joined(separator: ","))")
}
// MARK: documentation
func testAllRulesInReadme() {
for ruleName in FormatRules.byName.keys {
XCTAssertTrue(readme.contains("***\(ruleName)*** - "), ruleName)
}
}
func testNoInvalidRulesInReadme() {
let ruleNames = Set(FormatRules.byName.keys)
var range = readme.startIndex ..< readme.endIndex
while let match = readme.range(of: "\\*[a-zA-Z]+\\* - ", options: .regularExpression, range: range, locale: nil) {
let lower = readme.index(after: match.lowerBound)
let upper = readme.index(match.upperBound, offsetBy: -4)
let ruleName: String = String(readme[lower ..< upper])
XCTAssertTrue(ruleNames.contains(ruleName), ruleName)
range = match.upperBound ..< range.upperBound
}
}
func testAllOptionsInReadme() {
var arguments = Set(formatArguments)
deprecatedArguments.forEach { arguments.remove($0) }
for argument in arguments {
XCTAssertTrue(readme.contains("`--\(argument)`"), argument)
}
}
func testNoInvalidOptionsInReadme() {
let arguments = Set(commandLineArguments)
var range = readme.startIndex ..< readme.endIndex
while let match = readme.range(of: "`--[a-zA-Z]+`", options: .regularExpression, range: range, locale: nil) {
let lower = readme.index(match.lowerBound, offsetBy: 3)
let upper = readme.index(before: match.upperBound)
let argument: String = String(readme[lower ..< upper])
XCTAssertTrue(arguments.contains(argument), argument)
range = match.upperBound ..< range.upperBound
}
}
}
| 35.616788 | 610 | 0.591557 |
50dfcd57aa927f9e5916c9c2334fa6c692107c7b | 1,430 | go | Go | pkg/ratelimit/concurrency_limiter.go | srstack/pd | 7baf94c8644ccd55930d213e298fc0104bc7a453 | [
"Apache-2.0"
] | null | null | null | pkg/ratelimit/concurrency_limiter.go | srstack/pd | 7baf94c8644ccd55930d213e298fc0104bc7a453 | [
"Apache-2.0"
] | null | null | null | pkg/ratelimit/concurrency_limiter.go | srstack/pd | 7baf94c8644ccd55930d213e298fc0104bc7a453 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 TiKV Project Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ratelimit
import (
"sync"
)
type concurrencyLimiter struct {
mu sync.RWMutex
current uint64
limit uint64
}
func newConcurrencyLimiter(limit uint64) *concurrencyLimiter {
return &concurrencyLimiter{limit: limit}
}
func (l *concurrencyLimiter) allow() bool {
l.mu.Lock()
defer l.mu.Unlock()
if l.current+1 <= l.limit {
l.current++
return true
}
return false
}
func (l *concurrencyLimiter) release() {
l.mu.Lock()
defer l.mu.Unlock()
if l.current > 0 {
l.current--
}
}
func (l *concurrencyLimiter) getLimit() uint64 {
l.mu.RLock()
defer l.mu.RUnlock()
return l.limit
}
func (l *concurrencyLimiter) setLimit(limit uint64) {
l.mu.Lock()
defer l.mu.Unlock()
l.limit = limit
}
func (l *concurrencyLimiter) getCurrent() uint64 {
l.mu.RLock()
defer l.mu.RUnlock()
return l.current
}
| 20.140845 | 75 | 0.711189 |
9da6a1c93b523f64bb4c1bd3d2619605fb6f1672 | 1,063 | kt | Kotlin | src/test/kotlin/com/github/mpe85/grampa/grammar/RegexRuleTests.kt | mpe85/grampa | a0470653f276f68462999813447777d0f8faa4b1 | [
"MIT"
] | null | null | null | src/test/kotlin/com/github/mpe85/grampa/grammar/RegexRuleTests.kt | mpe85/grampa | a0470653f276f68462999813447777d0f8faa4b1 | [
"MIT"
] | null | null | null | src/test/kotlin/com/github/mpe85/grampa/grammar/RegexRuleTests.kt | mpe85/grampa | a0470653f276f68462999813447777d0f8faa4b1 | [
"MIT"
] | null | null | null | package com.github.mpe85.grampa.grammar
import com.github.mpe85.grampa.parser.Parser
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.stringPattern
import io.kotest.property.checkAll
class RegexRuleTests : StringSpec({
val patterns = listOf(
"[A-Z]{5,9}",
"[0-3]([a-c]|[e-g]{1,2})",
"([a-z0-9]+)[@]([a-z0-9]+)[.]([a-z0-9]+)",
"(\\d+)",
"(\\D+)",
"(\\w+)",
"(\\W+)"
)
"Regex rule matches correct pattern" {
patterns.forEach { pattern ->
checkAll(Arb.stringPattern(pattern)) { str ->
Parser(object : AbstractGrammar<Unit>() {
override fun start() = pattern.toRegexRule()
}).run(str).apply {
matched shouldBe true
matchedEntireInput shouldBe true
matchedInput shouldBe str
restOfInput shouldBe ""
}
}
}
}
})
| 30.371429 | 64 | 0.531515 |
7497b4cef2ff08e74bc4459556dc0c3dfb614ff2 | 6,605 | c | C | vmdir/testing/integration_tests/ppolicy/recycle.c | debojyoti-majumder/lightwave | 1ff3beaafb7351140b9372e3a46b2a288f53832e | [
"Apache-2.0"
] | 357 | 2015-04-20T00:16:30.000Z | 2022-03-17T05:34:09.000Z | vmdir/testing/integration_tests/ppolicy/recycle.c | tdeleeuw/lightwave | baae9b03ddeeb6299ab891f9c1e2957b86d37cc5 | [
"Apache-2.0"
] | 38 | 2015-11-19T05:20:53.000Z | 2022-03-31T07:21:59.000Z | vmdir/testing/integration_tests/ppolicy/recycle.c | tdeleeuw/lightwave | baae9b03ddeeb6299ab891f9c1e2957b86d37cc5 | [
"Apache-2.0"
] | 135 | 2015-04-21T15:23:21.000Z | 2022-03-30T11:46:36.000Z | /*
* Copyright © 2097 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
DWORD
InitializeRecycleSetup(
PVMDIR_PPOLICY_TEST_CONTEXT pPolicyContext
)
{
DWORD dwError = 0;
PSTR ppszAttrValue[] = { NULL, NULL };
struct _RecycleParam
{
PSTR pszAttrName;
PSTR pszValue;
}
RecycleParam[] =
{
{ ATTR_PASS_RECYCLE_CNT, "3" },
};
ppszAttrValue[0] = RecycleParam[0].pszValue;
dwError = VmDirTestReplaceAttributeValues(
pPolicyContext->pTestState->pLd,
pPolicyContext->pszPolicyDN,
RecycleParam[0].pszAttrName,
(PCSTR*)ppszAttrValue);
BAIL_ON_VMDIR_ERROR(dwError);
error:
return dwError;
}
DWORD
TestAdminRecycle(
PVMDIR_PPOLICY_TEST_CONTEXT pPolicyContext
)
{
DWORD dwError = 0;
DWORD dwCnt = 0;
PVMDIR_TEST_STATE pState = pPolicyContext->pTestState;
VMDIR_PP_CTRL_MODIFY ctrlModify = {0};
struct _RecycleRec
{
PSTR pszPwd;
DWORD dwResult;
DWORD dwPPolicyError;
}
RecycleRec[] =
{
{ "Recycle-0-1", 0 , 0},
{ "Recycle-0-2", 0 , 0},
{ "Recycle-0-3", 0 , 0},
{ "Recycle-0-3", 0 , 0}, // admin NOT subject to recycle rule
{ "Recycle-0-2", 0 , 0}, // regardless who's password it modify
{ "Recycle-0-1", 0 , 0},
};
for (dwCnt=0; dwCnt < sizeof(RecycleRec)/sizeof(RecycleRec[0]); dwCnt++)
{
memset(&ctrlModify, 0, sizeof(ctrlModify));
ctrlModify.pszTargetDN = pPolicyContext->pszTestUserDN;
ctrlModify.pszPassword = RecycleRec[dwCnt].pszPwd;
dwError = TestModifyPassword(
pPolicyContext->pTestState->pLd, // admin user modify normal user pwd
&ctrlModify);
BAIL_ON_VMDIR_ERROR(dwError);
TestAssertEquals(ctrlModify.ctrlResult.dwOpResult, RecycleRec[dwCnt].dwResult);
if (RecycleRec[dwCnt].dwPPolicyError != 0)
{
TestAssertEquals(ctrlModify.ctrlResult.bHasPPCtrlResponse, 1);
TestAssertEquals(ctrlModify.ctrlResult.PPolicyState.PPolicyError, RecycleRec[dwCnt].dwPPolicyError);
}
memset(&ctrlModify, 0, sizeof(ctrlModify));
ctrlModify.pszTargetDN = pPolicyContext->pTestState->pszUserDN;
ctrlModify.pszPassword = RecycleRec[dwCnt].pszPwd;
dwError = TestModifyPassword(
pPolicyContext->pTestState->pLd, // admin user modify admin user pwd
&ctrlModify);
BAIL_ON_VMDIR_ERROR(dwError);
TestAssertEquals(ctrlModify.ctrlResult.dwOpResult, RecycleRec[dwCnt].dwResult);
if (RecycleRec[dwCnt].dwPPolicyError != 0)
{
TestAssertEquals(ctrlModify.ctrlResult.bHasPPCtrlResponse, 1);
TestAssertEquals(ctrlModify.ctrlResult.PPolicyState.PPolicyError, RecycleRec[dwCnt].dwPPolicyError);
}
}
error:
return dwError;
}
DWORD
TestUserRecycle(
PVMDIR_PPOLICY_TEST_CONTEXT pPolicyContext
)
{
DWORD dwError = 0;
DWORD dwCnt = 0;
PVMDIR_TEST_STATE pState = pPolicyContext->pTestState;
VMDIR_PP_CTRL_MODIFY ctrlModify = {0};
struct _RecycleRec
{
PSTR pszPwd;
DWORD dwResult;
DWORD dwPPolicyError;
}
RecycleRec[] =
{
{ "Recycle-1-1", 0 , 0},
{ "Recycle-1-2", 0 , 0},
{ "Recycle-1-3", 0 , 0},
{ "Recycle-1-1", 19, 8}, // user recycle should fail
{ "Recycle-1-4", 0 , 0},
{ "Recycle-1-1", 0 , 0}, // recycle ok, pass count 3.
};
for (dwCnt=0; dwCnt < sizeof(RecycleRec)/sizeof(RecycleRec[0]); dwCnt++)
{
memset(&ctrlModify, 0, sizeof(ctrlModify));
ctrlModify.pszTargetDN = pPolicyContext->pszTestUserDN;
ctrlModify.pszPassword = RecycleRec[dwCnt].pszPwd;
dwError = TestModifyPassword(
pPolicyContext->pLdUser, // normal user modify self pwd
&ctrlModify);
BAIL_ON_VMDIR_ERROR(dwError);
TestAssertEquals(ctrlModify.ctrlResult.dwOpResult, RecycleRec[dwCnt].dwResult);
if (RecycleRec[dwCnt].dwPPolicyError != 0)
{
TestAssertEquals(ctrlModify.ctrlResult.bHasPPCtrlResponse, 1);
TestAssertEquals(ctrlModify.ctrlResult.PPolicyState.PPolicyError, RecycleRec[dwCnt].dwPPolicyError);
}
}
error:
return dwError;
}
/*
* restore original password
* restore recycle count to 0
*/
DWORD
CleanRecycleSetup(
PVMDIR_PPOLICY_TEST_CONTEXT pPolicyContext
)
{
DWORD dwError = 0;
PSTR ppszAttrValue[] = { NULL, NULL };
ppszAttrValue[0] = (PSTR)pPolicyContext->pTestState->pszPassword;
dwError = VmDirTestReplaceAttributeValues(
pPolicyContext->pTestState->pLd,
pPolicyContext->pTestState->pszUserDN,
ATTR_USER_PASSWORD,
(PCSTR*)ppszAttrValue);
BAIL_ON_VMDIR_ERROR(dwError);
ppszAttrValue[0] = (PSTR)pPolicyContext->pszTestUserPassword;
dwError = VmDirTestReplaceAttributeValues(
pPolicyContext->pTestState->pLd,
pPolicyContext->pszTestUserDN,
ATTR_USER_PASSWORD,
(PCSTR*)ppszAttrValue);
BAIL_ON_VMDIR_ERROR(dwError);
ppszAttrValue[0] = "0";
dwError = VmDirTestReplaceAttributeValues(
pPolicyContext->pTestState->pLd,
pPolicyContext->pszPolicyDN,
ATTR_PASS_RECYCLE_CNT,
(PCSTR*)ppszAttrValue);
BAIL_ON_VMDIR_ERROR(dwError);
error:
return dwError;
}
DWORD
TestRecycle(
PVMDIR_PPOLICY_TEST_CONTEXT pPolicyContext
)
{
DWORD dwError = 0;
dwError = InitializeRecycleSetup(pPolicyContext);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = TestAdminRecycle(pPolicyContext);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = TestUserRecycle(pPolicyContext);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = CleanRecycleSetup(pPolicyContext);
BAIL_ON_VMDIR_ERROR(dwError);
cleanup:
printf("%s %s (%d)\n", __FUNCTION__, dwError ? "failed" : "succeeded", dwError);
return dwError;
error:
goto cleanup;
}
| 28.842795 | 112 | 0.653596 |
e51cdbe4923a82da86916865c4458789cc8c8f69 | 811 | ts | TypeScript | src/messages/entities/message.entity.ts | droa3v/chat-app-server | 541f1d638939fea8ee0d4c313e22477fcc76cb28 | [
"MIT"
] | null | null | null | src/messages/entities/message.entity.ts | droa3v/chat-app-server | 541f1d638939fea8ee0d4c313e22477fcc76cb28 | [
"MIT"
] | null | null | null | src/messages/entities/message.entity.ts | droa3v/chat-app-server | 541f1d638939fea8ee0d4c313e22477fcc76cb28 | [
"MIT"
] | null | null | null | import { ObjectType, Field } from "@nestjs/graphql";
import { User } from "src/users/entities/user.entity";
import { Room } from "src/rooms/entities/room.entity";
import {
Column,
Entity,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
@Entity({ name: "Messages" })
@ObjectType()
export class Message {
@PrimaryGeneratedColumn("uuid")
@Field()
id: string;
@Column()
@Field()
body: string;
@ManyToOne(() => User)
@Field(() => User)
creator: User;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@ManyToOne(() => User, { nullable: true })
@Field(() => User, { nullable: true })
recipient?: User;
@ManyToOne(() => Room, { nullable: true })
@Field(() => Room, { nullable: true })
room?: Room;
}
| 22.527778 | 54 | 0.64365 |
d718ebc5a82c3e5e56a598b96f8020c0a0f5e7e7 | 182 | sql | SQL | application/logs/sql/uninstall.sql | sssasdsadasdad/jyerp_plus | d778b568f662d1eba3b300629d815791d3f4757e | [
"FSFAP"
] | null | null | null | application/logs/sql/uninstall.sql | sssasdsadasdad/jyerp_plus | d778b568f662d1eba3b300629d815791d3f4757e | [
"FSFAP"
] | null | null | null | application/logs/sql/uninstall.sql | sssasdsadasdad/jyerp_plus | d778b568f662d1eba3b300629d815791d3f4757e | [
"FSFAP"
] | null | null | null | -- -----------------------------
-- 导出时间 `2018-06-06 18:15:44`
-- -----------------------------
DROP TABLE IF EXISTS `dp_personnel_daily`;
DROP TABLE IF EXISTS `dp_personnel_plan`;
| 26 | 42 | 0.478022 |
0655b47371284743c539019e55a76994691f61a0 | 4,305 | rs | Rust | src/sentences/utils.rs | scOwez/nmea | 03bc65e6f524923022bf1b757b7aff18ed432d5b | [
"Apache-2.0"
] | null | null | null | src/sentences/utils.rs | scOwez/nmea | 03bc65e6f524923022bf1b757b7aff18ed432d5b | [
"Apache-2.0"
] | null | null | null | src/sentences/utils.rs | scOwez/nmea | 03bc65e6f524923022bf1b757b7aff18ed432d5b | [
"Apache-2.0"
] | null | null | null | use std::str;
use chrono::{NaiveDate, NaiveTime};
use nom::branch::alt;
use nom::bytes::complete::{tag, take, take_until};
use nom::character::complete::{char, digit1, one_of};
use nom::combinator::{map, map_parser, map_res};
use nom::number::complete::double;
use nom::sequence::tuple;
use nom::IResult;
pub(crate) fn parse_hms(i: &[u8]) -> IResult<&[u8], NaiveTime> {
map_res(
tuple((
map_res(take(2usize), parse_num::<u32>),
map_res(take(2usize), parse_num::<u32>),
map_parser(take_until(","), double),
)),
|(hour, minutes, sec)| -> std::result::Result<NaiveTime, &'static str> {
if sec.is_sign_negative() {
return Err("Invalid time: second is negative");
}
if hour >= 24 {
return Err("Invalid time: hour >= 24");
}
if minutes >= 60 {
return Err("Invalid time: min >= 60");
}
if sec >= 60. {
return Err("Invalid time: sec >= 60");
}
Ok(NaiveTime::from_hms_nano(
hour,
minutes,
sec.trunc() as u32,
(sec.fract() * 1_000_000_000f64).round() as u32,
))
},
)(i)
}
pub fn do_parse_lat_lon(i: &[u8]) -> IResult<&[u8], (f64, f64)> {
let (i, lat_deg) = map_res(take(2usize), parse_num::<u8>)(i)?;
let (i, lat_min) = double(i)?;
let (i, _) = char(',')(i)?;
let (i, lat_dir) = one_of("NS")(i)?;
let (i, _) = char(',')(i)?;
let (i, lon_deg) = map_res(take(3usize), parse_num::<u8>)(i)?;
let (i, lon_min) = double(i)?;
let (i, _) = char(',')(i)?;
let (i, lon_dir) = one_of("EW")(i)?;
let mut lat = f64::from(lat_deg) + lat_min / 60.;
if lat_dir == 'S' {
lat = -lat;
}
let mut lon = f64::from(lon_deg) + lon_min / 60.;
if lon_dir == 'W' {
lon = -lon;
}
Ok((i, (lat, lon)))
}
pub(crate) fn parse_lat_lon(i: &[u8]) -> IResult<&[u8], Option<(f64, f64)>> {
alt((map(tag(",,,"), |_| None), map(do_parse_lat_lon, Some)))(i)
}
pub(crate) fn parse_date(i: &[u8]) -> IResult<&[u8], NaiveDate> {
map_res(
tuple((
map_res(take(2usize), parse_num::<u8>),
map_res(take(2usize), parse_num::<u8>),
map_res(take(2usize), parse_num::<u8>),
)),
|data| -> Result<NaiveDate, &'static str> {
let (day, month, year) = (u32::from(data.0), u32::from(data.1), i32::from(data.2));
if month < 1 || month > 12 {
return Err("Invalid month < 1 or > 12");
}
if day < 1 || day > 31 {
return Err("Invalid day < 1 or > 31");
}
Ok(NaiveDate::from_ymd(year, month, day))
},
)(i)
}
pub(crate) fn parse_num<I: std::str::FromStr>(data: &[u8]) -> std::result::Result<I, &'static str> {
// println!("parse num {}", unsafe { str::from_utf8_unchecked(data) });
str::parse::<I>(unsafe { str::from_utf8_unchecked(data) }).map_err(|_| "parse of number failed")
}
pub(crate) fn parse_float_num<T: str::FromStr>(
input: &[u8],
) -> std::result::Result<T, &'static str> {
let s = str::from_utf8(input).map_err(|_| "invalid float number")?;
str::parse::<T>(s).map_err(|_| "parse of float number failed")
}
pub(crate) fn number<T: std::str::FromStr>(i: &[u8]) -> IResult<&[u8], T> {
map_res(digit1, parse_num)(i)
}
#[cfg(test)]
mod tests {
use super::*;
use approx::relative_eq;
#[test]
fn test_do_parse_lat_lon() {
let (_, lat_lon) = do_parse_lat_lon(b"4807.038,N,01131.324,E").unwrap();
relative_eq!(lat_lon.0, 48. + 7.038 / 60.);
relative_eq!(lat_lon.1, 11. + 31.324 / 60.);
}
#[test]
fn test_parse_hms() {
use chrono::Timelike;
let (_, time) = parse_hms(b"125619,").unwrap();
assert_eq!(time.hour(), 12);
assert_eq!(time.minute(), 56);
assert_eq!(time.second(), 19);
assert_eq!(time.nanosecond(), 0);
let (_, time) = parse_hms(b"125619.5,").unwrap();
assert_eq!(time.hour(), 12);
assert_eq!(time.minute(), 56);
assert_eq!(time.second(), 19);
assert_eq!(time.nanosecond(), 5_00_000_000);
}
}
| 32.613636 | 100 | 0.520557 |
b1ef2174eb416ec1f9250c2bfab1cf94afec3b46 | 41 | sql | SQL | app/server/appsmith-plugins/postgresPlugin/src/main/resources/templates/SELECT.sql | erezrokah/appsmith | c858edf7260de1811b35d4459e199fe15d18092e | [
"Apache-2.0"
] | 13,566 | 2020-07-09T16:14:45.000Z | 2022-03-31T23:53:08.000Z | app/server/appsmith-plugins/postgresPlugin/src/main/resources/templates/SELECT.sql | erezrokah/appsmith | c858edf7260de1811b35d4459e199fe15d18092e | [
"Apache-2.0"
] | 9,694 | 2020-07-10T05:24:09.000Z | 2022-03-31T22:34:42.000Z | app/server/appsmith-plugins/postgresPlugin/src/main/resources/templates/SELECT.sql | erezrokah/appsmith | c858edf7260de1811b35d4459e199fe15d18092e | [
"Apache-2.0"
] | 1,250 | 2020-07-10T05:33:31.000Z | 2022-03-31T16:27:14.000Z | SELECT * FROM users ORDER BY id LIMIT 10; | 41 | 41 | 0.756098 |
96393085715d000003e63dc8aea27af36aeb5f21 | 6,359 | php | PHP | Extensions/Upgrade/UpEntity.php | glushkovds/simplex-cms | 63e50892cbabe3d148baa39cbe759f09f607fc92 | [
"MIT"
] | null | null | null | Extensions/Upgrade/UpEntity.php | glushkovds/simplex-cms | 63e50892cbabe3d148baa39cbe759f09f607fc92 | [
"MIT"
] | null | null | null | Extensions/Upgrade/UpEntity.php | glushkovds/simplex-cms | 63e50892cbabe3d148baa39cbe759f09f607fc92 | [
"MIT"
] | null | null | null | <?php
namespace App\Extensions\Upgrade;
use App\Core\Console\Alert;
abstract class UpEntity extends UpFile
{
protected static $name = '';
public function upgrade()
{
if ($delegated = $this->upgradeDelegate()) {
return $delegated;
}
$this->upgradeInner();
$this->save();
return true;
// print_r($this->data);
// print_r($this->newData);
// die;
}
protected function upgradeDelegate()
{
}
protected function upgradeInner()
{
$this->upgradeNamespace();
$this->upgradeAnnotations();
$this->replaceClasses();
// print_r($this->data);
// print_r($this->newData);
// die;
}
protected function upgradeAnnotations()
{
$this->newData['annotations'] = str_replace(
[
'@author Evgeny Shilov <evgeny@internet-menu.ru>',
'@version 1.0',
],
'',
$this->newData['annotations']
);
$this->newData['annotations'] = preg_replace('@(\s?\*[\r\n\s]+)+\*\/@s', "\n*/", $this->newData['annotations']);
}
protected function upgradeNamespace()
{
$p = $this->getPlace();
$relPath = dirname(str_replace("{$this->config->fromRoot}/{$p['oldBase']}", '', $this->path));
$relPathParts = array_filter(explode('/', $relPath));
$ns = array_merge(['App', $p['newBase']], array_map('ucfirst', $relPathParts));
$this->newData['namespace'] = implode('\\', $ns);
}
protected function extNamespace()
{
['newPlace' => $extensionName] = $this->getPlace();
return "App\Extensions\\$extensionName";
}
protected function simplifyFqn($class)
{
$fqnParts = array_filter(explode('\\', $class));
if (count($fqnParts) > 1) {
$newFull = $class;
$class = end($fqnParts);
$this->newData['use'][$newFull] = $newFull;
}
return $class;
}
public function save()
{
$contents = '<?php' . "\n\n";
$contents .= "namespace {$this->newData['namespace']};\n\n";
$contents .= $this->useToStr() . "\n\n";
$contents .= $this->newData['annotations'] ? $this->newData['annotations'] . "\n" : '';
$contents .= $this->putEntity();
if ($this->newData['extends']) {
$contents .= " extends {$this->newData['extends']}";
}
if ($this->newData['implements']) {
$contents .= " implements {$this->newData['implements']}";
}
$contents .= "\n{\n";
$contents .= $this->newData['classContents'] . "\n}\n";
$this->newData['contents'] = $contents;
$newPath = $this->findNewPath();
if (!is_dir(dirname($newPath))) {
mkdir(dirname($newPath), 0777, true);
}
file_put_contents($newPath, $contents);
}
protected function putEntity()
{
return static::$name . " {$this->newData[static::$name]}";
}
protected function findNewName()
{
return $this->newData[static::$name] . '.php';
}
protected function useToStr()
{
$str = [];
foreach ($this->newData['use'] as $use) {
$str[] = "use $use;";
}
return implode("\n", $str);
}
protected static function parse($path)
{
$contents = file_get_contents($path);
$matches = [];
preg_match('@' . static::$name . ' ([\w\d_]+)@', $contents, $matches);
$class = $matches[1] ?? null;
if (empty($class)) {
throw new SkipFileException('Has no class');
}
preg_match('@extends ([\w\d_]+)@', $contents, $matches);
$extends = $matches[1] ?? null;
preg_match('@implements ([\w\d_\s\,]+)@', $contents, $matches);
$implements = trim($matches[1] ?? '') ?: null;
preg_match('@namespace ([\w\d_\\\]+)@', $contents, $matches);
$namespace = $matches[1] ?? null;
preg_match('@(\/\*\*.+\*\/)[\n\r\s]+' . static::$name . '@Uis', $contents, $matches);
$annotations = $matches[1] ?? null;
preg_match('@' . static::$name . ' [^\{]+\{(.*)\}@smi', $contents, $matches);
$classContents = $matches[1] ?? null;
if (empty($classContents)) {
throw new \Exception("Cant detect class contents $path");
}
$result = [
'contents' => $contents,
'entityType' => static::$name,
'entity' => $class,
static::$name => $class,
'extends' => $extends,
'implements' => $implements,
'namespace' => $namespace,
'use' => [],
'annotations' => $annotations,
'classContents' => $classContents,
];
return $result;
}
public function getFqn()
{
return implode('\\', array_filter([$this->newData['namespace'], $this->newData['entity']]));
}
protected function replacePart($partName)
{
$this->replace($this->data[$partName], $this->newData[$partName]);
}
public function replace($search, $replace)
{
$this->newData['classContents'] = str_replace($search, $replace, $this->newData['classContents']);
}
protected function replaceClasses()
{
foreach ($this->knownClasses as $from => $to) {
if (strpos($this->newData['classContents'], $from)) {
$this->replace($from, $this->simplifyFqn($to));
}
}
$classes = static::findClassesInContent($this->newData['classContents']);
foreach ($classes as $class) {
$newClass = UpClass::upgradeClassName($class);
if ($newClass) {
['namespace' => $ns, 'class' => $cn] = UpClass::classNameInfo($newClass);
$this->newData['use'][$newClass] = $newClass;
$this->replace($class, $cn);
}
}
}
protected static function splitCamelCase($input)
{
return preg_split(
'/(^[^A-Z]+|[A-Z][^A-Z]+)/',
$input,
-1, /* no limit for replacement count */
PREG_SPLIT_NO_EMPTY /*don't return empty elements*/
| PREG_SPLIT_DELIM_CAPTURE /*don't strip anything from output array*/
);
}
} | 30.719807 | 120 | 0.511716 |
4546e1165aad78f4ff8b308d530a1c521ca520a1 | 591 | rs | Rust | src/q2011.rs | JoverZhang/leetcode.rust | edac5248db5df77c6d4954d69cbd4635965fbebb | [
"MIT"
] | null | null | null | src/q2011.rs | JoverZhang/leetcode.rust | edac5248db5df77c6d4954d69cbd4635965fbebb | [
"MIT"
] | null | null | null | src/q2011.rs | JoverZhang/leetcode.rust | edac5248db5df77c6d4954d69cbd4635965fbebb | [
"MIT"
] | null | null | null | pub struct Solution {}
impl Solution {
pub fn final_value_after_operations(operations: Vec<String>) -> i32 {
let mut rst = 0;
for oper in operations {
if oper.starts_with("-") || oper.ends_with("-") {
rst -= 1;
} else if oper.starts_with("+") || oper.ends_with("+") {
rst += 1;
};
}
return rst;
}
}
#[test]
fn test() {
println!("{}", Solution::final_value_after_operations(vec![
String::from("--X"),
String::from("X++"),
String::from("X++"),
]));
}
| 23.64 | 73 | 0.478849 |
df81c06203c341133851d5e6860e3e3ee8cbc320 | 800 | tsx | TypeScript | www-resource/src/App.tsx | xiaoyaozi1010/image-min | d52d1e58fbec9e2168b90967df53d34ebbce2f2b | [
"MIT"
] | null | null | null | www-resource/src/App.tsx | xiaoyaozi1010/image-min | d52d1e58fbec9e2168b90967df53d34ebbce2f2b | [
"MIT"
] | null | null | null | www-resource/src/App.tsx | xiaoyaozi1010/image-min | d52d1e58fbec9e2168b90967df53d34ebbce2f2b | [
"MIT"
] | null | null | null | import * as React from 'react';
import './App.css';
import Title from './Components/Title/Title';
import UploadComponent from './Components/Upload/UploadComponent';
import { Row, Col } from 'antd';
class App extends React.Component {
state = {
title: '',
subTitle: ''
};
constructor(props: string) {
super(props);
this.state = {
title: 'image-min',
subTitle: 'A smaller image compression for designer.'
};
}
render() {
return (
<div className="main">
<Row align="middle">
<Col>
<Title title={this.state.title} subTitle={this.state.subTitle} />
</Col>
</Row>
<Row>
<Col>
<UploadComponent />
</Col>
</Row>
</div>
);
}
}
export default App;
| 21.052632 | 77 | 0.54375 |
21e85c9d03b22139a93509be44f5039a7100ecd0 | 141 | sql | SQL | MySQL/02_IN_LIMIT_Scripts.sql | ajsamant/SampleCodeAjinkya | f7515ca879efd01c67047d2527819a1366861e94 | [
"MIT"
] | null | null | null | MySQL/02_IN_LIMIT_Scripts.sql | ajsamant/SampleCodeAjinkya | f7515ca879efd01c67047d2527819a1366861e94 | [
"MIT"
] | null | null | null | MySQL/02_IN_LIMIT_Scripts.sql | ajsamant/SampleCodeAjinkya | f7515ca879efd01c67047d2527819a1366861e94 | [
"MIT"
] | null | null | null | SELECT
title, release_year, rental_duration
FROM
film
WHERE
rental_duration IN (3 , 5)
LIMIT 7;
SELECT title FROM film LIMIT 7; | 15.666667 | 40 | 0.716312 |
16975e3afaffc48237651a60d01015f90fd5d028 | 1,828 | ts | TypeScript | src/lib/api/router/routes/games.ts | Fyrlex/bs | d91678a850689d0431a0dc59f5d35ffba2c42b57 | [
"MIT"
] | null | null | null | src/lib/api/router/routes/games.ts | Fyrlex/bs | d91678a850689d0431a0dc59f5d35ffba2c42b57 | [
"MIT"
] | null | null | null | src/lib/api/router/routes/games.ts | Fyrlex/bs | d91678a850689d0431a0dc59f5d35ffba2c42b57 | [
"MIT"
] | null | null | null | import { FastifyInstance, HookHandlerDoneFunction, RouteShorthandOptions } from 'fastify';
import * as routers from './games/index.js';
import { BS } from '../../../structures/BSClient.js';
import { Snowflake } from 'discord-api-types';
const router = async (fastify: FastifyInstance, options: RouteShorthandOptions, done: HookHandlerDoneFunction): Promise<void> => {
fastify.delete('/:id', async (req, res) => {
const id = (req.params as { id: Snowflake }).id;
if (!id) return res.status(400).send({
error: true,
message: 'Please provide a game ID in the path.'
});
const game = BS.games.cache.get(id);
if (!game) return res.status(404).send({
error: true,
message: 'Game not found with provided ID.'
});
BS.games.cache.delete(game.id);
return res.status(200).send({
error: false,
message: 'Game successfully deleted.'
});
});
fastify.get('/:id', async (req, res) => {
const id = (req.params as { id: Snowflake }).id;
if (!id) return res.status(400).send({
error: true,
message: 'Please provide a game ID in the path.'
});
const game = BS.games.cache.get(id);
if (!game) return res.status(404).send({
error: true,
message: 'User not found with provided ID.'
});
return res.status(200).send({
error: false,
message: 'Game successfully found.',
data: game
});
});
fastify.post('/', async (req, res) => {
const game = BS.games.create(true);
return res.status(200).send({
error: false,
message: 'Game successfully created.',
data: game
});
});
for (const router of Object.values(routers)) await fastify.register(router.router, { prefix: `/:id/${router.name}` });
done();
};
export const usersRouter = { name: 'games', router }; | 29.015873 | 130 | 0.612691 |
c7c0a986e33366ee13a558ca45b33525ee5bb0f3 | 207,734 | py | Python | cfdm/examplefield.py | sadielbartholomew/cfdm | 04c1e6a271a569631826e08dc69dc2884000475e | [
"MIT"
] | null | null | null | cfdm/examplefield.py | sadielbartholomew/cfdm | 04c1e6a271a569631826e08dc69dc2884000475e | [
"MIT"
] | null | null | null | cfdm/examplefield.py | sadielbartholomew/cfdm | 04c1e6a271a569631826e08dc69dc2884000475e | [
"MIT"
] | null | null | null | from .functions import CF
from .cfdmimplementation import implementation
_implementation = implementation()
def example_field(n, _implementation=_implementation):
"""Return an example field construct.
.. versionadded:: (cfdm) 1.8.0
.. seealso:: `cfdm.example_fields`, `cfdm.example_domain`
:Parameters:
n: `int`
Select the example field construct to return, one of:
===== ===================================================
*n* Description
===== ===================================================
``0`` A field construct with properties as well as a
cell method construct and dimension coordinate
constructs with bounds.
``1`` A field construct with properties as well as at
least one of every type of metadata construct.
``2`` A field construct that contains a monthly time
series at each latitude-longitude location.
``3`` A field construct that contains discrete sampling
geometry (DSG) "timeSeries" features.
``4`` A field construct that contains discrete sampling
geometry (DSG) "timeSeriesProfile" features.
``5`` A field construct that contains a 12 hourly time
series at each latitude-longitude location.
``6`` A field construct that has polygon geometry
coordinate cells with interior ring variables.
``7`` A field construct that has rotated pole dimension
coordinate constructs and 2-d latitude and
longitude auxiliary coordinate constructs.
===== ===================================================
See the examples for details.
_implementation: (subclass of) `CFDMImplementation`, optional
Define the CF data model implementation that provides the
returned field constructs.
:Returns:
`Field`
The example field construct.
**Examples:**
>>> f = cfdm.example_field(0)
>>> print(f)
Field: specific_humidity (ncvar%q)
----------------------------------
Data : specific_humidity(latitude(5), longitude(8)) 1
Cell methods : area: mean
Dimension coords: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: time(1) = [2019-01-01 00:00:00]
>>> print(f.data.array)
[[0.007 0.034 0.003 0.014 0.018 0.037 0.024 0.029]
[0.023 0.036 0.045 0.062 0.046 0.073 0.006 0.066]
[0.11 0.131 0.124 0.146 0.087 0.103 0.057 0.011]
[0.029 0.059 0.039 0.07 0.058 0.072 0.009 0.017]
[0.006 0.036 0.019 0.035 0.018 0.037 0.034 0.013]]
>>> f = cfdm.example_field(1)
>>> print(f)
Field: air_temperature (ncvar%ta)
---------------------------------
Data : air_temperature(atmosphere_hybrid_height_coordinate(1), grid_latitude(10), grid_longitude(9)) K
Cell methods : grid_latitude(10): grid_longitude(9): mean where land (interval: 0.1 degrees) time(1): maximum
Field ancils : air_temperature standard_error(grid_latitude(10), grid_longitude(9)) = [[0.76, ..., 0.32]] K
Dimension coords: atmosphere_hybrid_height_coordinate(1) = [1.5]
: grid_latitude(10) = [2.2, ..., -1.76] degrees
: grid_longitude(9) = [-4.7, ..., -1.18] degrees
: time(1) = [2019-01-01 00:00:00]
Auxiliary coords: latitude(grid_latitude(10), grid_longitude(9)) = [[53.941, ..., 50.225]] degrees_N
: longitude(grid_longitude(9), grid_latitude(10)) = [[2.004, ..., 8.156]] degrees_E
: long_name=Grid latitude name(grid_latitude(10)) = [--, ..., b'kappa']
Cell measures : measure:area(grid_longitude(9), grid_latitude(10)) = [[2391.9657, ..., 2392.6009]] km2
Coord references: grid_mapping_name:rotated_latitude_longitude
: standard_name:atmosphere_hybrid_height_coordinate
Domain ancils : ncvar%a(atmosphere_hybrid_height_coordinate(1)) = [10.0] m
: ncvar%b(atmosphere_hybrid_height_coordinate(1)) = [20.0]
: surface_altitude(grid_latitude(10), grid_longitude(9)) = [[0.0, ..., 270.0]] m
>>> f = cfdm.example_field(2)
>>> print(f)
Field: air_potential_temperature (ncvar%air_potential_temperature)
------------------------------------------------------------------
Data : air_potential_temperature(time(36), latitude(5), longitude(8)) K
Cell methods : area: mean
Dimension coords: time(36) = [1959-12-16 12:00:00, ..., 1962-11-16 00:00:00]
: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: air_pressure(1) = [850.0] hPa
>>> f = cfdm.example_field(3)
>>> print(f)
Field: precipitation_flux (ncvar%p)
-----------------------------------
Data : precipitation_flux(cf_role=timeseries_id(4), ncdim%timeseries(9)) kg m-2 day-1
Auxiliary coords: time(cf_role=timeseries_id(4), ncdim%timeseries(9)) = [[1969-12-29 00:00:00, ..., 1970-01-07 00:00:00]]
: latitude(cf_role=timeseries_id(4)) = [-9.0, ..., 78.0] degrees_north
: longitude(cf_role=timeseries_id(4)) = [-23.0, ..., 178.0] degrees_east
: height(cf_role=timeseries_id(4)) = [0.5, ..., 345.0] m
: cf_role=timeseries_id(cf_role=timeseries_id(4)) = [b'station1', ..., b'station4']
: long_name=station information(cf_role=timeseries_id(4)) = [-10, ..., -7]
>>> f = cfdm.example_field(4)
>>> print(f)
Field: air_temperature (ncvar%ta)
---------------------------------
Data : air_temperature(cf_role=timeseries_id(3), ncdim%timeseries(26), ncdim%profile_1(4)) K
Auxiliary coords: time(cf_role=timeseries_id(3), ncdim%timeseries(26)) = [[1970-01-04 00:00:00, ..., --]]
: latitude(cf_role=timeseries_id(3)) = [-9.0, 2.0, 34.0] degrees_north
: longitude(cf_role=timeseries_id(3)) = [-23.0, 0.0, 67.0] degrees_east
: height(cf_role=timeseries_id(3)) = [0.5, 12.6, 23.7] m
: altitude(cf_role=timeseries_id(3), ncdim%timeseries(26), ncdim%profile_1(4)) = [[[2.07, ..., --]]] km
: cf_role=timeseries_id(cf_role=timeseries_id(3)) = [b'station1', b'station2', b'station3']
: long_name=station information(cf_role=timeseries_id(3)) = [-10, -9, -8]
: cf_role=profile_id(cf_role=timeseries_id(3), ncdim%timeseries(26)) = [[102, ..., --]]
>>> f = cfdm.example_field(5)
>>> print(f)
Field: air_potential_temperature (ncvar%air_potential_temperature)
------------------------------------------------------------------
Data : air_potential_temperature(time(118), latitude(5), longitude(8)) K
Cell methods : area: mean
Dimension coords: time(118) = [1959-01-01 06:00:00, ..., 1959-02-28 18:00:00]
: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: air_pressure(1) = [850.0] hPa
>>> f = cfdm.example_field(6)
>>> print(f)
Field: precipitation_amount (ncvar%pr)
--------------------------------------
Data : precipitation_amount(cf_role=timeseries_id(2), time(4))
Dimension coords: time(4) = [2000-01-16 12:00:00, ..., 2000-04-15 00:00:00]
Auxiliary coords: latitude(cf_role=timeseries_id(2)) = [25.0, 7.0] degrees_north
: longitude(cf_role=timeseries_id(2)) = [10.0, 40.0] degrees_east
: cf_role=timeseries_id(cf_role=timeseries_id(2)) = [b'x1', b'y2']
: ncvar%z(cf_role=timeseries_id(2), 3, 4) = [[[1.0, ..., --]]] m
Coord references: grid_mapping_name:latitude_longitude
>>> f = cfdm.example_field(7)
>>> print(f)
Field: eastward_wind (ncvar%ua)
-------------------------------
Data : eastward_wind(time(3), air_pressure(1), grid_latitude(4), grid_longitude(5)) m s-1
Cell methods : time(3): mean
Dimension coords: time(3) = [1979-05-01 12:00:00, 1979-05-02 12:00:00, 1979-05-03 12:00:00] gregorian
: air_pressure(1) = [850.0] hPa
: grid_latitude(4) = [0.44, ..., -0.88] degrees
: grid_longitude(5) = [-1.18, ..., 0.58] degrees
Auxiliary coords: latitude(grid_latitude(4), grid_longitude(5)) = [[52.4243, ..., 51.1163]] degrees_north
: longitude(grid_latitude(4), grid_longitude(5)) = [[8.0648, ..., 10.9238]] degrees_east
Coord references: grid_mapping_name:rotated_latitude_longitude
"""
if not 0 <= n <= 7:
raise ValueError(
"Must select an example construct with an integer "
f"argument between 0 and 7 inclusive. Got {n!r}"
)
# For safety given the private second argument which we might not
# document, otherwise a user gets an obscure error if they tried, say:
# >>> cfdm.example_field(2, 3)
# AttributeError: 'int' object has no attribute 'get_class'
if isinstance(_implementation, int):
raise ValueError(
"Only one example construct can be returned at a time. "
"Provide a single integer argument only."
)
AuxiliaryCoordinate = _implementation.get_class("AuxiliaryCoordinate")
CellMeasure = _implementation.get_class("CellMeasure")
CellMethod = _implementation.get_class("CellMethod")
CoordinateReference = _implementation.get_class("CoordinateReference")
DimensionCoordinate = _implementation.get_class("DimensionCoordinate")
DomainAncillary = _implementation.get_class("DomainAncillary")
DomainAxis = _implementation.get_class("DomainAxis")
FieldAncillary = _implementation.get_class("FieldAncillary")
Field = _implementation.get_class("Field")
Bounds = _implementation.get_class("Bounds")
InteriorRing = _implementation.get_class("InteriorRing")
Data = _implementation.get_class("Data")
if n == 0:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"project": "research",
"standard_name": "specific_humidity",
"units": "1",
}
)
f.nc_set_variable("q")
c = DomainAxis(size=5)
c.nc_set_dimension("lat")
f.set_construct(c, key="domainaxis0")
c = DomainAxis(size=8)
c.nc_set_dimension("lon")
f.set_construct(c, key="domainaxis1")
c = DomainAxis(size=1)
f.set_construct(c, key="domainaxis2")
data = Data(
[
[0.007, 0.034, 0.003, 0.014, 0.018, 0.037, 0.024, 0.029],
[0.023, 0.036, 0.045, 0.062, 0.046, 0.073, 0.006, 0.066],
[0.11, 0.131, 0.124, 0.146, 0.087, 0.103, 0.057, 0.011],
[0.029, 0.059, 0.039, 0.07, 0.058, 0.072, 0.009, 0.017],
[0.006, 0.036, 0.019, 0.035, 0.018, 0.037, 0.034, 0.013],
],
units="1",
dtype="f8",
)
f.set_data(data, axes=("domainaxis0", "domainaxis1"))
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_north", "standard_name": "latitude"}
)
c.nc_set_variable("lat")
data = Data(
[-75.0, -45.0, 0.0, 45.0, 75.0], units="degrees_north", dtype="f8"
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lat_bnds")
data = Data(
[
[-90.0, -60.0],
[-60.0, -30.0],
[-30.0, 30.0],
[30.0, 60.0],
[60.0, 90.0],
],
units="degrees_north",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="dimensioncoordinate0", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_east", "standard_name": "longitude"}
)
c.nc_set_variable("lon")
data = Data(
[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
units="degrees_east",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lon_bnds")
data = Data(
[
[0.0, 45.0],
[45.0, 90.0],
[90.0, 135.0],
[135.0, 180.0],
[180.0, 225.0],
[225.0, 270.0],
[270.0, 315.0],
[315.0, 360.0],
],
units="degrees_east",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate1", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "days since 2018-12-01", "standard_name": "time"}
)
c.nc_set_variable("time")
data = Data([31.0], units="days since 2018-12-01", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis2",), key="dimensioncoordinate2", copy=False
)
# cell_method
c = CellMethod()
c.set_method("mean")
c.set_axes("area")
f.set_construct(c)
elif n == 1:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"project": "research",
"standard_name": "air_temperature",
"units": "K",
}
)
f.nc_set_variable("ta")
c = DomainAxis(size=1)
c.nc_set_dimension("atmosphere_hybrid_height_coordinate")
f.set_construct(c, key="domainaxis0")
c = DomainAxis(size=10)
c.nc_set_dimension("y")
f.set_construct(c, key="domainaxis1")
c = DomainAxis(size=9)
c.nc_set_dimension("x")
f.set_construct(c, key="domainaxis2")
c = DomainAxis(size=1)
f.set_construct(c, key="domainaxis3")
data = Data(
[
[
[
262.8,
270.5,
279.8,
269.5,
260.9,
265.0,
263.5,
278.9,
269.2,
],
[
272.7,
268.4,
279.5,
278.9,
263.8,
263.3,
274.2,
265.7,
279.5,
],
[
269.7,
279.1,
273.4,
274.2,
279.6,
270.2,
280.0,
272.5,
263.7,
],
[
261.7,
260.6,
270.8,
260.3,
265.6,
279.4,
276.9,
267.6,
260.6,
],
[
264.2,
275.9,
262.5,
264.9,
264.7,
270.2,
270.4,
268.6,
275.3,
],
[
263.9,
263.8,
272.1,
263.7,
272.2,
264.2,
260.0,
263.5,
270.2,
],
[
273.8,
273.1,
268.5,
272.3,
264.3,
278.7,
270.6,
273.0,
270.6,
],
[
267.9,
273.5,
279.8,
260.3,
261.2,
275.3,
271.2,
260.8,
268.9,
],
[
270.9,
278.7,
273.2,
261.7,
271.6,
265.8,
273.0,
278.5,
266.4,
],
[
276.4,
264.2,
276.3,
266.1,
276.1,
268.1,
277.0,
273.4,
269.7,
],
]
],
units="K",
dtype="f8",
)
f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2"))
# domain_ancillary
c = DomainAncillary()
c.set_properties({"units": "m"})
c.nc_set_variable("a")
data = Data([10.0], units="m", dtype="f8")
c.set_data(data)
b = Bounds()
b.nc_set_variable("a_bounds")
data = Data([[5.0, 15.0]], units="m", dtype="f8")
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="domainancillary0", copy=False
)
# domain_ancillary
c = DomainAncillary()
c.nc_set_variable("b")
data = Data([20.0], dtype="f8")
c.set_data(data)
b = Bounds()
b.nc_set_variable("b_bounds")
data = Data([[14.0, 26.0]], dtype="f8")
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="domainancillary1", copy=False
)
# domain_ancillary
c = DomainAncillary()
c.set_properties({"units": "m", "standard_name": "surface_altitude"})
c.nc_set_variable("surface_altitude")
data = Data(
[
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 12.0, 10.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 17.0, 52.0, 40.0],
[0.0, 0.0, 0.0, 7.0, 12.0, 8.0, 37.0, 73.0, 107.0],
[0.0, 0.0, 28.0, 30.0, 30.0, 30.0, 83.0, 102.0, 164.0],
[34.0, 38.0, 34.0, 32.0, 30.0, 31.0, 105.0, 281.0, 370.0],
[91.0, 89.0, 95.0, 94.0, 132.0, 194.0, 154.0, 318.0, 357.0],
[93.0, 114.0, 116.0, 178.0, 323.0, 365.0, 307.0, 289.0, 270.0],
],
units="m",
dtype="f4",
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis1", "domainaxis2"),
key="domainancillary2",
copy=False,
)
# cell_measure
c = CellMeasure()
c.set_properties({"units": "km2"})
c.nc_set_variable("cell_measure")
data = Data(
[
[
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2391.9657,
2392.6009,
],
[
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2393.0949,
2393.0949,
],
[
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.4478,
2393.4478,
2393.4478,
],
[
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.6595,
2393.6595,
2393.6595,
2393.6595,
],
[
2393.6595,
2393.6595,
2393.6595,
2393.6595,
2393.6595,
2393.7301,
2393.7301,
2393.7301,
2393.7301,
2393.7301,
],
[
2393.7301,
2393.7301,
2393.7301,
2393.7301,
2393.6595,
2393.6595,
2393.6595,
2393.6595,
2393.6595,
2393.6595,
],
[
2393.6595,
2393.6595,
2393.6595,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
2393.4478,
],
[
2393.4478,
2393.4478,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
2393.0949,
],
[
2393.0949,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
2392.6009,
],
],
units="km2",
dtype="f8",
)
c.set_data(data)
c.set_measure("area")
f.set_construct(
c,
axes=("domainaxis2", "domainaxis1"),
key="cellmeasure0",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"units": "degrees_N", "standard_name": "latitude"})
c.nc_set_variable("latitude_1")
data = Data(
[
[
53.941,
53.987,
54.029,
54.066,
54.099,
54.127,
54.15,
54.169,
54.184,
],
[
53.504,
53.55,
53.591,
53.627,
53.66,
53.687,
53.711,
53.729,
53.744,
],
[
53.067,
53.112,
53.152,
53.189,
53.221,
53.248,
53.271,
53.29,
53.304,
],
[
52.629,
52.674,
52.714,
52.75,
52.782,
52.809,
52.832,
52.85,
52.864,
],
[
52.192,
52.236,
52.276,
52.311,
52.343,
52.37,
52.392,
52.41,
52.424,
],
[
51.754,
51.798,
51.837,
51.873,
51.904,
51.93,
51.953,
51.971,
51.984,
],
[
51.316,
51.36,
51.399,
51.434,
51.465,
51.491,
51.513,
51.531,
51.545,
],
[
50.879,
50.922,
50.96,
50.995,
51.025,
51.052,
51.074,
51.091,
51.105,
],
[
50.441,
50.484,
50.522,
50.556,
50.586,
50.612,
50.634,
50.652,
50.665,
],
[
50.003,
50.045,
50.083,
50.117,
50.147,
50.173,
50.194,
50.212,
50.225,
],
],
units="degrees_N",
dtype="f8",
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis1", "domainaxis2"),
key="auxiliarycoordinate0",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"units": "degrees_E", "standard_name": "longitude"})
c.nc_set_variable("longitude_1")
data = Data(
[
[
2.004,
2.747,
3.492,
4.238,
4.986,
5.734,
6.484,
7.234,
7.985,
2.085,
],
[
2.821,
3.558,
4.297,
5.037,
5.778,
6.52,
7.262,
8.005,
2.165,
2.893,
],
[
3.623,
4.355,
5.087,
5.821,
6.555,
7.29,
8.026,
2.243,
2.964,
3.687,
],
[
4.411,
5.136,
5.862,
6.589,
7.317,
8.045,
2.319,
3.033,
3.749,
4.466,
],
[
5.184,
5.903,
6.623,
7.344,
8.065,
2.394,
3.101,
3.81,
4.52,
5.231,
],
[
5.944,
6.656,
7.37,
8.084,
2.467,
3.168,
3.87,
4.573,
5.278,
5.983,
],
[
6.689,
7.395,
8.102,
2.539,
3.233,
3.929,
4.626,
5.323,
6.022,
6.721,
],
[
7.42,
8.121,
2.61,
3.298,
3.987,
4.677,
5.368,
6.059,
6.752,
7.445,
],
[
8.139,
2.679,
3.361,
4.043,
4.727,
5.411,
6.097,
6.783,
7.469,
8.156,
],
],
units="degrees_E",
dtype="f8",
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis2", "domainaxis1"),
key="auxiliarycoordinate1",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"long_name": "Grid latitude name"})
c.nc_set_variable("auxiliary")
data_mask = Data(
[
True,
False,
False,
False,
False,
False,
False,
False,
False,
False,
],
dtype="b1",
)
data = Data(
[
b"",
b"beta",
b"gamma",
b"delta",
b"epsilon",
b"zeta",
b"eta",
b"theta",
b"iota",
b"kappa",
],
dtype="S7",
mask=data_mask,
)
c.set_data(data)
f.set_construct(
c, axes=("domainaxis1",), key="auxiliarycoordinate2", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{
"computed_standard_name": "altitude",
"standard_name": "atmosphere_hybrid_height_coordinate",
}
)
c.nc_set_variable("atmosphere_hybrid_height_coordinate")
data = Data([1.5], dtype="f8")
c.set_data(data)
b = Bounds()
b.nc_set_variable("atmosphere_hybrid_height_coordinate_bounds")
data = Data([[1.0, 2.0]], dtype="f8")
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="dimensioncoordinate0", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees", "standard_name": "grid_latitude"}
)
c.nc_set_variable("y")
data = Data(
[2.2, 1.76, 1.32, 0.88, 0.44, 0.0, -0.44, -0.88, -1.32, -1.76],
units="degrees",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("y_bnds")
data = Data(
[
[2.42, 1.98],
[1.98, 1.54],
[1.54, 1.1],
[1.1, 0.66],
[0.66, 0.22],
[0.22, -0.22],
[-0.22, -0.66],
[-0.66, -1.1],
[-1.1, -1.54],
[-1.54, -1.98],
],
units="degrees",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate1", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees", "standard_name": "grid_longitude"}
)
c.nc_set_variable("x")
data = Data(
[-4.7, -4.26, -3.82, -3.38, -2.94, -2.5, -2.06, -1.62, -1.18],
units="degrees",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("x_bnds")
data = Data(
[
[-4.92, -4.48],
[-4.48, -4.04],
[-4.04, -3.6],
[-3.6, -3.16],
[-3.16, -2.72],
[-2.72, -2.28],
[-2.28, -1.84],
[-1.84, -1.4],
[-1.4, -0.96],
],
units="degrees",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis2",), key="dimensioncoordinate2", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "days since 2018-12-01", "standard_name": "time"}
)
c.nc_set_variable("time")
data = Data([31.0], units="days since 2018-12-01", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis3",), key="dimensioncoordinate3", copy=False
)
# field_ancillary
c = FieldAncillary()
c.set_properties(
{"units": "K", "standard_name": "air_temperature standard_error"}
)
c.nc_set_variable("air_temperature_standard_error")
data = Data(
[
[0.76, 0.38, 0.68, 0.19, 0.14, 0.52, 0.57, 0.19, 0.81],
[0.59, 0.68, 0.25, 0.13, 0.37, 0.12, 0.26, 0.45, 0.36],
[0.88, 0.4, 0.35, 0.87, 0.24, 0.64, 0.78, 0.28, 0.11],
[0.73, 0.49, 0.69, 0.54, 0.17, 0.6, 0.82, 0.89, 0.71],
[0.43, 0.39, 0.45, 0.74, 0.85, 0.47, 0.37, 0.87, 0.46],
[0.47, 0.31, 0.76, 0.69, 0.61, 0.26, 0.43, 0.75, 0.23],
[0.43, 0.26, 0.5, 0.79, 0.25, 0.63, 0.25, 0.24, 0.74],
[0.33, 0.26, 0.89, 0.48, 0.79, 0.88, 0.41, 0.89, 0.47],
[0.25, 0.42, 0.61, 0.87, 0.58, 0.89, 0.58, 0.8, 0.32],
[0.49, 0.48, 0.49, 0.16, 0.65, 0.66, 0.86, 0.74, 0.32],
],
units="K",
dtype="f8",
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis1", "domainaxis2"),
key="fieldancillary0",
copy=False,
)
# cell_method
c = CellMethod()
c.set_method("mean")
c.set_axes(("domainaxis1", "domainaxis2"))
c.set_qualifier("where", "land")
interval0 = Data(0.1, units="degrees", dtype="f8")
c.set_qualifier("interval", [interval0])
f.set_construct(c)
# cell_method
c = CellMethod()
c.set_method("maximum")
c.set_axes("domainaxis3")
f.set_construct(c)
# coordinate_reference
c = CoordinateReference()
c.set_coordinates({"dimensioncoordinate0"})
c.datum.set_parameter("earth_radius", 6371007)
c.coordinate_conversion.set_parameter(
"standard_name", "atmosphere_hybrid_height_coordinate"
)
c.coordinate_conversion.set_parameter(
"computed_standard_name", "altitude"
)
c.coordinate_conversion.set_domain_ancillaries(
{
"a": "domainancillary0",
"b": "domainancillary1",
"orog": "domainancillary2",
}
)
f.set_construct(c)
# coordinate_reference
c = CoordinateReference()
c.nc_set_variable("rotated_latitude_longitude")
c.set_coordinates(
{
"dimensioncoordinate2",
"auxiliarycoordinate1",
"dimensioncoordinate1",
"auxiliarycoordinate0",
}
)
c.datum.set_parameter("earth_radius", 6371007)
c.coordinate_conversion.set_parameter("grid_north_pole_latitude", 38.0)
c.coordinate_conversion.set_parameter(
"grid_north_pole_longitude", 190.0
)
c.coordinate_conversion.set_parameter(
"grid_mapping_name", "rotated_latitude_longitude"
)
f.set_construct(c)
elif n == 3:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"featureType": "timeSeries",
"_FillValue": -999.9,
"standard_name": "precipitation_flux",
"units": "kg m-2 day-1",
}
)
f.nc_set_variable("p")
f.nc_set_global_attributes({"Conventions": None, "featureType": None})
# domain_axis
c = DomainAxis(size=4)
c.nc_set_dimension("station")
f.set_construct(c, key="domainaxis0")
# domain_axis
c = DomainAxis(size=9)
c.nc_set_dimension("timeseries")
f.set_construct(c, key="domainaxis1")
# field data
data_mask = Data(
[
[False, False, False, True, True, True, True, True, True],
[False, False, False, False, False, False, False, True, True],
[False, False, False, False, False, True, True, True, True],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
],
],
dtype="b1",
)
data = Data(
[
[
3.98,
0.0,
0.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
0.0,
0.0,
0.0,
3.4,
0.0,
0.0,
4.61,
9.969209968386869e36,
9.969209968386869e36,
],
[
0.86,
0.8,
0.75,
0.0,
4.56,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.0, 0.09, 0.0, 0.91, 2.96, 1.14, 3.86, 0.0, 0.0],
],
units="kg m-2 day-1",
dtype="f8",
mask=data_mask,
)
f.set_data(data, axes=("domainaxis0", "domainaxis1"))
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "time",
"long_name": "time of measurement",
"units": "days since 1970-01-01 00:00:00",
}
)
c.nc_set_variable("time")
data_mask = Data(
[
[False, False, False, True, True, True, True, True, True],
[False, False, False, False, False, False, False, True, True],
[False, False, False, False, False, True, True, True, True],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
],
],
dtype="b1",
)
data = Data(
[
[
-3.0,
-2.0,
-1.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
9.969209968386869e36,
9.969209968386869e36,
],
[
0.5,
1.5,
2.5,
3.5,
4.5,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
],
units="days since 1970-01-01 00:00:00",
dtype="f8",
mask=data_mask,
)
c.set_data(data)
b = Bounds()
data_mask = Data(
[
[
[False, False],
[False, False],
[False, False],
[True, True],
[True, True],
[True, True],
[True, True],
[True, True],
[True, True],
],
[
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[True, True],
[True, True],
],
[
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[True, True],
[True, True],
[True, True],
[True, True],
],
[
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
[False, False],
],
],
dtype="b1",
)
data = Data(
[
[
[-3.5, -2.5],
[-2.5, -1.5],
[-1.5, -0.5],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
],
[
[0.5, 1.5],
[1.5, 2.5],
[2.5, 3.5],
[3.5, 4.5],
[4.5, 5.5],
[5.5, 6.5],
[6.5, 7.5],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
],
[
[0.0, 1.0],
[1.0, 2.0],
[2.0, 3.0],
[3.0, 4.0],
[4.0, 5.0],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
[9.969209968386869e36, 9.969209968386869e36],
],
[
[-2.5, -1.5],
[-1.5, -0.5],
[-0.5, 0.5],
[0.5, 1.5],
[1.5, 2.5],
[2.5, 3.5],
[3.5, 4.5],
[4.5, 5.5],
[5.5, 6.5],
],
],
units="days since 1970-01-01 00:00:00",
dtype="f8",
mask=data_mask,
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c,
axes=("domainaxis0", "domainaxis1"),
key="auxiliarycoordinate0",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "latitude",
"long_name": "station latitude",
"units": "degrees_north",
}
)
c.nc_set_variable("lat")
data = Data([-9.0, 2.0, 34.0, 78.0], units="degrees_north", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate1", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "longitude",
"long_name": "station longitude",
"units": "degrees_east",
}
)
c.nc_set_variable("lon")
data = Data(
[-23.0, 0.0, 67.0, 178.0], units="degrees_east", dtype="f8"
)
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate2", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"long_name": "vertical distance above the surface",
"standard_name": "height",
"units": "m",
"positive": "up",
"axis": "Z",
}
)
c.nc_set_variable("alt")
data = Data([0.5, 12.6, 23.7, 345.0], units="m", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate3", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{"long_name": "station name", "cf_role": "timeseries_id"}
)
c.nc_set_variable("station_name")
data = Data(
[b"station1", b"station2", b"station3", b"station4"], dtype="S8"
)
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate4", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"long_name": "station information"})
c.nc_set_variable("station_info")
data = Data([-10, -9, -8, -7], dtype="i4")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate5", copy=False
)
elif n == 4:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"featureType": "timeSeriesProfile",
"_FillValue": -999.9,
"standard_name": "air_temperature",
"units": "K",
}
)
f.nc_set_variable("ta")
f.nc_set_global_attribute("Conventions", None)
f.nc_set_global_attribute("featureType", None)
# domain_axis
c = DomainAxis(size=3)
c.nc_set_dimension("station")
f.set_construct(c, key="domainaxis0")
# domain_axis
c = DomainAxis(size=26)
c.nc_set_dimension("timeseries")
f.set_construct(c, key="domainaxis1")
# domain_axis
c = DomainAxis(size=4)
c.nc_set_dimension("profile_1")
f.set_construct(c, key="domainaxis2")
# field data
data_mask = Data(
[
[
[False, True, True, True],
[False, False, False, True],
[False, False, True, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
],
[
[False, False, False, False],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, True, True, True],
[False, False, False, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
],
[
[False, True, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, False, False, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, True, True],
[False, False, False, True],
[False, True, True, True],
[False, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
],
],
dtype="b1",
)
data = Data(
[
[
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[293.15, 288.84, 280.0, 9.969209968386869e36],
[
291.65,
285.0,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.45,
286.14,
9.969209968386869e36,
9.969209968386869e36,
],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
291.65,
288.57,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
293.27,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[293.36, 285.99, 285.46, 9.969209968386869e36],
[
291.2,
285.96,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
[
[291.74, 285.72, 283.21, 275.0],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[
290.15,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
291.08,
285.0,
9.969209968386869e36,
9.969209968386869e36,
],
[
291.32,
288.66,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
294.18,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[290.0, 286.05, 280.0, 9.969209968386869e36],
[291.23, 285.0, 281.11, 9.969209968386869e36],
[295.88, 286.83, 285.01, 9.969209968386869e36],
[292.37, 285.6, 280.0, 9.969209968386869e36],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[300.11, 285.0, 280.0, 9.969209968386869e36],
[290.0, 287.4, 9.969209968386869e36, 9.969209968386869e36],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
291.5,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
294.98,
290.64,
9.969209968386869e36,
9.969209968386869e36,
],
[290.66, 292.92, 280.0, 9.969209968386869e36],
[290.24, 285.36, 280.36, 9.969209968386869e36],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
292.79,
285.0,
9.969209968386869e36,
9.969209968386869e36,
],
[290.0, 287.22, 280.0, 9.969209968386869e36],
[290.0, 286.14, 280.0, 9.969209968386869e36],
],
[
[
291.74,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[291.44, 287.25, 280.0, 9.969209968386869e36],
[292.76, 285.0, 280.0, 9.969209968386869e36],
[291.59, 286.71, 284.47, 9.969209968386869e36],
[
292.19,
286.35,
9.969209968386869e36,
9.969209968386869e36,
],
[
295.67,
285.0,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.45,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[293.69, 285.9, 280.03, 9.969209968386869e36],
[290.0, 285.27, 280.87, 9.969209968386869e36],
[290.0, 285.0, 9.969209968386869e36, 9.969209968386869e36],
[290.12, 286.44, 282.01, 9.969209968386869e36],
[
291.23,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
292.97,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
290.0,
286.71,
9.969209968386869e36,
9.969209968386869e36,
],
[
292.01,
285.0,
9.969209968386869e36,
9.969209968386869e36,
],
[294.62, 285.33, 282.01, 9.969209968386869e36],
[
290.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
292.64,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
],
units="K",
dtype="f8",
mask=data_mask,
)
f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2"))
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "time",
"long_name": "time",
"units": "days since 1970-01-01 00:00:00",
}
)
c.nc_set_variable("time")
data_mask = Data(
[
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
True,
True,
True,
True,
True,
True,
],
],
dtype="b1",
)
data = Data(
[
[
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.0,
11.0,
12.0,
13.0,
14.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
0.0,
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.0,
11.0,
12.0,
13.0,
14.0,
15.0,
16.0,
17.0,
18.0,
19.0,
20.0,
21.0,
22.0,
23.0,
24.0,
25.0,
],
[
-3.0,
-2.0,
-1.0,
0.0,
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.0,
11.0,
12.0,
13.0,
14.0,
15.0,
16.0,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
units="days since 1970-01-01 00:00:00",
dtype="f8",
mask=data_mask,
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis0", "domainaxis1"),
key="auxiliarycoordinate0",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "latitude",
"long_name": "station latitude",
"units": "degrees_north",
}
)
c.nc_set_variable("lat")
data = Data([-9.0, 2.0, 34.0], units="degrees_north", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate1", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "longitude",
"long_name": "station longitude",
"units": "degrees_east",
}
)
c.nc_set_variable("lon")
data = Data([-23.0, 0.0, 67.0], units="degrees_east", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate2", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"long_name": "vertical distance above the surface",
"standard_name": "height",
"units": "m",
"positive": "up",
"axis": "Z",
}
)
c.nc_set_variable("alt")
data = Data([0.5, 12.6, 23.7], units="m", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate3", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{
"standard_name": "altitude",
"long_name": "height above mean sea level",
"units": "km",
"axis": "Z",
"positive": "up",
}
)
c.nc_set_variable("z")
data_mask = Data(
[
[
[False, True, True, True],
[False, False, False, True],
[False, False, True, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
],
[
[False, False, False, False],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, True, True, True],
[False, False, False, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
],
[
[False, True, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, False, True, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, False, True],
[False, False, False, True],
[False, False, True, True],
[False, False, False, True],
[False, True, True, True],
[False, True, True, True],
[False, False, True, True],
[False, False, True, True],
[False, False, False, True],
[False, True, True, True],
[False, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
],
],
dtype="b1",
)
data = Data(
[
[
[
2.07,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[1.01, 1.18, 1.82, 9.969209968386869e36],
[1.1, 1.18, 9.969209968386869e36, 9.969209968386869e36],
[1.63, 2.0, 9.969209968386869e36, 9.969209968386869e36],
[1.38, 1.83, 9.969209968386869e36, 9.969209968386869e36],
[
1.59,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[1.57, 2.12, 9.969209968386869e36, 9.969209968386869e36],
[
2.25,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
1.8,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[1.26, 2.17, 9.969209968386869e36, 9.969209968386869e36],
[1.05, 1.29, 2.1, 9.969209968386869e36],
[1.6, 1.97, 9.969209968386869e36, 9.969209968386869e36],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
[
[0.52, 0.58, 1.08, 1.38],
[0.26, 0.92, 9.969209968386869e36, 9.969209968386869e36],
[0.07, 0.4, 9.969209968386869e36, 9.969209968386869e36],
[
1.57,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.25, 1.6, 9.969209968386869e36, 9.969209968386869e36],
[0.46, 0.98, 9.969209968386869e36, 9.969209968386869e36],
[0.06, 0.31, 9.969209968386869e36, 9.969209968386869e36],
[
0.38,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.57, 1.29, 1.81, 9.969209968386869e36],
[0.39, 0.69, 1.69, 9.969209968386869e36],
[0.73, 1.38, 1.6, 9.969209968386869e36],
[0.45, 0.98, 1.13, 9.969209968386869e36],
[
0.15,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.09, 0.43, 0.62, 9.969209968386869e36],
[0.17, 0.99, 9.969209968386869e36, 9.969209968386869e36],
[
0.93,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
0.07,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
1.57,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.07, 0.12, 9.969209968386869e36, 9.969209968386869e36],
[0.45, 1.24, 1.3, 9.969209968386869e36],
[0.35, 0.68, 0.79, 9.969209968386869e36],
[0.81, 1.22, 9.969209968386869e36, 9.969209968386869e36],
[
0.59,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[0.1, 0.96, 9.969209968386869e36, 9.969209968386869e36],
[0.56, 0.78, 0.91, 9.969209968386869e36],
[0.71, 0.9, 1.04, 9.969209968386869e36],
],
[
[
3.52,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[3.47, 3.89, 4.81, 9.969209968386869e36],
[3.52, 3.93, 3.96, 9.969209968386869e36],
[4.03, 4.04, 4.8, 9.969209968386869e36],
[3.0, 3.65, 9.969209968386869e36, 9.969209968386869e36],
[3.33, 4.33, 9.969209968386869e36, 9.969209968386869e36],
[
3.77,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
3.35,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[3.19, 3.37, 9.969209968386869e36, 9.969209968386869e36],
[3.41, 3.54, 4.1, 9.969209968386869e36],
[3.02, 3.37, 3.87, 9.969209968386869e36],
[3.24, 4.24, 9.969209968386869e36, 9.969209968386869e36],
[3.32, 3.49, 3.97, 9.969209968386869e36],
[
3.32,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
3.85,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[3.73, 3.99, 9.969209968386869e36, 9.969209968386869e36],
[3.0, 3.91, 9.969209968386869e36, 9.969209968386869e36],
[3.64, 3.91, 4.56, 9.969209968386869e36],
[
4.1,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
3.11,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
],
units="km",
dtype="f8",
mask=data_mask,
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis0", "domainaxis1", "domainaxis2"),
key="auxiliarycoordinate4",
copy=False,
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties(
{"long_name": "station name", "cf_role": "timeseries_id"}
)
c.nc_set_variable("station_name")
data = Data([b"station1", b"station2", b"station3"], dtype="S8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate5", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"long_name": "station information"})
c.nc_set_variable("station_info")
data = Data([-10, -9, -8], dtype="i4")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate6", copy=False
)
# auxiliary_coordinate
c = AuxiliaryCoordinate()
c.set_properties({"cf_role": "profile_id"})
c.nc_set_variable("profile")
data_mask = Data(
[
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
True,
],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
],
[
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
True,
True,
True,
True,
True,
True,
],
],
dtype="b1",
)
data = Data(
[
[
102,
106,
109,
117,
121,
124,
132,
136,
139,
147,
151,
154,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
],
[
101,
104,
105,
108,
110,
113,
114,
116,
119,
120,
123,
125,
128,
129,
131,
134,
135,
138,
140,
143,
144,
146,
149,
150,
153,
155,
],
[
100,
103,
107,
111,
112,
115,
118,
122,
126,
127,
130,
133,
137,
141,
142,
145,
148,
152,
156,
157,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
-2147483647,
],
],
dtype="i4",
mask=data_mask,
)
c.set_data(data)
f.set_construct(
c,
axes=("domainaxis0", "domainaxis1"),
key="auxiliarycoordinate7",
copy=False,
)
elif n == 2:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"standard_name": "air_potential_temperature",
"units": "K",
}
)
f.nc_set_variable("air_potential_temperature")
f.nc_set_global_attribute("Conventions", None)
# domain_axis
c = DomainAxis(size=36)
c.nc_set_dimension("time")
f.set_construct(c, key="domainaxis0")
# domain_axis
c = DomainAxis(size=5)
c.nc_set_dimension("lat")
f.set_construct(c, key="domainaxis1")
# domain_axis
c = DomainAxis(size=8)
c.nc_set_dimension("lon")
f.set_construct(c, key="domainaxis2")
# domain_axis
c = DomainAxis(size=1)
f.set_construct(c, key="domainaxis3")
# field data
data = Data(
[
[
[210.7, 212.9, 282.7, 293.9, 264.0, 228.0, 211.6, 266.5],
[212.8, 224.3, 301.9, 308.2, 237.1, 233.9, 200.1, 208.2],
[234.9, 273.0, 245.1, 233.7, 262.9, 242.0, 254.7, 299.3],
[204.1, 233.4, 278.1, 293.7, 232.8, 246.2, 268.0, 298.4],
[309.5, 294.7, 209.8, 204.3, 224.8, 271.1, 292.2, 293.9],
],
[
[305.3, 271.6, 300.7, 267.8, 226.0, 204.9, 202.6, 294.3],
[291.7, 251.6, 311.1, 252.2, 297.1, 205.4, 289.5, 258.4],
[300.9, 304.2, 206.3, 259.2, 223.6, 236.2, 275.6, 284.9],
[226.4, 309.3, 223.7, 305.3, 283.4, 219.1, 303.8, 271.3],
[234.6, 301.8, 261.1, 226.6, 261.9, 267.0, 297.5, 241.3],
],
[
[249.4, 278.9, 308.2, 283.3, 283.2, 227.7, 288.3, 221.9],
[270.7, 268.0, 306.4, 294.9, 242.0, 276.5, 218.0, 247.2],
[229.8, 291.0, 246.1, 205.2, 232.7, 244.7, 235.4, 264.5],
[239.1, 278.2, 299.1, 203.2, 308.9, 303.2, 309.0, 228.9],
[203.2, 279.8, 248.5, 270.8, 234.0, 307.7, 236.4, 237.1],
],
[
[288.9, 235.0, 279.9, 218.1, 241.4, 233.6, 238.0, 221.9],
[235.0, 289.2, 283.8, 306.0, 219.7, 240.4, 199.0, 238.8],
[281.6, 262.3, 251.7, 290.0, 279.7, 267.1, 304.2, 244.6],
[298.3, 201.7, 251.8, 233.3, 253.5, 229.2, 228.7, 277.6],
[213.5, 290.2, 202.6, 217.9, 244.9, 224.1, 286.4, 268.1],
],
[
[231.1, 243.5, 199.9, 264.0, 282.2, 288.8, 269.4, 291.2],
[216.6, 256.6, 201.9, 279.4, 211.0, 223.4, 205.8, 207.7],
[230.2, 218.6, 248.6, 292.3, 253.3, 212.5, 205.9, 208.9],
[273.5, 249.9, 257.5, 237.6, 250.7, 233.4, 255.6, 255.2],
[274.0, 208.6, 283.6, 259.4, 242.0, 307.4, 251.2, 233.7],
],
[
[200.0, 265.0, 273.4, 235.5, 297.4, 232.2, 266.0, 277.8],
[260.3, 221.3, 243.1, 217.2, 205.8, 225.9, 227.8, 264.1],
[231.1, 210.2, 258.6, 215.7, 221.1, 303.4, 283.0, 209.3],
[260.5, 231.8, 212.0, 249.7, 202.5, 256.0, 291.2, 232.0],
[282.3, 266.8, 207.4, 262.4, 303.2, 277.5, 263.5, 294.7],
],
[
[234.4, 304.3, 226.2, 231.7, 261.9, 204.3, 287.5, 229.5],
[264.4, 291.3, 289.0, 295.4, 250.5, 252.1, 275.0, 244.1],
[245.2, 228.1, 227.2, 252.0, 307.9, 296.9, 247.9, 219.6],
[302.0, 256.5, 298.4, 222.3, 285.8, 308.4, 225.5, 202.6],
[308.8, 274.1, 215.4, 288.5, 230.5, 213.0, 310.2, 205.8],
],
[
[289.2, 275.2, 241.5, 231.5, 261.6, 310.1, 235.5, 280.6],
[273.7, 201.4, 290.0, 287.6, 220.2, 215.2, 215.1, 266.6],
[290.8, 309.8, 278.5, 286.3, 278.6, 203.6, 231.7, 263.9],
[231.1, 299.2, 301.8, 217.8, 286.1, 206.8, 254.8, 234.1],
[238.3, 301.8, 244.9, 263.8, 202.2, 257.2, 245.8, 199.4],
],
[
[204.3, 301.8, 247.5, 279.3, 276.3, 258.3, 252.2, 297.9],
[261.3, 230.3, 277.2, 255.9, 286.6, 203.5, 288.3, 246.3],
[281.8, 309.0, 241.4, 307.3, 261.0, 199.4, 311.1, 278.5],
[259.2, 302.6, 283.3, 206.4, 206.5, 250.3, 249.0, 271.0],
[274.2, 304.6, 252.5, 236.2, 244.3, 229.8, 221.1, 289.0],
],
[
[203.6, 292.0, 201.0, 280.9, 238.8, 199.9, 200.3, 244.4],
[244.9, 232.6, 204.9, 257.3, 265.7, 230.9, 231.6, 295.7],
[281.6, 282.9, 271.7, 250.3, 217.4, 269.5, 219.5, 262.1],
[308.2, 283.4, 259.5, 234.6, 248.6, 212.6, 262.7, 237.0],
[258.0, 257.9, 272.7, 310.4, 291.0, 265.9, 205.4, 256.9],
],
[
[261.8, 308.8, 303.2, 210.1, 281.0, 275.7, 200.6, 285.6],
[199.8, 219.7, 248.1, 231.8, 217.9, 199.1, 272.8, 282.2],
[264.1, 301.2, 269.9, 243.0, 223.8, 281.5, 247.8, 222.6],
[273.6, 199.5, 256.0, 199.9, 234.7, 273.7, 285.0, 288.2],
[306.7, 275.5, 301.5, 207.4, 278.4, 228.9, 245.3, 266.9],
],
[
[256.2, 229.4, 296.5, 305.5, 202.0, 247.2, 254.9, 306.1],
[251.3, 279.2, 215.4, 250.5, 204.3, 253.1, 275.8, 210.1],
[306.9, 208.4, 267.3, 284.5, 226.5, 280.0, 252.6, 286.8],
[293.9, 261.8, 262.9, 218.9, 238.7, 298.4, 311.2, 288.7],
[277.6, 223.3, 224.4, 202.2, 274.1, 203.7, 225.3, 229.6],
],
[
[212.3, 253.2, 257.3, 261.4, 268.9, 260.4, 255.5, 224.1],
[208.3, 227.6, 296.5, 307.7, 297.6, 230.3, 300.7, 273.5],
[268.9, 255.9, 220.3, 307.2, 274.5, 249.9, 284.0, 217.6],
[285.4, 306.5, 203.9, 232.4, 306.1, 219.9, 272.1, 222.3],
[220.6, 258.6, 307.9, 280.9, 310.4, 202.0, 237.3, 294.9],
],
[
[231.7, 299.5, 217.4, 267.3, 278.6, 204.4, 234.7, 233.5],
[266.0, 302.9, 215.8, 281.6, 254.0, 223.6, 248.1, 310.0],
[281.4, 257.0, 269.8, 207.8, 286.4, 221.4, 239.3, 251.8],
[237.9, 228.6, 289.9, 245.3, 232.9, 302.9, 278.2, 248.4],
[252.2, 249.6, 290.7, 203.2, 293.1, 205.7, 302.5, 217.6],
],
[
[255.1, 200.6, 268.4, 216.3, 246.5, 250.2, 292.9, 226.8],
[297.8, 280.7, 271.8, 251.7, 298.1, 218.0, 295.2, 234.5],
[231.8, 281.5, 305.0, 261.4, 222.9, 217.0, 211.6, 275.2],
[218.0, 308.1, 221.3, 251.8, 252.1, 254.3, 270.6, 294.9],
[299.6, 237.6, 216.5, 300.0, 286.2, 277.1, 242.6, 284.3],
],
[
[213.9, 219.2, 212.0, 241.9, 276.3, 269.1, 298.9, 200.9],
[274.2, 236.4, 218.4, 241.8, 208.6, 287.3, 219.0, 232.8],
[254.0, 266.1, 307.4, 239.1, 252.1, 284.1, 210.7, 291.2],
[200.4, 266.3, 298.3, 205.6, 305.1, 247.9, 285.4, 219.6],
[284.4, 274.0, 216.4, 210.8, 201.0, 223.1, 279.1, 224.8],
],
[
[255.8, 229.6, 292.6, 243.5, 304.0, 264.1, 285.4, 256.0],
[250.5, 262.1, 263.1, 281.3, 299.9, 289.5, 289.3, 235.6],
[226.9, 226.0, 218.7, 287.3, 227.2, 199.7, 283.5, 281.4],
[258.2, 237.4, 223.9, 214.6, 292.1, 280.1, 278.4, 233.0],
[309.7, 203.1, 299.0, 296.1, 250.3, 234.5, 231.0, 214.5],
],
[
[301.2, 216.9, 214.8, 310.8, 246.6, 201.3, 303.0, 306.4],
[284.8, 275.3, 303.3, 221.7, 262.8, 300.3, 264.8, 292.1],
[288.9, 219.7, 294.3, 206.1, 213.5, 234.4, 209.6, 269.4],
[282.5, 230.5, 248.4, 279.0, 249.4, 242.6, 286.0, 238.3],
[275.5, 236.7, 210.9, 296.1, 210.4, 209.1, 246.9, 298.5],
],
[
[213.3, 277.8, 289.6, 213.5, 242.6, 292.9, 273.9, 293.0],
[268.7, 300.8, 310.2, 274.6, 228.1, 248.0, 245.3, 214.7],
[234.9, 279.7, 306.4, 306.1, 301.8, 210.3, 297.3, 310.7],
[263.2, 293.6, 225.8, 311.1, 277.1, 248.0, 220.4, 308.1],
[243.4, 285.4, 290.6, 235.2, 211.5, 229.2, 250.9, 262.8],
],
[
[200.1, 290.2, 222.1, 274.7, 291.9, 226.3, 227.9, 210.4],
[217.9, 270.3, 238.3, 246.0, 285.9, 213.6, 310.6, 299.0],
[239.6, 309.7, 261.7, 273.4, 305.2, 243.0, 274.1, 255.3],
[245.9, 292.1, 216.8, 199.5, 309.2, 286.8, 289.9, 299.7],
[210.3, 208.9, 211.2, 245.7, 240.7, 249.1, 219.0, 256.6],
],
[
[204.6, 266.5, 294.7, 242.1, 282.9, 204.9, 241.7, 303.7],
[251.1, 220.4, 263.1, 211.7, 219.9, 240.0, 278.6, 240.3],
[308.8, 255.9, 258.2, 253.4, 279.9, 308.5, 229.5, 254.0],
[270.8, 278.9, 269.2, 272.7, 285.4, 206.3, 216.8, 238.3],
[305.4, 205.9, 306.8, 272.7, 234.2, 244.4, 277.6, 295.4],
],
[
[203.2, 246.8, 305.1, 289.9, 260.8, 274.0, 310.7, 299.0],
[292.7, 241.5, 255.5, 205.8, 212.6, 243.9, 287.4, 232.5],
[200.3, 301.1, 221.0, 311.2, 246.9, 290.8, 309.0, 286.5],
[214.0, 206.0, 254.6, 227.0, 217.5, 236.1, 213.1, 260.2],
[302.5, 230.8, 294.0, 235.9, 250.7, 209.4, 218.7, 266.0],
],
[
[244.6, 287.8, 273.8, 267.2, 237.6, 224.2, 206.1, 242.4],
[201.9, 243.0, 270.5, 308.8, 241.6, 243.9, 271.9, 250.5],
[216.1, 305.7, 257.5, 311.2, 223.2, 276.0, 213.0, 252.5],
[233.4, 221.0, 262.4, 257.7, 234.0, 225.8, 219.6, 308.1],
[282.1, 223.3, 284.9, 238.4, 235.8, 305.6, 308.6, 219.4],
],
[
[238.4, 201.7, 229.7, 224.8, 209.0, 280.5, 293.8, 260.4],
[273.7, 253.7, 299.4, 241.4, 229.3, 230.3, 265.6, 287.3],
[283.9, 265.2, 289.2, 284.3, 221.0, 306.3, 253.9, 246.3],
[241.3, 289.5, 212.4, 217.2, 201.7, 238.0, 265.2, 257.7],
[269.9, 213.4, 256.6, 290.1, 266.8, 278.9, 247.5, 286.8],
],
[
[304.5, 275.8, 216.5, 273.4, 220.4, 251.1, 255.9, 282.2],
[300.2, 274.3, 297.8, 229.3, 207.1, 297.7, 280.1, 216.4],
[287.9, 308.4, 283.0, 281.3, 222.6, 228.0, 257.0, 222.2],
[310.1, 263.2, 248.8, 243.0, 241.8, 219.4, 293.1, 277.2],
[299.7, 249.8, 241.3, 267.5, 290.6, 258.1, 261.7, 293.5],
],
[
[269.8, 297.4, 264.3, 253.0, 249.8, 228.4, 259.8, 278.6],
[288.0, 274.6, 299.8, 298.8, 248.1, 267.0, 287.7, 206.5],
[221.2, 235.6, 235.3, 252.1, 220.6, 215.5, 284.1, 237.9],
[292.9, 264.2, 297.6, 284.0, 304.3, 211.0, 271.5, 199.7],
[245.3, 293.9, 243.8, 268.9, 260.6, 262.5, 264.8, 211.0],
],
[
[267.9, 244.2, 269.1, 215.6, 284.3, 229.4, 307.6, 255.2],
[296.3, 280.6, 302.1, 302.1, 215.1, 206.6, 227.5, 263.2],
[253.7, 287.9, 280.9, 299.6, 206.1, 300.4, 307.1, 211.6],
[260.0, 276.3, 296.1, 285.9, 270.2, 243.4, 231.6, 267.1],
[303.5, 199.4, 307.1, 213.2, 236.5, 265.4, 249.6, 268.8],
],
[
[282.4, 298.8, 306.8, 311.1, 263.3, 239.8, 205.8, 199.4],
[247.0, 255.0, 220.5, 263.8, 254.0, 257.5, 299.2, 271.9],
[295.1, 253.6, 241.7, 214.4, 246.8, 293.7, 230.0, 285.2],
[298.6, 241.6, 217.5, 296.1, 265.1, 215.2, 249.0, 237.3],
[261.4, 235.1, 298.9, 248.9, 211.0, 235.1, 273.1, 255.3],
],
[
[215.0, 214.4, 204.8, 304.0, 235.6, 300.1, 234.4, 272.1],
[274.2, 209.0, 306.8, 229.5, 303.7, 284.1, 223.7, 272.6],
[266.5, 259.3, 264.1, 311.2, 305.4, 261.1, 262.7, 309.6],
[310.0, 308.1, 273.8, 250.9, 233.3, 209.8, 249.8, 273.8],
[200.0, 221.3, 294.8, 216.5, 206.1, 297.6, 211.8, 275.1],
],
[
[288.7, 234.6, 235.5, 205.8, 205.4, 214.5, 288.4, 254.0],
[200.5, 228.3, 244.9, 238.5, 263.1, 285.6, 292.7, 295.0],
[291.0, 246.3, 268.1, 208.8, 215.3, 278.1, 286.1, 290.0],
[258.5, 283.0, 279.5, 257.4, 234.2, 269.8, 256.3, 209.2],
[303.9, 206.7, 293.6, 272.0, 290.2, 288.6, 236.9, 268.3],
],
[
[217.3, 264.2, 249.4, 296.9, 208.4, 232.0, 288.0, 299.4],
[258.0, 218.9, 205.5, 279.4, 293.8, 260.4, 228.3, 224.0],
[210.6, 217.2, 241.7, 201.7, 215.0, 255.9, 241.0, 240.8],
[256.2, 305.1, 293.5, 253.9, 271.0, 248.8, 206.2, 305.7],
[275.0, 301.1, 284.7, 227.8, 252.3, 231.2, 214.9, 243.8],
],
[
[307.1, 206.8, 207.1, 260.3, 257.4, 310.1, 287.4, 242.8],
[291.5, 266.9, 302.8, 232.3, 283.1, 207.8, 249.3, 252.4],
[207.4, 222.4, 218.9, 266.7, 214.4, 227.9, 254.5, 310.7],
[232.6, 248.7, 257.5, 243.6, 261.9, 220.7, 294.0, 286.5],
[286.3, 262.3, 202.2, 279.2, 257.1, 230.2, 250.6, 225.3],
],
[
[299.3, 268.7, 296.3, 199.9, 254.3, 295.7, 275.3, 271.8],
[250.6, 226.6, 301.3, 207.4, 242.9, 273.1, 216.1, 252.0],
[275.8, 291.3, 270.6, 282.9, 250.5, 291.3, 260.6, 310.1],
[253.2, 221.3, 281.1, 283.0, 268.0, 263.9, 224.3, 284.0],
[236.5, 218.9, 229.2, 227.9, 226.2, 247.3, 298.1, 226.8],
],
[
[215.9, 289.9, 222.7, 270.5, 247.7, 200.7, 219.0, 252.4],
[202.8, 278.9, 259.1, 207.2, 299.8, 249.2, 259.8, 200.7],
[249.3, 205.9, 303.5, 304.2, 216.8, 308.1, 201.5, 241.9],
[256.9, 264.6, 227.4, 229.5, 294.2, 271.0, 254.5, 274.6],
[268.1, 199.3, 275.7, 289.0, 205.0, 218.2, 270.6, 280.4],
],
[
[290.2, 274.0, 281.7, 263.1, 202.1, 199.7, 228.1, 260.0],
[248.7, 305.0, 306.2, 255.3, 298.0, 254.6, 276.0, 249.4],
[217.2, 272.4, 278.8, 252.1, 236.4, 223.6, 201.8, 300.9],
[302.4, 305.0, 273.1, 261.9, 241.4, 285.0, 275.1, 210.2],
[242.1, 208.1, 258.0, 222.2, 244.7, 236.9, 216.0, 260.5],
],
[
[239.9, 220.7, 246.1, 209.0, 247.9, 247.4, 227.1, 291.7],
[205.5, 287.2, 305.5, 238.8, 291.1, 250.0, 202.0, 234.0],
[275.4, 210.0, 276.8, 287.3, 281.2, 279.6, 306.0, 228.3],
[301.9, 295.9, 298.4, 304.0, 227.9, 301.7, 296.2, 247.4],
[210.1, 212.0, 275.1, 271.8, 254.0, 274.8, 283.8, 286.6],
],
],
units="K",
dtype="f8",
)
f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2"))
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"standard_name": "time", "units": "days since 1959-01-01"}
)
c.nc_set_variable("time")
data = Data(
[
349.5,
380.5,
410.5,
440.5,
471.0,
501.5,
532.0,
562.5,
593.5,
624.0,
654.5,
685.0,
715.5,
746.5,
776.0,
805.5,
836.0,
866.5,
897.0,
927.5,
958.5,
989.0,
1019.5,
1050.0,
1080.5,
1111.5,
1141.0,
1170.5,
1201.0,
1231.5,
1262.0,
1292.5,
1323.5,
1354.0,
1384.5,
1415.0,
],
units="days since 1959-01-01",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("bounds")
data = Data(
[
[334.0, 365.0],
[365.0, 396.0],
[396.0, 425.0],
[425.0, 456.0],
[456.0, 486.0],
[486.0, 517.0],
[517.0, 547.0],
[547.0, 578.0],
[578.0, 609.0],
[609.0, 639.0],
[639.0, 670.0],
[670.0, 700.0],
[700.0, 731.0],
[731.0, 762.0],
[762.0, 790.0],
[790.0, 821.0],
[821.0, 851.0],
[851.0, 882.0],
[882.0, 912.0],
[912.0, 943.0],
[943.0, 974.0],
[974.0, 1004.0],
[1004.0, 1035.0],
[1035.0, 1065.0],
[1065.0, 1096.0],
[1096.0, 1127.0],
[1127.0, 1155.0],
[1155.0, 1186.0],
[1186.0, 1216.0],
[1216.0, 1247.0],
[1247.0, 1277.0],
[1277.0, 1308.0],
[1308.0, 1339.0],
[1339.0, 1369.0],
[1369.0, 1400.0],
[1400.0, 1430.0],
],
units="days since 1959-01-01",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="dimensioncoordinate0", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_north", "standard_name": "latitude"}
)
c.nc_set_variable("lat")
data = Data(
[-75.0, -45.0, 0.0, 45.0, 75.0], units="degrees_north", dtype="f8"
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lat_bnds")
data = Data(
[
[-90.0, -60.0],
[-60.0, -30.0],
[-30.0, 30.0],
[30.0, 60.0],
[60.0, 90.0],
],
units="degrees_north",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate1", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_east", "standard_name": "longitude"}
)
c.nc_set_variable("lon")
data = Data(
[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
units="degrees_east",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lon_bnds")
data = Data(
[
[0.0, 45.0],
[45.0, 90.0],
[90.0, 135.0],
[135.0, 180.0],
[180.0, 225.0],
[225.0, 270.0],
[270.0, 315.0],
[315.0, 360.0],
],
units="degrees_east",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis2",), key="dimensioncoordinate2", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties({"standard_name": "air_pressure", "units": "hPa"})
c.nc_set_variable("air_pressure")
data = Data([850.0], units="hPa", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis3",), key="dimensioncoordinate3", copy=False
)
# cell_method
c = CellMethod()
c.set_method("mean")
c.set_axes("area")
f.set_construct(c)
elif n == 5:
f = Field()
f.set_properties(
{
"Conventions": "CF-" + CF(),
"standard_name": "air_potential_temperature",
"units": "K",
}
)
f.nc_set_variable("air_potential_temperature")
f.nc_set_global_attributes({"Conventions": None})
# domain_axis
c = DomainAxis(size=118)
c.nc_set_dimension("time")
f.set_construct(c, key="domainaxis0")
# domain_axis
c = DomainAxis(size=5)
c.nc_set_dimension("lat")
f.set_construct(c, key="domainaxis1")
# domain_axis
c = DomainAxis(size=8)
c.nc_set_dimension("lon")
f.set_construct(c, key="domainaxis2")
# domain_axis
c = DomainAxis(size=1)
f.set_construct(c, key="domainaxis3")
# field data
data = Data(
[
[
[274.0, 282.2, 267.4, 275.3, 274.3, 280.0, 281.9, 266.7],
[263.9, 268.6, 276.9, 275.8, 271.1, 277.3, 270.2, 278.0],
[266.5, 267.9, 267.8, 268.2, 257.7, 263.5, 273.9, 281.0],
[274.9, 265.2, 284.2, 275.5, 254.3, 277.4, 258.1, 273.3],
[279.9, 291.9, 273.9, 285.8, 277.1, 271.3, 273.4, 261.8],
],
[
[292.2, 275.7, 286.9, 287.2, 269.2, 266.1, 286.4, 272.4],
[276.9, 269.2, 290.9, 283.1, 268.2, 274.0, 267.8, 253.2],
[285.5, 288.9, 261.7, 278.6, 287.6, 269.0, 277.2, 279.1],
[264.1, 256.4, 278.1, 272.1, 271.4, 277.2, 271.2, 274.5],
[277.5, 290.1, 282.4, 264.7, 277.8, 257.5, 261.3, 284.6],
],
[
[277.2, 279.8, 259.0, 267.0, 277.9, 282.0, 268.7, 277.7],
[280.2, 256.7, 264.0, 272.8, 284.2, 262.6, 292.9, 273.4],
[256.3, 276.7, 280.7, 258.6, 267.7, 260.7, 273.3, 273.7],
[278.9, 279.4, 276.5, 272.7, 271.3, 260.1, 287.4, 278.9],
[288.7, 278.6, 284.2, 277.1, 283.8, 283.5, 262.4, 268.1],
],
[
[266.4, 277.7, 279.8, 271.1, 257.1, 286.9, 277.9, 261.5],
[277.6, 273.5, 261.1, 280.8, 280.1, 266.0, 270.8, 256.0],
[281.0, 290.1, 263.1, 274.8, 288.2, 277.2, 278.8, 260.4],
[248.1, 285.8, 274.2, 268.1, 279.6, 278.1, 262.3, 286.0],
[274.3, 272.8, 276.4, 281.7, 258.1, 275.2, 259.4, 279.5],
],
[
[266.7, 259.6, 257.7, 265.6, 259.3, 256.6, 255.7, 285.6],
[283.4, 274.8, 268.7, 277.2, 265.2, 281.5, 282.5, 258.1],
[284.2, 291.0, 268.9, 260.0, 281.3, 266.9, 274.6, 289.2],
[279.4, 284.7, 266.6, 285.6, 275.1, 284.8, 286.4, 284.3],
[269.1, 273.3, 272.8, 279.9, 283.2, 285.5, 258.1, 261.7],
],
[
[296.4, 281.1, 278.6, 273.2, 288.7, 281.3, 265.6, 284.2],
[276.8, 271.7, 274.4, 271.1, 279.9, 265.4, 292.5, 259.7],
[278.7, 279.6, 277.0, 270.7, 266.1, 265.2, 272.5, 278.1],
[284.0, 254.0, 279.7, 291.1, 282.4, 279.3, 257.6, 285.1],
[272.2, 283.6, 270.0, 271.9, 294.8, 260.4, 275.9, 275.5],
],
[
[273.5, 273.9, 298.2, 275.1, 268.2, 260.2, 260.5, 272.5],
[264.7, 241.2, 261.1, 260.3, 272.8, 285.2, 283.7, 275.5],
[273.2, 256.0, 282.9, 272.0, 253.9, 291.0, 267.5, 272.1],
[259.6, 262.7, 278.5, 271.6, 260.1, 273.3, 286.1, 267.7],
[266.3, 262.5, 273.4, 278.9, 274.9, 267.1, 274.6, 286.1],
],
[
[278.1, 269.1, 271.4, 266.1, 258.6, 281.9, 256.9, 281.7],
[275.0, 281.3, 256.7, 252.4, 281.5, 273.6, 259.1, 266.1],
[264.1, 266.0, 278.9, 267.4, 286.4, 281.7, 270.2, 266.1],
[274.2, 261.9, 270.1, 291.9, 292.1, 277.6, 283.6, 279.4],
[281.4, 270.6, 255.5, 269.4, 264.8, 262.4, 275.3, 286.9],
],
[
[269.6, 269.8, 270.8, 270.1, 277.6, 271.0, 263.6, 274.5],
[259.0, 251.2, 295.4, 262.1, 262.6, 283.3, 269.0, 268.1],
[286.0, 275.6, 264.2, 265.3, 263.7, 268.6, 269.9, 281.2],
[269.6, 274.9, 256.7, 284.1, 271.1, 254.8, 258.1, 273.0],
[269.2, 271.2, 275.3, 279.8, 278.7, 278.8, 280.5, 285.8],
],
[
[285.9, 246.7, 255.7, 282.1, 258.9, 262.6, 300.0, 288.3],
[279.2, 266.6, 271.0, 258.5, 257.9, 274.8, 264.4, 267.4],
[282.0, 266.8, 280.1, 289.6, 278.2, 282.2, 288.7, 273.6],
[279.2, 273.1, 266.7, 271.5, 275.4, 278.2, 269.7, 291.6],
[281.1, 282.1, 271.3, 260.0, 275.7, 291.4, 266.6, 265.2],
],
[
[278.5, 263.3, 285.9, 255.2, 283.8, 288.7, 282.8, 262.9],
[272.6, 288.2, 257.5, 269.8, 273.6, 266.7, 276.2, 275.5],
[261.8, 274.2, 278.3, 273.3, 268.8, 278.5, 273.0, 276.7],
[276.2, 271.2, 284.8, 272.2, 274.7, 253.6, 268.7, 273.1],
[285.6, 270.2, 271.4, 285.5, 248.1, 273.1, 294.9, 272.9],
],
[
[269.3, 252.5, 271.3, 268.2, 270.8, 282.2, 275.0, 274.2],
[257.5, 295.6, 278.0, 284.6, 277.3, 277.3, 273.1, 278.8],
[279.8, 286.5, 259.5, 287.2, 276.8, 282.0, 265.9, 283.8],
[276.2, 282.4, 252.7, 265.5, 252.9, 274.6, 265.5, 274.1],
[269.8, 267.4, 292.5, 256.7, 274.3, 278.9, 270.3, 252.5],
],
[
[287.4, 275.6, 287.9, 284.6, 281.7, 280.5, 267.8, 283.9],
[292.0, 286.4, 276.1, 277.8, 280.8, 268.4, 281.6, 262.4],
[260.7, 265.9, 274.9, 275.9, 277.3, 286.2, 296.4, 280.1],
[251.1, 283.6, 265.0, 280.6, 254.8, 251.6, 275.2, 279.2],
[273.3, 272.0, 254.3, 287.5, 275.3, 282.1, 272.6, 266.8],
],
[
[279.6, 268.3, 280.6, 267.5, 260.8, 268.2, 276.2, 247.4],
[268.1, 275.0, 278.7, 265.8, 283.8, 271.6, 284.5, 276.6],
[269.7, 270.1, 274.9, 252.2, 285.5, 254.3, 266.2, 270.6],
[274.1, 273.7, 269.4, 262.9, 281.7, 282.7, 270.0, 264.8],
[280.7, 265.3, 291.6, 281.2, 273.1, 273.5, 291.3, 274.4],
],
[
[270.4, 273.8, 260.8, 262.9, 268.9, 278.1, 261.7, 257.3],
[262.4, 261.2, 265.5, 276.6, 264.4, 271.6, 272.9, 273.3],
[247.1, 271.7, 272.0, 279.3, 269.3, 255.2, 279.9, 272.8],
[291.6, 279.5, 263.2, 285.0, 263.5, 257.0, 274.2, 270.1],
[261.5, 270.7, 280.2, 264.5, 267.0, 260.3, 277.4, 288.1],
],
[
[261.5, 285.4, 275.3, 276.7, 279.4, 269.1, 264.1, 254.2],
[262.1, 272.5, 262.2, 275.6, 276.1, 269.9, 263.3, 281.2],
[287.1, 276.5, 285.9, 267.1, 274.2, 269.0, 265.3, 281.2],
[265.7, 278.5, 251.2, 269.6, 263.7, 260.4, 264.8, 280.3],
[269.0, 269.8, 262.3, 277.5, 269.8, 269.3, 262.7, 266.8],
],
[
[287.6, 279.1, 268.2, 285.1, 286.4, 260.3, 267.4, 275.6],
[263.2, 280.9, 271.3, 271.5, 263.9, 280.2, 265.9, 283.9],
[272.8, 280.7, 272.9, 263.4, 264.2, 280.2, 289.7, 279.0],
[279.0, 279.7, 285.9, 293.0, 299.2, 268.6, 274.9, 279.1],
[261.8, 277.4, 275.8, 262.5, 275.9, 265.9, 284.6, 264.7],
],
[
[265.2, 284.8, 277.7, 267.9, 265.4, 283.8, 276.7, 274.6],
[274.6, 273.5, 285.1, 268.8, 272.6, 268.6, 284.2, 288.1],
[268.9, 271.7, 274.2, 280.7, 288.0, 280.6, 269.8, 278.0],
[263.6, 261.7, 279.2, 271.7, 280.5, 246.8, 263.4, 266.8],
[268.9, 266.0, 269.0, 273.5, 287.7, 272.5, 278.3, 269.5],
],
[
[265.0, 269.2, 275.2, 263.1, 293.9, 275.4, 256.5, 262.7],
[272.2, 276.3, 286.5, 255.0, 264.8, 287.4, 277.6, 249.9],
[283.1, 278.2, 285.0, 268.0, 277.9, 259.3, 261.4, 279.2],
[278.7, 277.0, 254.3, 281.4, 283.8, 266.5, 260.9, 267.0],
[282.3, 273.5, 278.7, 290.6, 274.6, 284.2, 281.4, 284.3],
],
[
[277.0, 268.1, 269.3, 272.3, 286.1, 266.7, 294.1, 274.9],
[261.3, 265.1, 283.2, 258.9, 278.1, 275.1, 284.4, 287.3],
[264.6, 274.7, 270.3, 261.1, 274.0, 287.4, 267.2, 277.8],
[276.2, 284.9, 281.6, 265.8, 253.0, 270.2, 276.5, 282.8],
[244.8, 282.7, 265.0, 261.4, 277.6, 283.7, 285.7, 267.3],
],
[
[276.9, 275.1, 256.0, 270.9, 285.0, 271.6, 272.0, 268.9],
[244.3, 266.3, 285.2, 266.5, 279.4, 271.0, 267.2, 274.7],
[275.0, 264.0, 280.7, 286.7, 275.2, 280.2, 282.1, 271.0],
[272.8, 265.3, 278.5, 283.8, 291.0, 280.9, 266.6, 269.2],
[287.0, 263.0, 269.0, 263.4, 267.3, 256.1, 280.7, 263.3],
],
[
[264.8, 281.0, 286.5, 260.8, 285.7, 262.2, 260.5, 267.2],
[277.2, 285.5, 263.2, 259.4, 266.5, 271.3, 272.8, 259.7],
[273.8, 286.1, 271.7, 263.6, 286.8, 270.7, 277.0, 262.0],
[279.0, 262.3, 283.9, 257.4, 279.4, 261.5, 276.1, 264.8],
[266.3, 268.7, 264.2, 279.7, 287.5, 271.9, 262.9, 272.0],
],
[
[288.8, 263.8, 278.6, 276.3, 269.9, 247.4, 258.2, 286.5],
[284.4, 262.1, 262.1, 265.7, 275.7, 265.7, 269.6, 281.1],
[259.3, 288.6, 267.9, 268.0, 274.9, 274.8, 255.8, 270.7],
[270.7, 276.4, 288.7, 276.5, 279.7, 251.3, 274.0, 281.2],
[258.4, 277.9, 262.8, 272.4, 286.9, 277.0, 279.6, 291.4],
],
[
[282.9, 289.5, 275.3, 281.6, 271.8, 275.7, 282.4, 265.0],
[250.2, 288.4, 278.6, 269.3, 264.3, 285.2, 259.2, 263.9],
[271.0, 280.5, 272.9, 269.5, 277.2, 276.4, 247.4, 302.6],
[276.1, 254.1, 300.1, 279.7, 265.7, 270.9, 281.0, 264.6],
[260.8, 258.2, 287.8, 277.3, 276.3, 258.8, 283.3, 273.4],
],
[
[287.8, 276.5, 281.3, 290.4, 248.3, 279.4, 265.3, 277.0],
[262.0, 266.8, 274.4, 273.1, 287.7, 268.5, 276.0, 275.8],
[280.5, 281.0, 258.2, 268.6, 266.0, 274.2, 260.6, 257.3],
[274.1, 265.9, 263.6, 267.9, 277.5, 277.1, 264.6, 275.6],
[284.1, 267.1, 272.9, 262.4, 264.9, 283.6, 270.7, 274.8],
],
[
[262.7, 275.7, 276.7, 269.0, 274.4, 266.2, 270.8, 258.2],
[262.2, 271.5, 276.8, 283.7, 287.6, 278.3, 268.9, 262.6],
[280.8, 269.7, 273.0, 275.2, 260.9, 246.2, 288.0, 274.2],
[264.8, 288.0, 258.0, 270.1, 276.8, 280.9, 271.2, 274.1],
[259.9, 284.3, 292.6, 273.7, 270.2, 290.0, 272.4, 278.5],
],
[
[255.0, 268.8, 260.8, 280.4, 269.7, 275.9, 282.3, 279.8],
[276.1, 284.3, 275.5, 263.6, 254.1, 265.5, 271.2, 274.5],
[281.3, 269.2, 281.2, 292.6, 284.0, 251.0, 271.4, 276.0],
[278.0, 266.5, 282.5, 272.1, 283.1, 270.0, 281.2, 250.7],
[279.9, 271.5, 286.0, 289.7, 259.0, 279.6, 264.3, 286.0],
],
[
[278.7, 270.2, 269.1, 263.8, 285.6, 285.3, 252.7, 271.3],
[282.5, 278.2, 285.7, 267.2, 271.0, 278.2, 278.1, 270.0],
[282.5, 261.9, 268.3, 278.6, 279.8, 276.1, 275.5, 272.7],
[273.3, 286.7, 297.1, 277.4, 272.2, 268.7, 289.2, 274.8],
[270.0, 278.6, 277.3, 269.1, 255.0, 277.0, 271.3, 263.4],
],
[
[265.3, 270.9, 271.1, 276.2, 260.0, 277.5, 267.1, 259.3],
[259.2, 271.4, 287.1, 288.8, 265.3, 274.7, 277.0, 261.0],
[265.4, 283.4, 272.0, 272.8, 276.2, 271.8, 270.6, 280.9],
[283.6, 270.2, 271.2, 276.5, 268.7, 274.7, 275.7, 276.1],
[277.6, 279.7, 251.2, 285.2, 268.9, 275.1, 284.2, 271.5],
],
[
[267.4, 261.0, 283.3, 269.1, 272.5, 263.9, 290.3, 257.6],
[264.5, 277.0, 282.8, 267.8, 286.2, 290.0, 283.1, 291.9],
[279.4, 261.9, 279.5, 262.4, 278.8, 278.7, 267.4, 272.1],
[274.6, 269.4, 290.0, 282.7, 274.5, 271.4, 268.4, 275.8],
[256.1, 264.2, 284.7, 267.2, 271.0, 263.2, 276.9, 277.7],
],
[
[262.4, 266.1, 272.0, 279.0, 286.3, 259.2, 278.4, 264.0],
[283.9, 267.5, 276.3, 264.9, 262.6, 277.1, 268.6, 279.2],
[271.2, 257.6, 266.2, 299.8, 279.7, 270.3, 293.7, 256.1],
[293.1, 290.4, 282.9, 283.2, 278.9, 255.9, 266.3, 272.9],
[271.2, 255.9, 273.1, 254.2, 267.5, 272.5, 270.5, 281.1],
],
[
[267.8, 271.9, 276.9, 265.0, 260.1, 291.9, 287.7, 272.5],
[270.0, 292.6, 282.1, 275.1, 274.0, 270.6, 280.5, 285.6],
[273.4, 270.6, 258.3, 267.3, 260.4, 284.7, 259.4, 296.0],
[280.9, 270.6, 273.0, 268.5, 282.0, 295.1, 283.0, 259.2],
[286.5, 267.2, 260.9, 260.6, 276.0, 276.3, 260.6, 273.8],
],
[
[248.9, 284.4, 284.9, 272.2, 288.7, 266.3, 272.7, 279.8],
[274.7, 278.5, 275.1, 260.0, 277.1, 276.1, 278.0, 280.2],
[267.5, 253.5, 266.4, 267.0, 283.0, 269.9, 265.7, 248.3],
[270.6, 266.6, 260.1, 278.7, 293.7, 274.4, 273.6, 284.3],
[291.1, 287.7, 293.3, 272.9, 289.3, 271.5, 264.8, 272.1],
],
[
[275.5, 271.5, 265.2, 298.2, 274.5, 263.3, 275.7, 285.8],
[284.6, 281.6, 271.0, 274.6, 262.3, 266.5, 268.1, 272.8],
[256.3, 262.6, 256.6, 292.2, 273.1, 287.6, 284.1, 263.4],
[292.0, 275.0, 260.0, 270.3, 258.7, 266.5, 273.1, 265.2],
[270.5, 273.5, 260.0, 280.1, 283.2, 282.2, 286.3, 280.6],
],
[
[261.6, 286.0, 288.0, 286.7, 267.7, 265.3, 272.0, 256.4],
[271.8, 266.4, 260.4, 272.6, 268.7, 262.2, 269.6, 269.9],
[275.9, 281.0, 285.7, 271.3, 265.1, 263.6, 272.1, 264.9],
[298.8, 266.1, 269.2, 267.4, 277.4, 264.1, 262.9, 260.6],
[279.5, 263.5, 267.1, 259.3, 286.7, 267.9, 268.7, 276.2],
],
[
[275.1, 275.0, 256.0, 261.4, 273.9, 273.7, 263.5, 266.9],
[263.9, 284.4, 282.9, 261.3, 275.6, 270.6, 258.6, 271.9],
[257.9, 272.3, 275.2, 272.2, 275.0, 289.1, 266.7, 276.6],
[283.9, 272.3, 270.0, 260.1, 270.5, 275.9, 275.6, 273.8],
[273.5, 269.5, 261.0, 278.1, 284.3, 262.6, 266.0, 271.4],
],
[
[280.2, 272.6, 271.9, 283.6, 258.8, 274.2, 260.2, 270.7],
[276.4, 279.2, 282.1, 276.6, 278.5, 263.4, 274.7, 278.0],
[286.4, 265.1, 279.5, 243.6, 279.8, 281.4, 266.6, 276.4],
[265.8, 274.9, 263.3, 278.6, 289.6, 260.3, 267.0, 265.7],
[266.1, 263.7, 278.3, 267.4, 270.1, 253.0, 280.0, 275.1],
],
[
[266.6, 265.7, 272.9, 273.6, 260.6, 271.8, 284.2, 285.6],
[268.4, 277.9, 268.6, 265.6, 259.7, 264.3, 272.2, 265.5],
[280.3, 283.1, 276.5, 261.6, 264.8, 267.9, 270.3, 282.4],
[270.6, 268.4, 254.2, 288.3, 281.0, 258.9, 273.9, 283.1],
[270.0, 267.0, 260.7, 275.1, 285.3, 279.1, 261.6, 270.3],
],
[
[275.1, 262.0, 269.0, 280.9, 275.9, 271.9, 276.4, 275.0],
[285.3, 280.8, 269.3, 275.2, 276.8, 280.6, 290.2, 255.7],
[264.8, 280.8, 279.2, 275.2, 261.6, 280.8, 267.7, 282.6],
[259.4, 280.5, 264.9, 254.4, 269.2, 287.8, 278.7, 266.8],
[290.6, 278.2, 276.7, 261.8, 277.6, 264.4, 279.3, 258.9],
],
[
[265.9, 287.0, 267.1, 267.3, 252.9, 269.2, 271.2, 252.7],
[262.0, 293.8, 276.6, 264.1, 270.0, 276.3, 277.2, 269.3],
[292.2, 270.0, 266.5, 260.7, 276.7, 284.4, 276.2, 269.0],
[260.5, 273.0, 269.1, 282.8, 261.4, 271.9, 275.2, 274.6],
[285.1, 272.6, 263.9, 270.1, 287.4, 282.0, 279.4, 264.7],
],
[
[272.7, 257.4, 285.7, 260.9, 262.0, 287.7, 277.6, 277.3],
[279.9, 280.4, 278.3, 272.9, 278.8, 272.5, 282.9, 260.9],
[267.3, 274.3, 265.2, 287.9, 286.6, 269.5, 283.9, 265.8],
[274.3, 265.8, 276.6, 271.2, 276.8, 287.1, 257.2, 269.3],
[283.4, 269.9, 278.7, 272.3, 272.6, 268.4, 280.7, 266.7],
],
[
[262.4, 278.1, 257.7, 280.3, 274.5, 285.5, 272.5, 283.3],
[268.8, 269.6, 278.0, 269.5, 277.7, 266.9, 285.6, 268.4],
[269.3, 287.8, 270.0, 271.4, 288.3, 285.3, 275.5, 300.0],
[273.6, 261.2, 284.5, 276.2, 271.4, 276.6, 266.2, 263.0],
[274.5, 275.4, 269.7, 274.6, 271.2, 260.3, 275.3, 265.1],
],
[
[281.5, 288.1, 283.9, 275.4, 265.8, 271.4, 261.6, 260.1],
[257.7, 278.1, 286.9, 276.0, 271.3, 286.2, 277.2, 275.2],
[266.6, 278.6, 256.8, 264.8, 278.1, 261.7, 269.6, 278.0],
[283.8, 290.7, 274.1, 267.2, 258.9, 282.4, 292.4, 310.1],
[275.8, 280.5, 250.5, 276.1, 269.2, 294.5, 279.6, 268.5],
],
[
[280.2, 268.9, 273.2, 270.7, 285.5, 276.7, 263.0, 255.3],
[276.8, 263.3, 266.9, 292.5, 260.9, 278.0, 278.0, 263.6],
[283.3, 294.0, 282.1, 277.8, 282.4, 270.7, 268.2, 285.4],
[266.9, 272.5, 288.0, 266.4, 279.6, 257.7, 288.5, 267.1],
[267.6, 267.1, 276.3, 268.3, 266.4, 269.1, 270.1, 274.4],
],
[
[294.5, 269.9, 284.3, 276.0, 278.7, 289.9, 272.1, 273.0],
[274.5, 260.5, 283.4, 261.7, 281.3, 272.5, 268.9, 268.8],
[271.3, 277.3, 279.4, 269.1, 274.3, 274.2, 281.9, 269.7],
[280.2, 267.1, 284.0, 270.8, 276.6, 271.6, 271.5, 267.7],
[266.9, 272.4, 267.8, 279.6, 262.5, 253.3, 265.8, 256.1],
],
[
[269.9, 282.7, 277.3, 270.7, 280.0, 276.0, 278.2, 257.2],
[271.8, 265.5, 271.6, 274.9, 272.9, 289.5, 258.8, 260.8],
[287.4, 266.8, 285.1, 275.6, 292.4, 262.5, 269.3, 279.0],
[269.9, 268.1, 259.4, 274.3, 290.3, 271.1, 290.3, 276.5],
[272.8, 264.2, 264.4, 277.6, 264.3, 290.3, 265.4, 266.4],
],
[
[268.4, 277.8, 287.6, 273.6, 281.8, 262.4, 265.5, 289.1],
[289.5, 264.5, 275.2, 256.3, 259.8, 290.0, 260.7, 272.7],
[281.6, 278.4, 266.6, 264.4, 264.6, 264.2, 281.8, 271.2],
[285.1, 282.4, 289.6, 262.2, 285.0, 273.2, 257.9, 280.2],
[290.3, 284.4, 299.6, 266.6, 261.0, 273.5, 274.5, 284.6],
],
[
[270.8, 282.5, 290.8, 266.6, 285.0, 275.8, 290.5, 268.7],
[281.1, 283.5, 279.0, 272.2, 276.8, 280.3, 272.9, 275.6],
[283.8, 269.0, 276.2, 265.1, 283.9, 285.1, 280.4, 273.9],
[271.5, 280.2, 280.5, 278.4, 265.4, 271.7, 287.2, 261.4],
[290.3, 251.7, 269.1, 279.9, 281.1, 270.9, 259.6, 284.7],
],
[
[279.0, 264.6, 274.8, 282.1, 271.7, 254.4, 268.8, 271.1],
[293.9, 283.5, 265.1, 263.8, 278.4, 263.5, 270.8, 270.8],
[266.6, 257.7, 277.7, 275.2, 257.4, 269.6, 289.5, 269.2],
[274.4, 287.4, 277.3, 257.5, 269.0, 271.2, 272.6, 272.8],
[272.5, 271.5, 260.6, 274.3, 274.7, 262.7, 260.6, 253.6],
],
[
[278.7, 267.4, 279.0, 271.9, 269.8, 260.8, 284.9, 282.4],
[288.6, 262.9, 260.4, 272.2, 271.1, 280.6, 273.7, 282.8],
[272.1, 264.7, 284.6, 299.6, 258.7, 265.3, 269.5, 276.7],
[286.5, 271.9, 282.3, 266.2, 277.7, 260.4, 267.9, 287.9],
[269.8, 255.4, 276.4, 281.8, 266.6, 275.7, 288.3, 265.8],
],
[
[261.3, 245.6, 265.9, 267.4, 266.7, 276.5, 272.7, 256.9],
[264.1, 285.6, 278.5, 269.2, 268.6, 259.6, 253.3, 260.1],
[272.9, 266.8, 278.3, 280.0, 283.0, 281.2, 276.7, 275.0],
[273.1, 261.5, 276.6, 272.7, 280.9, 287.7, 273.2, 274.7],
[285.0, 271.5, 271.9, 264.1, 278.7, 273.1, 271.5, 255.9],
],
[
[264.6, 288.9, 278.1, 253.0, 281.4, 294.3, 252.1, 260.7],
[273.0, 275.1, 283.2, 256.1, 284.4, 283.8, 274.2, 288.1],
[260.1, 269.9, 277.9, 281.7, 282.4, 280.8, 278.3, 278.7],
[275.0, 274.1, 281.0, 269.8, 276.6, 276.2, 263.7, 264.0],
[280.4, 280.4, 257.8, 249.8, 275.1, 265.2, 261.9, 285.8],
],
[
[269.3, 274.1, 277.9, 265.4, 272.4, 274.9, 272.8, 270.7],
[276.4, 280.4, 294.0, 260.7, 281.6, 271.0, 283.6, 277.4],
[278.9, 257.9, 268.4, 279.0, 278.0, 276.4, 260.1, 260.9],
[282.2, 272.1, 249.6, 289.8, 269.7, 280.0, 280.9, 266.1],
[251.9, 269.4, 270.0, 278.7, 265.4, 271.9, 282.9, 256.7],
],
[
[258.5, 291.3, 274.2, 273.1, 276.9, 280.7, 275.0, 259.9],
[262.6, 266.9, 261.4, 274.7, 267.8, 296.9, 271.9, 261.0],
[266.9, 273.3, 274.6, 274.2, 264.5, 271.5, 288.2, 289.1],
[270.4, 288.9, 276.0, 268.6, 277.1, 277.8, 277.2, 284.2],
[279.6, 265.8, 280.9, 295.2, 255.6, 269.8, 265.8, 259.3],
],
[
[261.9, 275.9, 262.0, 273.1, 268.1, 277.6, 265.8, 285.0],
[260.2, 280.5, 262.2, 263.6, 264.0, 275.7, 262.7, 286.0],
[250.8, 284.8, 260.6, 272.9, 290.0, 264.2, 266.3, 264.6],
[278.6, 292.3, 272.7, 284.3, 285.9, 278.1, 273.1, 272.0],
[248.7, 268.6, 280.3, 274.9, 272.8, 298.1, 272.7, 281.5],
],
[
[282.3, 279.1, 265.4, 269.3, 258.5, 264.1, 272.3, 279.0],
[268.5, 274.1, 265.4, 256.7, 279.8, 275.6, 270.7, 285.5],
[269.1, 297.5, 283.9, 244.9, 258.4, 272.7, 265.2, 265.2],
[289.8, 281.7, 278.2, 299.5, 281.1, 270.7, 269.4, 275.4],
[273.0, 287.2, 272.5, 274.0, 287.7, 275.6, 278.4, 266.4],
],
[
[287.8, 302.7, 261.9, 270.8, 285.9, 285.5, 262.4, 274.5],
[281.9, 273.0, 268.4, 265.0, 279.0, 258.6, 266.1, 280.5],
[274.5, 277.5, 283.3, 266.4, 287.0, 270.0, 265.0, 269.0],
[287.4, 257.5, 269.6, 275.0, 278.6, 287.2, 279.4, 282.2],
[261.1, 265.7, 281.6, 271.7, 278.0, 272.4, 278.9, 264.4],
],
[
[280.2, 269.2, 247.1, 286.4, 273.2, 270.5, 284.3, 264.1],
[280.4, 264.9, 274.1, 275.1, 273.8, 286.6, 286.8, 276.2],
[264.1, 274.5, 276.3, 263.8, 277.7, 265.6, 269.1, 271.3],
[269.9, 287.5, 283.1, 267.8, 272.5, 272.0, 268.1, 291.4],
[267.6, 290.6, 277.0, 283.0, 285.9, 261.4, 274.7, 275.9],
],
[
[295.2, 298.9, 273.2, 274.7, 268.2, 274.9, 273.0, 277.7],
[261.1, 283.1, 261.0, 295.8, 284.1, 276.2, 280.9, 281.2],
[265.5, 277.7, 270.3, 260.5, 252.6, 273.5, 271.3, 278.4],
[286.9, 266.0, 277.0, 277.8, 280.6, 260.7, 277.7, 272.2],
[272.3, 291.7, 260.2, 272.0, 286.3, 276.4, 285.2, 260.8],
],
[
[285.7, 275.2, 279.7, 266.4, 269.5, 273.6, 272.7, 274.0],
[276.0, 265.2, 278.8, 271.5, 288.0, 273.8, 269.9, 254.7],
[262.7, 258.9, 279.5, 265.9, 276.1, 283.3, 286.1, 286.4],
[268.8, 272.1, 281.3, 269.7, 255.5, 273.0, 273.2, 275.1],
[255.8, 282.3, 262.0, 276.3, 289.3, 270.5, 265.6, 267.7],
],
[
[293.2, 280.3, 295.2, 273.1, 263.9, 266.4, 278.2, 279.8],
[283.8, 280.8, 280.5, 263.9, 279.7, 269.4, 246.4, 263.9],
[271.1, 257.8, 266.7, 263.8, 264.6, 256.0, 273.8, 298.3],
[278.6, 282.3, 267.9, 265.2, 277.1, 273.2, 283.6, 277.0],
[290.1, 275.6, 265.0, 267.6, 265.7, 263.7, 277.6, 290.6],
],
[
[275.3, 294.0, 267.9, 268.1, 268.5, 286.1, 289.5, 261.5],
[263.4, 276.0, 257.0, 289.8, 280.5, 262.4, 279.0, 272.5],
[280.0, 272.6, 279.6, 258.1, 271.4, 271.1, 290.0, 241.2],
[268.4, 290.5, 281.8, 276.8, 277.6, 282.8, 274.1, 267.6],
[275.6, 272.5, 260.1, 261.6, 264.9, 266.8, 277.0, 256.7],
],
[
[263.9, 274.4, 279.7, 260.2, 271.7, 270.0, 272.9, 271.1],
[281.6, 293.4, 286.1, 277.4, 275.0, 286.5, 279.0, 267.1],
[282.3, 272.2, 283.8, 277.5, 292.2, 287.3, 275.5, 274.4],
[278.2, 267.3, 276.3, 268.8, 264.1, 257.0, 278.8, 282.5],
[294.8, 280.0, 276.5, 266.6, 278.3, 256.7, 264.4, 291.7],
],
[
[274.2, 259.3, 267.9, 268.5, 279.0, 264.4, 263.2, 269.1],
[280.5, 272.5, 264.1, 290.7, 288.6, 263.6, 279.9, 278.5],
[276.4, 277.5, 275.6, 283.6, 288.1, 270.3, 286.0, 281.5],
[255.3, 259.7, 261.7, 290.6, 295.0, 280.1, 254.9, 262.2],
[255.4, 257.5, 273.1, 257.7, 258.4, 294.7, 279.3, 282.0],
],
[
[270.4, 273.0, 256.5, 259.9, 268.2, 258.4, 275.5, 294.0],
[280.1, 263.8, 258.3, 274.2, 273.0, 259.8, 253.7, 267.3],
[278.0, 260.8, 263.1, 269.8, 291.2, 279.7, 261.4, 288.6],
[272.1, 292.0, 287.7, 272.4, 273.5, 275.2, 270.0, 268.1],
[286.6, 289.0, 268.9, 277.8, 276.3, 278.3, 262.5, 280.1],
],
[
[275.3, 283.6, 274.4, 272.1, 272.1, 271.1, 273.2, 288.4],
[287.5, 258.1, 286.5, 277.6, 279.5, 288.8, 261.1, 281.0],
[272.5, 264.2, 258.5, 260.8, 267.7, 263.1, 277.2, 280.8],
[265.9, 280.6, 273.1, 244.5, 266.9, 270.7, 277.0, 266.7],
[262.6, 271.8, 270.4, 264.7, 277.9, 267.0, 281.2, 270.1],
],
[
[269.0, 265.1, 271.9, 260.6, 266.8, 255.9, 289.6, 257.0],
[263.2, 271.7, 279.0, 296.9, 271.8, 280.4, 289.9, 277.7],
[251.9, 272.5, 265.7, 272.6, 260.0, 289.5, 262.7, 267.6],
[272.1, 261.7, 265.0, 272.5, 260.6, 283.2, 273.3, 274.1],
[264.0, 266.1, 278.9, 261.3, 266.3, 277.6, 281.9, 284.8],
],
[
[258.6, 265.0, 272.3, 275.7, 279.0, 265.1, 270.8, 258.5],
[266.0, 267.3, 272.9, 274.0, 267.3, 260.6, 280.1, 268.4],
[271.9, 263.6, 266.4, 270.7, 249.5, 286.0, 283.6, 279.2],
[286.9, 288.0, 271.0, 272.5, 271.0, 268.6, 274.6, 267.2],
[269.9, 285.8, 287.2, 277.3, 263.6, 273.8, 281.6, 264.7],
],
[
[269.3, 262.2, 271.6, 265.8, 277.2, 276.9, 273.2, 255.7],
[257.7, 266.9, 269.7, 255.2, 265.2, 301.2, 284.5, 284.7],
[292.6, 268.3, 267.8, 283.6, 262.1, 276.8, 257.8, 271.6],
[259.7, 289.9, 268.4, 277.1, 281.3, 280.5, 265.2, 266.4],
[261.3, 270.0, 266.3, 271.8, 266.7, 254.9, 281.9, 268.6],
],
[
[284.2, 272.6, 278.2, 288.0, 277.0, 261.2, 263.4, 277.3],
[292.5, 270.3, 273.6, 280.3, 261.1, 275.7, 287.1, 278.1],
[295.6, 289.6, 259.1, 266.5, 272.6, 263.2, 272.3, 273.0],
[277.6, 265.0, 267.4, 286.5, 276.2, 276.7, 284.1, 272.1],
[268.4, 273.3, 279.4, 271.9, 261.0, 258.6, 254.6, 269.2],
],
[
[283.8, 265.7, 276.6, 273.9, 268.4, 273.4, 253.4, 271.6],
[276.3, 267.8, 261.1, 267.5, 264.4, 272.4, 291.2, 278.9],
[264.5, 288.0, 272.0, 275.1, 272.2, 275.9, 273.7, 276.4],
[261.7, 252.8, 263.5, 279.2, 285.4, 278.1, 257.6, 264.5],
[267.9, 271.1, 273.4, 276.0, 270.4, 280.8, 272.3, 271.2],
],
[
[272.1, 283.6, 274.5, 271.8, 260.5, 254.9, 280.2, 257.2],
[274.4, 273.8, 263.3, 272.1, 268.6, 279.6, 268.9, 255.7],
[288.6, 288.7, 260.7, 260.6, 273.0, 270.3, 260.6, 281.4],
[256.1, 279.3, 273.7, 250.0, 264.3, 279.6, 277.0, 282.7],
[278.4, 265.3, 272.3, 274.0, 270.8, 272.3, 275.2, 285.1],
],
[
[279.1, 268.2, 268.7, 275.2, 280.5, 274.3, 285.5, 249.8],
[281.2, 267.2, 269.4, 254.8, 284.3, 265.8, 275.3, 260.3],
[282.4, 281.2, 274.6, 277.3, 272.2, 256.8, 273.4, 284.1],
[281.1, 288.6, 269.8, 281.0, 264.7, 258.8, 281.7, 255.5],
[278.4, 280.5, 273.5, 272.0, 279.4, 278.1, 295.4, 246.6],
],
[
[270.0, 259.1, 266.0, 288.3, 268.3, 258.3, 270.1, 286.4],
[268.0, 266.1, 276.0, 253.1, 272.1, 271.2, 270.4, 270.7],
[279.8, 282.8, 264.2, 257.1, 292.4, 276.8, 270.5, 256.9],
[281.7, 280.6, 276.0, 266.0, 278.0, 278.5, 282.8, 268.0],
[275.3, 262.2, 251.9, 270.9, 273.2, 287.4, 285.4, 263.5],
],
[
[282.1, 283.6, 269.3, 276.5, 274.8, 271.5, 276.9, 274.5],
[270.7, 274.9, 286.1, 285.4, 277.8, 269.6, 269.9, 276.3],
[273.1, 278.9, 264.2, 277.1, 257.9, 271.7, 278.9, 262.2],
[292.8, 262.7, 276.5, 274.8, 266.3, 278.1, 277.9, 267.2],
[284.3, 276.9, 282.4, 292.9, 269.5, 269.0, 270.2, 284.6],
],
[
[273.7, 285.3, 272.8, 255.1, 275.0, 269.7, 255.4, 277.4],
[278.6, 272.9, 273.1, 299.3, 271.3, 274.8, 262.7, 272.2],
[272.7, 278.3, 260.2, 264.1, 288.9, 283.2, 259.9, 271.9],
[278.5, 270.0, 265.9, 276.4, 270.0, 255.6, 263.7, 260.0],
[273.4, 266.5, 267.4, 286.9, 268.0, 269.7, 275.1, 269.9],
],
[
[250.5, 267.5, 277.8, 287.8, 276.0, 272.6, 274.8, 292.1],
[263.8, 276.1, 265.4, 266.5, 262.2, 257.9, 275.3, 267.0],
[276.2, 277.0, 276.8, 295.3, 285.2, 257.5, 259.0, 287.8],
[291.8, 257.9, 271.5, 253.3, 270.8, 273.7, 270.7, 280.3],
[270.4, 262.5, 272.5, 268.6, 282.5, 254.3, 272.1, 280.2],
],
[
[274.4, 290.9, 276.8, 267.3, 274.7, 289.6, 267.5, 292.8],
[260.7, 281.5, 264.6, 272.4, 259.0, 274.3, 279.7, 272.6],
[273.2, 262.4, 269.2, 280.0, 275.7, 270.5, 286.6, 293.1],
[267.2, 277.4, 274.5, 274.4, 274.2, 298.3, 286.3, 265.0],
[285.1, 272.3, 263.6, 282.3, 248.3, 275.0, 254.5, 288.2],
],
[
[273.3, 268.5, 282.8, 259.8, 251.3, 270.6, 259.7, 269.6],
[269.6, 278.6, 281.7, 286.3, 283.3, 255.9, 267.4, 283.3],
[256.9, 272.4, 273.2, 263.5, 269.9, 277.0, 259.4, 289.0],
[249.0, 271.5, 279.6, 264.4, 264.4, 263.8, 269.5, 266.3],
[274.4, 278.7, 262.8, 286.0, 282.3, 282.2, 267.3, 273.7],
],
[
[266.9, 259.2, 262.7, 286.4, 257.2, 265.0, 261.5, 283.8],
[275.8, 285.6, 284.7, 258.0, 277.1, 281.5, 266.8, 256.5],
[279.2, 273.6, 267.9, 266.6, 278.4, 275.8, 257.4, 258.7],
[269.9, 247.3, 288.3, 265.3, 269.2, 268.7, 267.9, 280.9],
[252.7, 276.1, 267.5, 279.1, 276.5, 279.8, 257.0, 264.3],
],
[
[284.5, 284.9, 267.2, 274.0, 284.2, 285.8, 274.6, 279.3],
[274.4, 281.6, 260.7, 253.7, 264.9, 261.2, 279.6, 284.1],
[260.1, 276.5, 278.0, 264.0, 264.1, 271.5, 265.2, 290.4],
[274.2, 262.7, 284.7, 290.1, 279.3, 263.6, 279.3, 270.4],
[271.5, 273.7, 264.5, 271.8, 286.5, 263.7, 272.3, 273.6],
],
[
[274.6, 255.3, 290.2, 273.7, 268.6, 267.0, 284.3, 257.5],
[260.7, 248.0, 271.0, 279.5, 279.1, 278.6, 258.2, 290.7],
[264.4, 281.6, 271.5, 283.0, 276.7, 292.1, 274.3, 267.2],
[280.3, 266.8, 272.8, 267.6, 271.0, 272.1, 285.2, 262.9],
[267.5, 256.5, 283.1, 280.3, 263.4, 270.6, 274.9, 268.2],
],
[
[277.8, 270.0, 288.3, 276.6, 276.9, 267.6, 286.9, 275.1],
[282.3, 259.3, 273.5, 295.0, 282.6, 273.9, 275.9, 288.2],
[269.0, 270.2, 292.6, 254.1, 271.9, 271.7, 271.7, 279.6],
[279.5, 252.0, 285.7, 260.6, 252.7, 275.4, 290.4, 277.3],
[276.0, 281.8, 270.6, 272.5, 259.3, 274.4, 290.2, 278.3],
],
[
[256.6, 274.6, 274.0, 285.3, 263.0, 266.5, 264.6, 277.0],
[276.0, 279.5, 272.4, 259.3, 273.0, 276.7, 286.7, 284.0],
[279.8, 265.5, 272.2, 276.8, 283.9, 272.7, 287.7, 263.0],
[267.9, 266.4, 274.4, 251.5, 279.1, 274.1, 258.6, 284.7],
[279.9, 274.3, 268.2, 273.2, 284.7, 291.7, 257.4, 281.0],
],
[
[264.8, 274.6, 275.8, 269.6, 263.1, 254.5, 286.9, 260.2],
[279.8, 281.9, 277.0, 256.9, 268.3, 277.3, 258.9, 268.9],
[255.6, 269.4, 290.6, 276.8, 261.0, 261.6, 286.6, 279.8],
[295.8, 270.1, 259.1, 286.5, 282.2, 269.1, 274.1, 293.4],
[281.4, 264.5, 258.0, 283.1, 272.5, 263.5, 269.8, 266.1],
],
[
[281.0, 287.9, 289.3, 251.7, 284.6, 273.3, 269.2, 274.5],
[268.7, 266.3, 265.5, 271.6, 258.9, 270.1, 277.6, 279.0],
[250.8, 277.2, 260.2, 285.0, 263.0, 279.1, 278.1, 251.8],
[267.4, 272.5, 250.2, 283.1, 269.6, 275.8, 257.6, 275.4],
[273.7, 261.9, 258.7, 267.0, 277.0, 272.1, 280.8, 265.4],
],
[
[281.4, 274.2, 274.0, 278.7, 282.4, 285.4, 262.9, 266.7],
[294.3, 283.0, 282.1, 269.5, 266.3, 292.0, 258.3, 273.1],
[274.7, 257.9, 264.8, 261.9, 247.3, 284.5, 283.9, 274.9],
[287.1, 273.3, 286.9, 283.1, 288.3, 265.8, 272.0, 295.6],
[276.9, 267.3, 271.6, 275.2, 279.6, 277.0, 262.8, 265.3],
],
[
[277.1, 289.1, 284.3, 279.8, 276.7, 290.2, 265.7, 260.0],
[260.8, 251.6, 263.8, 267.6, 266.2, 259.9, 276.7, 267.7],
[273.2, 265.0, 281.7, 270.2, 281.7, 259.8, 264.0, 260.8],
[275.8, 274.9, 279.4, 283.3, 272.6, 273.0, 279.1, 288.0],
[266.9, 261.1, 270.0, 289.2, 250.5, 276.0, 289.7, 281.9],
],
[
[274.8, 273.8, 277.1, 288.6, 277.1, 257.3, 277.7, 279.4],
[278.3, 269.0, 278.2, 277.3, 275.1, 266.6, 280.7, 276.7],
[270.3, 257.8, 264.6, 271.6, 287.7, 274.0, 272.5, 265.8],
[259.1, 269.2, 290.7, 281.9, 270.4, 287.1, 290.8, 290.0],
[285.0, 273.4, 283.4, 278.1, 286.7, 259.6, 249.6, 273.6],
],
[
[269.2, 291.3, 282.4, 279.8, 269.8, 272.5, 271.7, 261.8],
[261.1, 273.4, 287.5, 282.1, 262.1, 275.4, 271.9, 269.1],
[266.1, 272.4, 270.5, 281.2, 271.9, 285.6, 259.6, 290.2],
[270.5, 275.9, 255.8, 275.6, 277.8, 272.3, 271.8, 278.8],
[268.7, 277.8, 267.6, 264.7, 279.0, 258.8, 288.6, 277.3],
],
[
[272.1, 267.0, 251.9, 277.8, 263.8, 275.8, 275.8, 293.0],
[264.4, 268.3, 261.4, 266.6, 283.4, 282.3, 255.5, 272.3],
[262.7, 285.2, 276.2, 283.8, 275.3, 274.8, 290.9, 280.4],
[275.2, 263.9, 275.8, 267.1, 267.2, 267.4, 269.2, 270.3],
[289.4, 259.3, 275.2, 274.0, 268.4, 280.8, 278.5, 266.6],
],
[
[261.1, 264.3, 275.0, 282.6, 286.0, 271.9, 276.3, 263.2],
[280.9, 268.7, 274.8, 280.0, 263.5, 284.9, 279.8, 256.3],
[269.5, 274.8, 271.5, 273.5, 265.1, 283.4, 271.6, 269.9],
[293.7, 278.1, 267.6, 265.9, 261.6, 269.8, 272.4, 277.1],
[267.8, 292.5, 271.5, 279.8, 256.7, 271.9, 273.7, 275.1],
],
[
[290.6, 269.7, 282.3, 277.8, 289.0, 284.4, 274.0, 275.3],
[261.0, 276.2, 282.4, 260.1, 274.1, 279.1, 280.7, 266.0],
[275.6, 265.3, 287.5, 272.9, 278.9, 258.9, 273.2, 264.0],
[287.0, 280.2, 268.2, 277.5, 277.2, 258.7, 263.0, 262.2],
[277.2, 293.3, 270.3, 265.9, 264.7, 262.0, 281.5, 275.9],
],
[
[277.8, 282.3, 278.4, 263.6, 270.7, 275.2, 277.3, 281.0],
[275.2, 263.9, 285.6, 269.5, 272.8, 279.1, 269.4, 268.2],
[261.5, 267.2, 260.3, 293.5, 281.6, 280.1, 282.5, 274.3],
[279.7, 264.8, 258.8, 279.2, 278.6, 261.3, 261.7, 268.0],
[281.1, 258.5, 290.3, 268.9, 275.5, 272.2, 267.3, 276.0],
],
[
[257.4, 261.4, 271.5, 273.8, 272.6, 254.5, 282.5, 262.8],
[260.2, 260.9, 280.4, 279.8, 268.2, 273.2, 275.6, 274.7],
[275.1, 277.5, 285.3, 280.8, 273.3, 263.0, 263.2, 297.7],
[274.7, 275.9, 265.6, 266.9, 273.4, 269.6, 279.8, 276.2],
[279.6, 268.9, 270.3, 269.1, 267.5, 282.4, 279.1, 252.3],
],
[
[277.5, 272.1, 261.2, 266.4, 291.3, 273.9, 270.5, 270.9],
[275.4, 270.1, 260.8, 270.1, 277.3, 271.5, 280.9, 268.7],
[277.8, 277.3, 274.3, 269.1, 280.6, 283.8, 268.4, 278.3],
[291.0, 267.1, 261.3, 269.0, 271.5, 280.5, 274.5, 290.5],
[280.9, 268.4, 283.4, 284.3, 269.5, 261.1, 279.7, 288.4],
],
[
[274.7, 258.8, 271.0, 272.1, 263.9, 268.4, 264.6, 288.0],
[280.5, 254.7, 272.6, 278.1, 250.7, 280.2, 285.2, 275.4],
[286.7, 281.5, 254.7, 276.5, 263.9, 281.3, 278.1, 273.0],
[259.4, 277.5, 271.9, 273.2, 264.0, 273.4, 286.5, 268.5],
[277.3, 270.3, 286.2, 273.9, 268.8, 282.7, 272.1, 274.1],
],
[
[273.2, 257.3, 287.3, 268.4, 278.7, 272.9, 249.7, 272.8],
[272.3, 266.7, 284.1, 280.8, 265.1, 275.5, 282.5, 249.9],
[270.0, 272.4, 276.6, 269.2, 262.0, 289.0, 278.1, 282.9],
[277.6, 246.5, 264.1, 285.4, 279.1, 279.4, 279.2, 288.6],
[276.9, 259.9, 276.0, 252.1, 272.8, 277.6, 277.4, 281.5],
],
[
[280.5, 277.4, 273.8, 284.9, 263.1, 262.4, 297.5, 274.8],
[265.6, 271.3, 294.9, 290.9, 275.9, 275.0, 279.2, 256.7],
[275.8, 266.7, 260.6, 273.5, 270.9, 266.2, 253.6, 270.1],
[282.8, 270.1, 269.4, 278.6, 276.0, 270.8, 279.3, 272.3],
[277.4, 282.5, 257.7, 267.2, 271.4, 267.1, 269.9, 253.6],
],
[
[275.5, 272.7, 268.2, 253.0, 272.0, 272.8, 282.0, 274.8],
[271.3, 295.3, 275.4, 276.9, 270.7, 268.7, 281.0, 294.1],
[285.9, 254.7, 274.8, 259.6, 262.1, 279.0, 280.7, 275.5],
[276.9, 276.7, 258.6, 274.9, 281.7, 279.6, 267.7, 269.1],
[289.2, 256.6, 274.6, 254.9, 257.0, 280.3, 270.2, 272.6],
],
[
[269.6, 270.3, 269.7, 279.4, 253.0, 257.1, 295.4, 287.3],
[264.8, 277.6, 271.6, 271.1, 268.8, 275.6, 262.6, 267.5],
[272.7, 256.1, 259.7, 273.3, 265.6, 287.5, 270.7, 283.3],
[262.8, 276.3, 263.5, 281.9, 264.6, 267.2, 260.5, 263.5],
[286.6, 267.0, 273.4, 277.2, 276.6, 287.9, 262.0, 261.8],
],
[
[277.3, 277.7, 269.9, 263.9, 282.3, 281.7, 280.3, 269.8],
[275.0, 285.4, 290.3, 280.3, 265.4, 262.6, 251.7, 273.8],
[275.0, 276.3, 262.7, 266.6, 273.2, 269.0, 269.6, 256.1],
[271.4, 291.2, 275.5, 265.8, 274.0, 280.6, 291.5, 260.2],
[258.3, 281.9, 264.1, 278.0, 279.1, 269.8, 278.9, 257.5],
],
[
[276.7, 280.6, 262.5, 260.8, 276.9, 284.7, 289.2, 245.8],
[266.1, 251.6, 267.1, 272.0, 275.1, 261.7, 272.0, 269.1],
[276.2, 267.4, 264.4, 279.1, 278.0, 261.8, 291.5, 268.1],
[281.6, 282.3, 267.2, 285.8, 267.3, 287.0, 262.5, 282.3],
[276.1, 276.5, 253.5, 274.9, 264.8, 262.6, 268.3, 276.9],
],
[
[281.0, 290.1, 285.8, 279.5, 275.5, 286.3, 277.5, 268.3],
[284.4, 279.7, 290.9, 273.3, 275.1, 276.8, 270.6, 271.8],
[270.2, 271.8, 266.6, 269.5, 287.0, 281.4, 261.6, 264.1],
[276.7, 269.5, 278.1, 275.2, 281.0, 264.9, 275.4, 272.4],
[267.5, 287.3, 262.6, 270.7, 273.2, 280.5, 264.8, 263.9],
],
[
[287.5, 290.3, 280.7, 271.0, 265.0, 274.3, 277.4, 265.4],
[271.6, 263.7, 294.4, 289.2, 273.0, 267.7, 276.1, 279.3],
[277.1, 273.6, 269.9, 258.6, 252.7, 276.9, 286.8, 266.5],
[277.3, 271.8, 269.1, 280.1, 291.2, 262.5, 263.6, 261.4],
[276.4, 260.8, 259.8, 265.0, 296.3, 269.9, 276.8, 278.7],
],
[
[261.1, 260.2, 270.9, 269.2, 279.8, 243.0, 270.1, 265.4],
[275.1, 271.3, 271.6, 297.3, 275.4, 264.1, 275.1, 268.9],
[274.9, 277.0, 274.7, 280.4, 283.5, 269.7, 253.7, 272.1],
[271.8, 262.5, 259.3, 266.2, 279.2, 275.5, 276.8, 272.5],
[269.8, 277.3, 275.8, 283.6, 261.1, 268.3, 248.6, 262.8],
],
[
[270.5, 274.3, 270.4, 269.5, 271.5, 273.9, 281.5, 276.6],
[277.3, 271.4, 294.4, 281.4, 269.7, 287.9, 260.6, 276.1],
[270.9, 271.2, 269.0, 269.8, 263.8, 263.1, 281.3, 288.1],
[263.8, 277.5, 270.3, 264.8, 270.0, 290.4, 265.1, 273.1],
[251.5, 282.6, 265.7, 262.8, 267.1, 269.4, 285.3, 269.2],
],
[
[270.1, 281.4, 284.2, 263.7, 278.9, 266.2, 282.9, 273.6],
[286.6, 275.3, 281.8, 272.7, 265.7, 253.1, 269.1, 264.6],
[293.7, 278.5, 272.9, 275.7, 279.7, 281.6, 270.3, 260.9],
[277.6, 289.1, 253.7, 282.5, 285.1, 276.3, 260.7, 289.7],
[286.6, 289.8, 244.6, 286.1, 265.8, 289.2, 284.5, 284.1],
],
[
[280.4, 269.5, 270.3, 274.6, 272.1, 284.9, 272.3, 276.4],
[265.1, 285.5, 267.2, 275.9, 277.2, 266.5, 280.4, 275.9],
[291.2, 265.5, 294.6, 258.7, 267.8, 269.9, 283.3, 275.3],
[270.5, 267.0, 263.4, 270.2, 279.5, 270.6, 265.6, 286.5],
[274.4, 277.7, 272.3, 267.6, 278.8, 267.4, 275.6, 265.9],
],
[
[279.7, 272.4, 275.7, 276.4, 267.8, 263.7, 289.2, 296.3],
[279.9, 305.1, 272.7, 269.6, 273.8, 282.6, 277.3, 267.1],
[276.4, 274.6, 273.0, 265.4, 268.2, 283.6, 273.2, 260.1],
[285.8, 275.2, 253.9, 261.6, 268.5, 284.8, 268.9, 263.2],
[279.8, 281.4, 286.1, 275.0, 271.4, 280.0, 282.9, 279.9],
],
[
[286.3, 290.2, 283.0, 250.6, 274.3, 257.9, 273.7, 285.2],
[286.2, 277.6, 266.2, 271.3, 262.4, 262.6, 273.9, 275.3],
[273.4, 285.1, 282.6, 289.2, 294.0, 265.3, 275.9, 257.5],
[283.3, 272.9, 255.5, 264.4, 280.0, 261.6, 283.3, 271.8],
[291.1, 279.2, 266.4, 264.4, 267.3, 284.5, 276.7, 265.7],
],
[
[262.9, 284.6, 268.7, 277.1, 280.8, 267.9, 268.4, 273.8],
[257.7, 284.1, 292.8, 284.7, 271.5, 257.8, 271.2, 276.5],
[293.1, 285.6, 279.3, 266.0, 291.1, 273.8, 278.9, 272.9],
[258.5, 271.1, 271.4, 266.5, 261.7, 254.0, 280.3, 277.9],
[284.2, 257.3, 273.4, 258.4, 280.2, 279.0, 268.1, 264.2],
],
[
[282.2, 266.1, 282.7, 296.2, 258.5, 269.3, 267.5, 286.1],
[264.6, 282.6, 255.9, 278.9, 267.8, 265.5, 270.1, 280.6],
[273.7, 274.2, 272.4, 275.9, 260.4, 289.8, 264.6, 277.4],
[272.6, 278.7, 283.1, 277.4, 278.2, 289.5, 271.6, 263.3],
[268.1, 268.8, 285.6, 259.7, 248.9, 282.8, 279.1, 273.2],
],
[
[281.6, 276.5, 258.1, 265.5, 256.5, 266.2, 285.0, 276.8],
[278.5, 273.0, 279.2, 260.2, 268.4, 271.8, 266.4, 258.7],
[274.8, 258.4, 258.4, 279.9, 267.1, 279.5, 281.9, 281.7],
[275.0, 279.3, 267.4, 267.1, 275.9, 251.9, 273.9, 259.5],
[291.5, 262.5, 276.4, 281.7, 275.2, 260.9, 272.7, 277.5],
],
[
[255.6, 257.6, 273.1, 272.6, 293.2, 260.9, 277.7, 280.5],
[254.3, 283.5, 275.1, 268.0, 293.5, 271.7, 283.8, 280.2],
[264.8, 261.5, 270.9, 278.2, 268.8, 278.5, 278.8, 270.3],
[279.5, 276.8, 271.4, 262.3, 273.4, 259.1, 280.3, 265.6],
[256.2, 278.8, 260.5, 262.3, 251.4, 286.6, 281.1, 259.6],
],
[
[272.7, 274.6, 263.7, 276.5, 269.4, 287.5, 259.3, 281.9],
[284.4, 257.9, 245.8, 258.5, 258.6, 269.5, 262.1, 268.8],
[275.2, 263.3, 270.5, 285.4, 256.8, 280.1, 267.2, 276.7],
[272.6, 292.5, 281.8, 265.6, 270.6, 280.1, 272.6, 261.0],
[269.2, 272.2, 275.0, 250.4, 281.1, 269.8, 273.7, 277.4],
],
[
[261.9, 289.6, 262.0, 286.8, 266.3, 263.4, 263.0, 274.8],
[284.5, 273.8, 272.9, 273.6, 264.3, 278.5, 269.5, 293.6],
[272.4, 268.8, 262.8, 270.0, 285.0, 264.0, 286.0, 294.4],
[279.9, 275.6, 256.9, 285.8, 268.5, 270.1, 268.0, 263.0],
[270.8, 279.4, 276.6, 274.5, 264.0, 277.9, 281.6, 269.4],
],
[
[277.3, 271.4, 268.6, 262.2, 259.6, 262.5, 264.0, 278.7],
[273.8, 280.7, 275.7, 254.3, 270.0, 268.9, 278.2, 269.7],
[284.6, 270.7, 284.1, 277.3, 271.7, 276.2, 276.2, 270.5],
[288.2, 264.5, 262.5, 279.8, 272.5, 266.7, 260.6, 287.1],
[276.0, 286.9, 272.8, 279.3, 266.5, 281.7, 275.4, 274.1],
],
],
units="K",
dtype="f8",
)
f.set_data(data, axes=("domainaxis0", "domainaxis1", "domainaxis2"))
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"standard_name": "time", "units": "days since 1959-01-01"}
)
c.nc_set_variable("time")
data = Data(
[
0.25,
0.75,
1.25,
1.75,
2.25,
2.75,
3.25,
3.75,
4.25,
4.75,
5.25,
5.75,
6.25,
6.75,
7.25,
7.75,
8.25,
8.75,
9.25,
9.75,
10.25,
10.75,
11.25,
11.75,
12.25,
12.75,
13.25,
13.75,
14.25,
14.75,
15.25,
15.75,
16.25,
16.75,
17.25,
17.75,
18.25,
18.75,
19.25,
19.75,
20.25,
20.75,
21.25,
21.75,
22.25,
22.75,
23.25,
23.75,
24.25,
24.75,
25.25,
25.75,
26.25,
26.75,
27.25,
27.75,
28.25,
28.75,
29.25,
29.75,
30.25,
30.75,
31.25,
31.75,
32.25,
32.75,
33.25,
33.75,
34.25,
34.75,
35.25,
35.75,
36.25,
36.75,
37.25,
37.75,
38.25,
38.75,
39.25,
39.75,
40.25,
40.75,
41.25,
41.75,
42.25,
42.75,
43.25,
43.75,
44.25,
44.75,
45.25,
45.75,
46.25,
46.75,
47.25,
47.75,
48.25,
48.75,
49.25,
49.75,
50.25,
50.75,
51.25,
51.75,
52.25,
52.75,
53.25,
53.75,
54.25,
54.75,
55.25,
55.75,
56.25,
56.75,
57.25,
57.75,
58.25,
58.75,
],
units="days since 1959-01-01",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("bounds")
data = Data(
[
[0.0, 0.5],
[0.5, 1.0],
[1.0, 1.5],
[1.5, 2.0],
[2.0, 2.5],
[2.5, 3.0],
[3.0, 3.5],
[3.5, 4.0],
[4.0, 4.5],
[4.5, 5.0],
[5.0, 5.5],
[5.5, 6.0],
[6.0, 6.5],
[6.5, 7.0],
[7.0, 7.5],
[7.5, 8.0],
[8.0, 8.5],
[8.5, 9.0],
[9.0, 9.5],
[9.5, 10.0],
[10.0, 10.5],
[10.5, 11.0],
[11.0, 11.5],
[11.5, 12.0],
[12.0, 12.5],
[12.5, 13.0],
[13.0, 13.5],
[13.5, 14.0],
[14.0, 14.5],
[14.5, 15.0],
[15.0, 15.5],
[15.5, 16.0],
[16.0, 16.5],
[16.5, 17.0],
[17.0, 17.5],
[17.5, 18.0],
[18.0, 18.5],
[18.5, 19.0],
[19.0, 19.5],
[19.5, 20.0],
[20.0, 20.5],
[20.5, 21.0],
[21.0, 21.5],
[21.5, 22.0],
[22.0, 22.5],
[22.5, 23.0],
[23.0, 23.5],
[23.5, 24.0],
[24.0, 24.5],
[24.5, 25.0],
[25.0, 25.5],
[25.5, 26.0],
[26.0, 26.5],
[26.5, 27.0],
[27.0, 27.5],
[27.5, 28.0],
[28.0, 28.5],
[28.5, 29.0],
[29.0, 29.5],
[29.5, 30.0],
[30.0, 30.5],
[30.5, 31.0],
[31.0, 31.5],
[31.5, 32.0],
[32.0, 32.5],
[32.5, 33.0],
[33.0, 33.5],
[33.5, 34.0],
[34.0, 34.5],
[34.5, 35.0],
[35.0, 35.5],
[35.5, 36.0],
[36.0, 36.5],
[36.5, 37.0],
[37.0, 37.5],
[37.5, 38.0],
[38.0, 38.5],
[38.5, 39.0],
[39.0, 39.5],
[39.5, 40.0],
[40.0, 40.5],
[40.5, 41.0],
[41.0, 41.5],
[41.5, 42.0],
[42.0, 42.5],
[42.5, 43.0],
[43.0, 43.5],
[43.5, 44.0],
[44.0, 44.5],
[44.5, 45.0],
[45.0, 45.5],
[45.5, 46.0],
[46.0, 46.5],
[46.5, 47.0],
[47.0, 47.5],
[47.5, 48.0],
[48.0, 48.5],
[48.5, 49.0],
[49.0, 49.5],
[49.5, 50.0],
[50.0, 50.5],
[50.5, 51.0],
[51.0, 51.5],
[51.5, 52.0],
[52.0, 52.5],
[52.5, 53.0],
[53.0, 53.5],
[53.5, 54.0],
[54.0, 54.5],
[54.5, 55.0],
[55.0, 55.5],
[55.5, 56.0],
[56.0, 56.5],
[56.5, 57.0],
[57.0, 57.5],
[57.5, 58.0],
[58.0, 58.5],
[58.5, 59.0],
],
units="days since 1959-01-01",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="dimensioncoordinate0", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_north", "standard_name": "latitude"}
)
c.nc_set_variable("lat")
data = Data(
[-75.0, -45.0, 0.0, 45.0, 75.0], units="degrees_north", dtype="f8"
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lat_bnds")
data = Data(
[
[-90.0, -60.0],
[-60.0, -30.0],
[-30.0, 30.0],
[30.0, 60.0],
[60.0, 90.0],
],
units="degrees_north",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate1", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties(
{"units": "degrees_east", "standard_name": "longitude"}
)
c.nc_set_variable("lon")
data = Data(
[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5],
units="degrees_east",
dtype="f8",
)
c.set_data(data)
b = Bounds()
b.nc_set_variable("lon_bnds")
data = Data(
[
[0.0, 45.0],
[45.0, 90.0],
[90.0, 135.0],
[135.0, 180.0],
[180.0, 225.0],
[225.0, 270.0],
[270.0, 315.0],
[315.0, 360.0],
],
units="degrees_east",
dtype="f8",
)
b.set_data(data)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis2",), key="dimensioncoordinate2", copy=False
)
# dimension_coordinate
c = DimensionCoordinate()
c.set_properties({"standard_name": "air_pressure", "units": "hPa"})
c.nc_set_variable("air_pressure")
data = Data([850.0], units="hPa", dtype="f8")
c.set_data(data)
f.set_construct(
c, axes=("domainaxis3",), key="dimensioncoordinate3", copy=False
)
# cell_method
c = CellMethod()
c.set_method("mean")
c.set_axes("area")
f.set_construct(c)
elif n == 6:
# field: precipitation_amount
f = Field()
f.set_properties(
{
"Conventions": "CF-1.8",
"featureType": "timeSeries",
"comment": "global comment",
"standard_name": "precipitation_amount",
"standard_units": "kg m-2",
}
)
d = Data([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]], dtype="f8")
f.set_data(d)
f.nc_set_variable("pr")
f.nc_set_geometry_variable("geometry1")
# netCDF global attributes
f.nc_set_global_attributes(
{"Conventions": None, "featureType": None, "comment": None}
)
# domain_axis: ncdim%instance
c = DomainAxis()
c.set_size(2)
c.nc_set_dimension("instance")
f.set_construct(c, key="domainaxis0", copy=False)
# domain_axis: ncdim%time
c = DomainAxis()
c.set_size(4)
c.nc_set_dimension("time")
f.set_construct(c, key="domainaxis1", copy=False)
# field data axes
f.set_data_axes(("domainaxis0", "domainaxis1"))
# auxiliary_coordinate: latitude
c = AuxiliaryCoordinate()
c.set_properties(
{"units": "degrees_north", "standard_name": "latitude"}
)
d = Data([25.0, 7.0], units="degrees_north", dtype="f8")
c.set_data(d)
c.nc_set_variable("lat")
c.set_geometry("polygon")
b = Bounds()
b.set_properties(
{
"units": "degrees_north",
"standard_name": "latitude",
"axis": "Y",
}
)
d = Data(
[
[
[0.0, 15.0, 0.0, 9.969209968386869e36],
[5.0, 10.0, 5.0, 5.0],
[20.0, 35.0, 20.0, 9.969209968386869e36],
],
[
[0.0, 15.0, 0.0, 9.969209968386869e36],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
],
units="degrees_north",
dtype="f8",
mask=Data(
[
[
[False, False, False, True],
[False, False, False, False],
[False, False, False, True],
],
[
[False, False, False, True],
[True, True, True, True],
[True, True, True, True],
],
],
dtype="b1",
),
)
b.set_data(d)
b.nc_set_variable("y")
c.set_bounds(b)
i = InteriorRing()
d = Data(
[[0, 1, 0], [0, -2147483647, -2147483647]],
dtype="i4",
mask=Data(
[[False, False, False], [False, True, True]], dtype="b1"
),
)
i.set_data(d)
i.nc_set_variable("interior_ring")
c.set_interior_ring(i)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate0", copy=False
)
# auxiliary_coordinate: longitude
c = AuxiliaryCoordinate()
c.set_properties(
{"units": "degrees_east", "standard_name": "longitude"}
)
d = Data([10.0, 40.0], units="degrees_east", dtype="f8")
c.set_data(d)
c.nc_set_variable("lon")
c.set_geometry("polygon")
b = Bounds()
b.set_properties(
{
"units": "degrees_east",
"standard_name": "longitude",
"axis": "X",
}
)
d = Data(
[
[
[20.0, 10.0, 0.0, 9.969209968386869e36],
[5.0, 10.0, 15.0, 10.0],
[20.0, 10.0, 0.0, 9.969209968386869e36],
],
[
[50.0, 40.0, 30.0, 9.969209968386869e36],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
],
units="degrees_east",
dtype="f8",
mask=Data(
[
[
[False, False, False, True],
[False, False, False, False],
[False, False, False, True],
],
[
[False, False, False, True],
[True, True, True, True],
[True, True, True, True],
],
],
dtype="b1",
),
)
b.set_data(d)
b.nc_set_variable("x")
c.set_bounds(b)
i = InteriorRing()
d = Data(
[[0, 1, 0], [0, -2147483647, -2147483647]],
dtype="i4",
mask=Data(
[[False, False, False], [False, True, True]], dtype="b1"
),
)
i.set_data(d)
i.nc_set_variable("interior_ring")
c.set_interior_ring(i)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate1", copy=False
)
# auxiliary_coordinate: cf_role=timeseries_id
c = AuxiliaryCoordinate()
c.set_properties({"cf_role": "timeseries_id"})
d = Data([b"x1", b"y2"], dtype="S2")
c.set_data(d)
c.nc_set_variable("instance_id")
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate2", copy=False
)
# auxiliary_coordinate: Z
c = AuxiliaryCoordinate()
c.nc_set_variable("z")
c.set_geometry("polygon")
b = Bounds()
b.set_properties(
{"units": "m", "standard_name": "altitude", "axis": "Z"}
)
d = Data(
[
[
[1.0, 2.0, 4.0, 9.969209968386869e36],
[2.0, 3.0, 4.0, 5.0],
[5.0, 1.0, 4.0, 9.969209968386869e36],
],
[
[3.0, 2.0, 1.0, 9.969209968386869e36],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
[
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
9.969209968386869e36,
],
],
],
units="m",
dtype="f8",
mask=Data(
[
[
[False, False, False, True],
[False, False, False, False],
[False, False, False, True],
],
[
[False, False, False, True],
[True, True, True, True],
[True, True, True, True],
],
],
dtype="b1",
),
)
b.set_data(d)
b.nc_set_variable("z")
c.set_bounds(b)
i = InteriorRing()
d = Data(
[[0, 1, 0], [0, -2147483647, -2147483647]],
dtype="i4",
mask=Data(
[[False, False, False], [False, True, True]], dtype="b1"
),
)
i.set_data(d)
i.nc_set_variable("interior_ring")
c.set_interior_ring(i)
f.set_construct(
c, axes=("domainaxis0",), key="auxiliarycoordinate3", copy=False
)
# dimension_coordinate: time
c = DimensionCoordinate()
c.set_properties(
{"standard_name": "time", "units": "days since 2000-01-01"}
)
d = Data(
[15.5, 45, 74.5, 105],
units="days since 2000-01-01",
calendar="gregorian",
dtype="f8",
)
c.set_data(d)
c.nc_set_variable("time")
b = Bounds()
d = Data(
[[0.0, 31.0], [31.0, 60.0], [60.0, 91.0], [91.0, 121.0]],
units="days since 2000-01-01",
calendar="gregorian",
dtype="f8",
)
b.set_data(d)
b.nc_set_variable("time_bounds")
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate0", copy=False
)
# coordinate_reference
c = CoordinateReference()
c.nc_set_variable("datum")
c.set_coordinates({"auxiliarycoordinate0", "auxiliarycoordinate1"})
c.datum.set_parameter("semi_major_axis", 6378137.0)
c.datum.set_parameter("inverse_flattening", 298.257223563)
c.datum.set_parameter("longitude_of_prime_meridian", 0.0)
c.coordinate_conversion.set_parameter(
"grid_mapping_name", "latitude_longitude"
)
f.set_construct(c)
elif n == 7:
# field: eastward_wind
f = Field()
f.set_properties(
{
"Conventions": "CF-1.8",
"_FillValue": -1073741824.0,
"standard_name": "eastward_wind",
"units": "m s-1",
}
)
d = Data(
[
[
[
[12.62, 13.23, 13.75, 14.13, 14.28],
[12.46, 12.9, 13.46, 13.71, 14.03],
[12.22, 12.57, 12.91, 13.19, 13.8],
[11.83, 12.25, 12.6, 13.09, 13.63],
]
],
[
[
[3.6, 3.3, 3.13, 3.21, 3.67],
[3.69, 3.53, 3.91, 4.5, 5.63],
[4.64, 5.03, 5.8, 6.79, 8.17],
[6.7, 7.42, 8.23, 9.32, 10.5],
]
],
[
[
[10.42, 10.81, 11.03, 10.96, 10.6],
[10.59, 10.95, 11.36, 11.27, 11.08],
[10.82, 11.19, 11.43, 11.43, 11.45],
[10.93, 11.23, 11.35, 11.58, 11.64],
]
],
],
units="m s-1",
dtype="f4",
fill_value=-1073741824.0,
)
f.set_data(d)
f.nc_set_variable("ua")
# domain_axis: ncdim%t
c = DomainAxis()
c.set_size(3)
c.nc_set_dimension("t")
f.set_construct(c, key="domainaxis0", copy=False)
# domain_axis: ncdim%z
c = DomainAxis()
c.set_size(1)
c.nc_set_dimension("z")
f.set_construct(c, key="domainaxis1", copy=False)
# domain_axis: ncdim%y
c = DomainAxis()
c.set_size(4)
c.nc_set_dimension("y")
f.set_construct(c, key="domainaxis2", copy=False)
# domain_axis: ncdim%x
c = DomainAxis()
c.set_size(5)
c.nc_set_dimension("x")
f.set_construct(c, key="domainaxis3", copy=False)
# field data axes
f.set_data_axes(
("domainaxis0", "domainaxis1", "domainaxis2", "domainaxis3")
)
# auxiliary_coordinate: latitude
c = AuxiliaryCoordinate()
c.set_properties(
{"standard_name": "latitude", "units": "degrees_north"}
)
d = Data(
[
[52.4243, 52.4338, 52.439, 52.4398, 52.4362],
[51.9845, 51.9939, 51.999, 51.9998, 51.9962],
[51.5446, 51.5539, 51.559, 51.5598, 51.5563],
[51.1048, 51.114, 51.119, 51.1198, 51.1163],
],
units="degrees_north",
dtype="f8",
)
c.set_data(d)
b = Bounds()
d = Data(
[
[
[52.6378, 52.198, 52.2097, 52.6496],
[52.6496, 52.2097, 52.217, 52.6569],
[52.6569, 52.217, 52.2199, 52.6599],
[52.6599, 52.2199, 52.2185, 52.6585],
[52.6585, 52.2185, 52.2128, 52.6527],
],
[
[52.198, 51.7582, 51.7698, 52.2097],
[52.2097, 51.7698, 51.777, 52.217],
[52.217, 51.777, 51.7799, 52.2199],
[52.2199, 51.7799, 51.7786, 52.2185],
[52.2185, 51.7786, 51.7729, 52.2128],
],
[
[51.7582, 51.3184, 51.3299, 51.7698],
[51.7698, 51.3299, 51.337, 51.777],
[51.777, 51.337, 51.3399, 51.7799],
[51.7799, 51.3399, 51.3386, 51.7786],
[51.7786, 51.3386, 51.333, 51.7729],
],
[
[51.3184, 50.8786, 50.89, 51.3299],
[51.3299, 50.89, 50.8971, 51.337],
[51.337, 50.8971, 50.8999, 51.3399],
[51.3399, 50.8999, 50.8986, 51.3386],
[51.3386, 50.8986, 50.893, 51.333],
],
],
units="degrees_north",
dtype="f8",
)
b.set_data(d)
c.set_bounds(b)
f.set_construct(
c,
axes=("domainaxis2", "domainaxis3"),
key="auxiliarycoordinate0",
copy=False,
)
# auxiliary_coordinate: longitude
c = AuxiliaryCoordinate()
c.set_properties(
{"standard_name": "longitude", "units": "degrees_east"}
)
d = Data(
[
[8.0648, 8.7862, 9.5079, 10.2296, 10.9514],
[8.0838, 8.7981, 9.5127, 10.2274, 10.942],
[8.1024, 8.8098, 9.5175, 10.2252, 10.9328],
[8.1207, 8.8213, 9.5221, 10.223, 10.9238],
],
units="degrees_east",
dtype="f8",
)
c.set_data(d)
b = Bounds()
d = Data(
[
[
[7.6928, 7.7155, 8.4332, 8.4176],
[8.4176, 8.4332, 9.1512, 9.1428],
[9.1428, 9.1512, 9.8694, 9.8681],
[9.8681, 9.8694, 10.5876, 10.5935],
[10.5935, 10.5876, 11.3057, 11.3187],
],
[
[7.7155, 7.7379, 8.4485, 8.4332],
[8.4332, 8.4485, 9.1595, 9.1512],
[9.1512, 9.1595, 9.8707, 9.8694],
[9.8694, 9.8707, 10.5818, 10.5876],
[10.5876, 10.5818, 11.2929, 11.3057],
],
[
[7.7379, 7.7598, 8.4636, 8.4485],
[8.4485, 8.4636, 9.1677, 9.1595],
[9.1595, 9.1677, 9.8719, 9.8707],
[9.8707, 9.8719, 10.5762, 10.5818],
[10.5818, 10.5762, 11.2804, 11.2929],
],
[
[7.7598, 7.7812, 8.4783, 8.4636],
[8.4636, 8.4783, 9.1757, 9.1677],
[9.1677, 9.1757, 9.8732, 9.8719],
[9.8719, 9.8732, 10.5707, 10.5762],
[10.5762, 10.5707, 11.2681, 11.2804],
],
],
units="degrees_east",
dtype="f8",
)
b.set_data(d)
c.set_bounds(b)
f.set_construct(
c,
axes=("domainaxis2", "domainaxis3"),
key="auxiliarycoordinate1",
copy=False,
)
# dimension_coordinate: time
c = DimensionCoordinate()
c.set_properties(
{
"axis": "T",
"standard_name": "time",
"units": "days since 1979-1-1",
"calendar": "gregorian",
}
)
d = Data(
[120.5, 121.5, 122.5],
units="days since 1979-1-1",
calendar="gregorian",
dtype="f8",
)
c.set_data(d)
b = Bounds()
d = Data(
[[120.0, 121.0], [121.0, 122.0], [122.0, 123.0]],
units="days since 1979-1-1",
calendar="gregorian",
dtype="f8",
)
b.set_data(d)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis0",), key="dimensioncoordinate0", copy=False
)
# dimension_coordinate: air_pressure
c = DimensionCoordinate()
c.set_properties(
{
"positive": "down",
"axis": "Z",
"standard_name": "air_pressure",
"units": "hPa",
}
)
d = Data([850.0], units="hPa", dtype="f8")
c.set_data(d)
f.set_construct(
c, axes=("domainaxis1",), key="dimensioncoordinate1", copy=False
)
# dimension_coordinate: grid_latitude
c = DimensionCoordinate()
c.set_properties(
{"axis": "Y", "standard_name": "grid_latitude", "units": "degrees"}
)
d = Data([0.44, 0.0, -0.44, -0.88], units="degrees", dtype="f8")
c.set_data(d)
b = Bounds()
d = Data(
[[0.66, 0.22], [0.22, -0.22], [-0.22, -0.66], [-0.66, -1.1]],
units="degrees",
dtype="f8",
)
b.set_data(d)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis2",), key="dimensioncoordinate2", copy=False
)
# dimension_coordinate: grid_longitude
c = DimensionCoordinate()
c.set_properties(
{
"axis": "X",
"standard_name": "grid_longitude",
"units": "degrees",
}
)
d = Data([-1.18, -0.74, -0.3, 0.14, 0.58], units="degrees", dtype="f8")
c.set_data(d)
b = Bounds()
d = Data(
[
[-1.4, -0.96],
[-0.96, -0.52],
[-0.52, -0.08],
[-0.08, 0.36],
[0.36, 0.8],
],
units="degrees",
dtype="f8",
)
b.set_data(d)
c.set_bounds(b)
f.set_construct(
c, axes=("domainaxis3",), key="dimensioncoordinate3", copy=False
)
# cell_method
c = CellMethod()
c.set_method("mean")
c.set_axes(("domainaxis0",))
f.set_construct(c)
# coordinate_reference
c = CoordinateReference()
c.set_coordinates(
{
"dimensioncoordinate3",
"auxiliarycoordinate1",
"auxiliarycoordinate0",
"dimensioncoordinate2",
}
)
c.coordinate_conversion.set_parameter(
"grid_mapping_name", "rotated_latitude_longitude"
)
c.coordinate_conversion.set_parameter("grid_north_pole_latitude", 38.0)
c.coordinate_conversion.set_parameter(
"grid_north_pole_longitude", 190.0
)
f.set_construct(c)
return f
def example_fields(*n, _func=example_field):
"""Return example field constructs.
.. versionadded:: (cfdm) 1.8.9.0
.. seealso:: `cfdm.example_field`, `cfdm.example_domain`
:Parameters:
n: zero or more `int`, optional
Select the example field constructs to return, any
combination of:
===== ===================================================
*n* Description
===== ===================================================
``0`` A field construct with properties as well as a
cell method construct and dimension coordinate
constructs with bounds.
``1`` A field construct with properties as well as at
least one of every type of metadata construct.
``2`` A field construct that contains a monthly time
series at each latitude-longitude location.
``3`` A field construct that contains discrete sampling
geometry (DSG) "timeSeries" features.
``4`` A field construct that contains discrete sampling
geometry (DSG) "timeSeriesProfile" features.
``5`` A field construct that contains a 12 hourly time
series at each latitude-longitude location.
``6`` A field construct that has polygon geometry
coordinate cells with interior ring variables.
``7`` A field construct that has rotated pole dimension
coordinate constructs and 2-d latitude and
longitude auxiliary coordinate constructs.
===== ===================================================
If no individual field constructs are selected then all
available field constructs will be returned.
Field constructs may be selected multiple time, and will
be output in the order that they are given.
See the `cfdm.example_field` for details.
_func: function
The function that returns each individual field construct.
:Returns:
`list`
The example field constructs.
**Examples**
>>> cfdm.example_fields()
[<Field: specific_humidity(latitude(5), longitude(8)) 1>,
<Field: air_temperature(atmosphere_hybrid_height_coordinate(1), grid_latitude(10), grid_longitude(9)) K>,
<Field: air_potential_temperature(time(36), latitude(5), longitude(8)) K>,
<Field: precipitation_flux(cf_role=timeseries_id(4), ncdim%timeseries(9)) kg m-2 day-1>,
<Field: air_temperature(cf_role=timeseries_id(3), ncdim%timeseries(26), ncdim%profile_1(4)) K>,
<Field: air_potential_temperature(time(118), latitude(5), longitude(8)) K>,
<Field: precipitation_amount(cf_role=timeseries_id(2), time(4))>,
<Field: eastward_wind(time(3), air_pressure(1), grid_latitude(4), grid_longitude(5)) m s-1>]
>>> cfdm.example_fields(7, 1)
[<Field: eastward_wind(time(3), air_pressure(1), grid_latitude(4), grid_longitude(5)) m s-1>,
<Field: air_temperature(atmosphere_hybrid_height_coordinate(1), grid_latitude(10), grid_longitude(9)) K>]
>>> cfdm.example_fields(3)
[<Field: precipitation_flux(cf_role=timeseries_id(4), ncdim%timeseries(9)) kg m-2 day-1>]
>>> cfdm.example_fields(3, 3, 4)
[<Field: precipitation_flux(cf_role=timeseries_id(4), ncdim%timeseries(9)) kg m-2 day-1>,
<Field: precipitation_flux(cf_role=timeseries_id(4), ncdim%timeseries(9)) kg m-2 day-1>,
<Field: air_temperature(cf_role=timeseries_id(3), ncdim%timeseries(26), ncdim%profile_1(4)) K>]
See the `cfdm.example_field` for more details.
"""
if not n:
out = []
i = 0
while True:
try:
out.append(_func(i))
except ValueError:
break
i += 1
else:
out = [_func(i) for i in n]
return out
def example_domain(n, _func=example_field):
"""Return an example domain construct.
.. versionadded:: (cfdm) 1.8.9.0
.. seealso:: `cfdm.example_field`, `cfdm.example_fields`
:Parameters:
n: `int`
Select the example domain construct to return, one of:
===== ===================================================
*n* Description
===== ===================================================
``0`` A domain construct dimension coordinate constructs
with bounds.
``1`` A domain construct with at least one of every
possible type of metadata construct.
``2`` A domain construct dimension coordinate constructs
with bounds.
series at each latitude-longitude location.
``3`` A domain construct for discrete sampling geometry
(DSG) "timeSeries" features.
``4`` A domain construct or discrete sampling geometry
(DSG) "timeSeriesProfile" features.
``5`` A domain construct dimension coordinate constructs
with bounds.
``6`` A domain construct that has polygon geometry
coordinate cells with interior ring variables.
``7`` A domain construct that has rotated pole dimension
coordinate constructs and 2-d latitude and
longitude auxiliary coordinate constructs.
===== ===================================================
See the examples for details.
_func: function
The function that creates the field construct from which
the domain construct is derived.
:Returns:
`Domain`
The example domain construct.
**Examples:**
>>> f = cfdm.example_domain(0)
>>> print(f)
Dimension coords: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: time(1) = [2019-01-01 00:00:00]
>>> f = cfdm.example_domain(1)
>>> print(f)
Dimension coords: atmosphere_hybrid_height_coordinate(1) = [1.5]
: grid_latitude(10) = [2.2, ..., -1.76] degrees
: grid_longitude(9) = [-4.7, ..., -1.18] degrees
: time(1) = [2019-01-01 00:00:00]
Auxiliary coords: latitude(grid_latitude(10), grid_longitude(9)) = [[53.941, ..., 50.225]] degrees_N
: longitude(grid_longitude(9), grid_latitude(10)) = [[2.004, ..., 8.156]] degrees_E
: long_name=Grid latitude name(grid_latitude(10)) = [--, ..., b'kappa']
Cell measures : measure:area(grid_longitude(9), grid_latitude(10)) = [[2391.9657, ..., 2392.6009]] km2
Coord references: grid_mapping_name:rotated_latitude_longitude
: standard_name:atmosphere_hybrid_height_coordinate
Domain ancils : ncvar%a(atmosphere_hybrid_height_coordinate(1)) = [10.0] m
: ncvar%b(atmosphere_hybrid_height_coordinate(1)) = [20.0]
: surface_altitude(grid_latitude(10), grid_longitude(9)) = [[0.0, ..., 270.0]] m
>>> f = cfdm.example_domain(2)
>>> print(f)
Dimension coords: time(36) = [1959-12-16 12:00:00, ..., 1962-11-16 00:00:00]
: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: air_pressure(1) = [850.0] hPa
>>> f = cfdm.example_domain(3)
>>> print(f)
Auxiliary coords: time(cf_role=timeseries_id(4), ncdim%timeseries(9)) = [[1969-12-29 00:00:00, ..., 1970-01-07 00:00:00]]
: latitude(cf_role=timeseries_id(4)) = [-9.0, ..., 78.0] degrees_north
: longitude(cf_role=timeseries_id(4)) = [-23.0, ..., 178.0] degrees_east
: height(cf_role=timeseries_id(4)) = [0.5, ..., 345.0] m
: cf_role=timeseries_id(cf_role=timeseries_id(4)) = [b'station1', ..., b'station4']
: long_name=station information(cf_role=timeseries_id(4)) = [-10, ..., -7]
>>> f = cfdm.example_domain(4)
>>> print(f)
Auxiliary coords: time(cf_role=timeseries_id(3), ncdim%timeseries(26)) = [[1970-01-04 00:00:00, ..., --]]
: latitude(cf_role=timeseries_id(3)) = [-9.0, 2.0, 34.0] degrees_north
: longitude(cf_role=timeseries_id(3)) = [-23.0, 0.0, 67.0] degrees_east
: height(cf_role=timeseries_id(3)) = [0.5, 12.6, 23.7] m
: altitude(cf_role=timeseries_id(3), ncdim%timeseries(26), ncdim%profile_1(4)) = [[[2.07, ..., --]]] km
: cf_role=timeseries_id(cf_role=timeseries_id(3)) = [b'station1', b'station2', b'station3']
: long_name=station information(cf_role=timeseries_id(3)) = [-10, -9, -8]
: cf_role=profile_id(cf_role=timeseries_id(3), ncdim%timeseries(26)) = [[102, ..., --]]
>>> f = cfdm.example_domain(5)
>>> print(f)
Dimension coords: time(118) = [1959-01-01 06:00:00, ..., 1959-02-28 18:00:00]
: latitude(5) = [-75.0, ..., 75.0] degrees_north
: longitude(8) = [22.5, ..., 337.5] degrees_east
: air_pressure(1) = [850.0] hPa
>>> f = cfdm.example_domain(6)
>>> print(f)
Dimension coords: time(4) = [2000-01-16 12:00:00, ..., 2000-04-15 00:00:00]
Auxiliary coords: latitude(cf_role=timeseries_id(2)) = [25.0, 7.0] degrees_north
: longitude(cf_role=timeseries_id(2)) = [10.0, 40.0] degrees_east
: cf_role=timeseries_id(cf_role=timeseries_id(2)) = [b'x1', b'y2']
: ncvar%z(cf_role=timeseries_id(2), 3, 4) = [[[1.0, ..., --]]] m
Coord references: grid_mapping_name:latitude_longitude
>>> f = cfdm.example_domain(7)
>>> print(f)
Dimension coords: time(3) = [1979-05-01 12:00:00, 1979-05-02 12:00:00, 1979-05-03 12:00:00] gregorian
: air_pressure(1) = [850.0] hPa
: grid_latitude(4) = [0.44, ..., -0.88] degrees
: grid_longitude(5) = [-1.18, ..., 0.58] degrees
Auxiliary coords: latitude(grid_latitude(4), grid_longitude(5)) = [[52.4243, ..., 51.1163]] degrees_north
: longitude(grid_latitude(4), grid_longitude(5)) = [[8.0648, ..., 10.9238]] degrees_east
Coord references: grid_mapping_name:rotated_latitude_longitude
"""
return _func(n).get_domain()
| 38.93066 | 125 | 0.374667 |
cb688bcb3b82363afbee882f18c5da6615b55dfe | 451,653 | html | HTML | docs/html/_modules/sqlalchemy/sql/schema.html | aspuru-guzik-group/mission_control | bfe930e1038e9e0d6c4bb327474766e85b2190cb | [
"Apache-2.0"
] | 3 | 2017-09-01T19:49:59.000Z | 2018-06-04T10:30:01.000Z | docs/html/_modules/sqlalchemy/sql/schema.html | aspuru-guzik-group/mission_control | bfe930e1038e9e0d6c4bb327474766e85b2190cb | [
"Apache-2.0"
] | null | null | null | docs/html/_modules/sqlalchemy/sql/schema.html | aspuru-guzik-group/mission_control | bfe930e1038e9e0d6c4bb327474766e85b2190cb | [
"Apache-2.0"
] | 1 | 2018-12-13T19:48:27.000Z | 2018-12-13T19:48:27.000Z |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sqlalchemy.sql.schema — MissionControl 0.0.1 documentation</title>
<link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
<link rel="index" title="Index"
href="../../../genindex.html"/>
<link rel="search" title="Search" href="../../../search.html"/>
<link rel="top" title="MissionControl 0.0.1 documentation" href="../../../index.html"/>
<link rel="up" title="Module code" href="../../index.html"/>
<script src="../../../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../../../index.html" class="icon icon-home"> MissionControl
</a>
<div class="version">
0.0.1
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../user_guide.html">User Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../examples.html">Examples</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../api.html">API Documentation</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../../index.html">MissionControl</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../../index.html">Docs</a> »</li>
<li><a href="../../index.html">Module code</a> »</li>
<li>sqlalchemy.sql.schema</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<h1>Source code for sqlalchemy.sql.schema</h1><div class="highlight"><pre>
<span></span><span class="c1"># sql/schema.py</span>
<span class="c1"># Copyright (C) 2005-2017 the SQLAlchemy authors and contributors</span>
<span class="c1"># <see AUTHORS file></span>
<span class="c1">#</span>
<span class="c1"># This module is part of SQLAlchemy and is released under</span>
<span class="c1"># the MIT License: http://www.opensource.org/licenses/mit-license.php</span>
<span class="sd">"""The schema module provides the building blocks for database metadata.</span>
<span class="sd">Each element within this module describes a database entity which can be</span>
<span class="sd">created and dropped, or is otherwise part of such an entity. Examples include</span>
<span class="sd">tables, columns, sequences, and indexes.</span>
<span class="sd">All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as</span>
<span class="sd">defined in this module they are intended to be agnostic of any vendor-specific</span>
<span class="sd">constructs.</span>
<span class="sd">A collection of entities are grouped into a unit called</span>
<span class="sd">:class:`~sqlalchemy.schema.MetaData`. MetaData serves as a logical grouping of</span>
<span class="sd">schema elements, and can also be associated with an actual database connection</span>
<span class="sd">such that operations involving the contained elements can contact the database</span>
<span class="sd">as needed.</span>
<span class="sd">Two of the elements here also build upon their "syntactic" counterparts, which</span>
<span class="sd">are defined in :class:`~sqlalchemy.sql.expression.`, specifically</span>
<span class="sd">:class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`.</span>
<span class="sd">Since these objects are part of the SQL expression language, they are usable</span>
<span class="sd">as components in SQL expressions.</span>
<span class="sd">"""</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">absolute_import</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="k">import</span> <span class="n">exc</span><span class="p">,</span> <span class="n">util</span><span class="p">,</span> <span class="n">event</span><span class="p">,</span> <span class="n">inspection</span>
<span class="kn">from</span> <span class="nn">.base</span> <span class="k">import</span> <span class="n">SchemaEventTarget</span><span class="p">,</span> <span class="n">DialectKWArgs</span>
<span class="kn">import</span> <span class="nn">operator</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">visitors</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">type_api</span>
<span class="kn">from</span> <span class="nn">.base</span> <span class="k">import</span> <span class="n">_bind_or_error</span><span class="p">,</span> <span class="n">ColumnCollection</span>
<span class="kn">from</span> <span class="nn">.elements</span> <span class="k">import</span> <span class="n">ClauseElement</span><span class="p">,</span> <span class="n">ColumnClause</span><span class="p">,</span> \
<span class="n">_as_truncated</span><span class="p">,</span> <span class="n">TextClause</span><span class="p">,</span> <span class="n">_literal_as_text</span><span class="p">,</span>\
<span class="n">ColumnElement</span><span class="p">,</span> <span class="n">quoted_name</span>
<span class="kn">from</span> <span class="nn">.selectable</span> <span class="k">import</span> <span class="n">TableClause</span>
<span class="kn">import</span> <span class="nn">collections</span>
<span class="kn">import</span> <span class="nn">sqlalchemy</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">ddl</span>
<span class="n">RETAIN_SCHEMA</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">symbol</span><span class="p">(</span><span class="s1">'retain_schema'</span><span class="p">)</span>
<span class="n">BLANK_SCHEMA</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">symbol</span><span class="p">(</span>
<span class="s1">'blank_schema'</span><span class="p">,</span>
<span class="sd">"""Symbol indicating that a :class:`.Table` or :class:`.Sequence`</span>
<span class="sd"> should have 'None' for its schema, even if the parent</span>
<span class="sd"> :class:`.MetaData` has specified a schema.</span>
<span class="sd"> .. versionadded:: 1.0.14</span>
<span class="sd"> """</span>
<span class="p">)</span>
<span class="k">def</span> <span class="nf">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">):</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="n">name</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">schema</span> <span class="o">+</span> <span class="s2">"."</span> <span class="o">+</span> <span class="n">name</span>
<span class="nd">@inspection</span><span class="o">.</span><span class="n">_self_inspects</span>
<span class="k">class</span> <span class="nc">SchemaItem</span><span class="p">(</span><span class="n">SchemaEventTarget</span><span class="p">,</span> <span class="n">visitors</span><span class="o">.</span><span class="n">Visitable</span><span class="p">):</span>
<span class="sd">"""Base class for items that define a database schema."""</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'schema_item'</span>
<span class="k">def</span> <span class="nf">_init_items</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="sd">"""Initialize the list of child items for this SchemaItem."""</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">args</span><span class="p">:</span>
<span class="k">if</span> <span class="n">item</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">item</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">get_children</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="sd">"""used to allow SchemaVisitor access"""</span>
<span class="k">return</span> <span class="p">[]</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">generic_repr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">omit_kwarg</span><span class="o">=</span><span class="p">[</span><span class="s1">'info'</span><span class="p">])</span>
<span class="nd">@property</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">deprecated</span><span class="p">(</span><span class="s1">'0.9'</span><span class="p">,</span> <span class="s1">'Use ``<obj>.name.quote``'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">quote</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the value of the ``quote`` flag passed</span>
<span class="sd"> to this schema object, for those schema items which</span>
<span class="sd"> have a ``name`` field.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="o">.</span><span class="n">quote</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">info</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Info dictionary associated with the object, allowing user-defined</span>
<span class="sd"> data to be associated with this :class:`.SchemaItem`.</span>
<span class="sd"> The dictionary is automatically generated when first accessed.</span>
<span class="sd"> It can also be specified in the constructor of some objects,</span>
<span class="sd"> such as :class:`.Table` and :class:`.Column`.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="p">{}</span>
<span class="k">def</span> <span class="nf">_schema_item_copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">schema_item</span><span class="p">):</span>
<span class="k">if</span> <span class="s1">'info'</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">:</span>
<span class="n">schema_item</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">info</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="n">schema_item</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">_update</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">dispatch</span><span class="p">)</span>
<span class="k">return</span> <span class="n">schema_item</span>
<span class="k">def</span> <span class="nf">_translate_schema</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">effective_schema</span><span class="p">,</span> <span class="n">map_</span><span class="p">):</span>
<span class="k">return</span> <span class="n">map_</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">effective_schema</span><span class="p">,</span> <span class="n">effective_schema</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Table</span><span class="p">(</span><span class="n">DialectKWArgs</span><span class="p">,</span> <span class="n">SchemaItem</span><span class="p">,</span> <span class="n">TableClause</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Represent a table in a database.</span>
<span class="sd"> e.g.::</span>
<span class="sd"> mytable = Table("mytable", metadata,</span>
<span class="sd"> Column('mytable_id', Integer, primary_key=True),</span>
<span class="sd"> Column('value', String(50))</span>
<span class="sd"> )</span>
<span class="sd"> The :class:`.Table` object constructs a unique instance of itself based</span>
<span class="sd"> on its name and optional schema name within the given</span>
<span class="sd"> :class:`.MetaData` object. Calling the :class:`.Table`</span>
<span class="sd"> constructor with the same name and same :class:`.MetaData` argument</span>
<span class="sd"> a second time will return the *same* :class:`.Table` object - in this way</span>
<span class="sd"> the :class:`.Table` constructor acts as a registry function.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`metadata_describing` - Introduction to database metadata</span>
<span class="sd"> Constructor arguments are as follows:</span>
<span class="sd"> :param name: The name of this table as represented in the database.</span>
<span class="sd"> The table name, along with the value of the ``schema`` parameter,</span>
<span class="sd"> forms a key which uniquely identifies this :class:`.Table` within</span>
<span class="sd"> the owning :class:`.MetaData` collection.</span>
<span class="sd"> Additional calls to :class:`.Table` with the same name, metadata,</span>
<span class="sd"> and schema name will return the same :class:`.Table` object.</span>
<span class="sd"> Names which contain no upper case characters</span>
<span class="sd"> will be treated as case insensitive names, and will not be quoted</span>
<span class="sd"> unless they are a reserved word or contain special characters.</span>
<span class="sd"> A name with any number of upper case characters is considered</span>
<span class="sd"> to be case sensitive, and will be sent as quoted.</span>
<span class="sd"> To enable unconditional quoting for the table name, specify the flag</span>
<span class="sd"> ``quote=True`` to the constructor, or use the :class:`.quoted_name`</span>
<span class="sd"> construct to specify the name.</span>
<span class="sd"> :param metadata: a :class:`.MetaData` object which will contain this</span>
<span class="sd"> table. The metadata is used as a point of association of this table</span>
<span class="sd"> with other tables which are referenced via foreign key. It also</span>
<span class="sd"> may be used to associate this table with a particular</span>
<span class="sd"> :class:`.Connectable`.</span>
<span class="sd"> :param \*args: Additional positional arguments are used primarily</span>
<span class="sd"> to add the list of :class:`.Column` objects contained within this</span>
<span class="sd"> table. Similar to the style of a CREATE TABLE statement, other</span>
<span class="sd"> :class:`.SchemaItem` constructs may be added here, including</span>
<span class="sd"> :class:`.PrimaryKeyConstraint`, and :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> :param autoload: Defaults to False, unless :paramref:`.Table.autoload_with`</span>
<span class="sd"> is set in which case it defaults to True; :class:`.Column` objects</span>
<span class="sd"> for this table should be reflected from the database, possibly</span>
<span class="sd"> augmenting or replacing existing :class:`.Column` objects that were</span>
<span class="sd"> explicitly specified.</span>
<span class="sd"> .. versionchanged:: 1.0.0 setting the :paramref:`.Table.autoload_with`</span>
<span class="sd"> parameter implies that :paramref:`.Table.autoload` will default</span>
<span class="sd"> to True.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`metadata_reflection_toplevel`</span>
<span class="sd"> :param autoload_replace: Defaults to ``True``; when using</span>
<span class="sd"> :paramref:`.Table.autoload`</span>
<span class="sd"> in conjunction with :paramref:`.Table.extend_existing`, indicates</span>
<span class="sd"> that :class:`.Column` objects present in the already-existing</span>
<span class="sd"> :class:`.Table` object should be replaced with columns of the same</span>
<span class="sd"> name retrieved from the autoload process. When ``False``, columns</span>
<span class="sd"> already present under existing names will be omitted from the</span>
<span class="sd"> reflection process.</span>
<span class="sd"> Note that this setting does not impact :class:`.Column` objects</span>
<span class="sd"> specified programmatically within the call to :class:`.Table` that</span>
<span class="sd"> also is autoloading; those :class:`.Column` objects will always</span>
<span class="sd"> replace existing columns of the same name when</span>
<span class="sd"> :paramref:`.Table.extend_existing` is ``True``.</span>
<span class="sd"> .. versionadded:: 0.7.5</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.Table.autoload`</span>
<span class="sd"> :paramref:`.Table.extend_existing`</span>
<span class="sd"> :param autoload_with: An :class:`.Engine` or :class:`.Connection` object</span>
<span class="sd"> with which this :class:`.Table` object will be reflected; when</span>
<span class="sd"> set to a non-None value, it implies that :paramref:`.Table.autoload`</span>
<span class="sd"> is ``True``. If left unset, but :paramref:`.Table.autoload` is</span>
<span class="sd"> explicitly set to ``True``, an autoload operation will attempt to</span>
<span class="sd"> proceed by locating an :class:`.Engine` or :class:`.Connection` bound</span>
<span class="sd"> to the underlying :class:`.MetaData` object.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.Table.autoload`</span>
<span class="sd"> :param extend_existing: When ``True``, indicates that if this</span>
<span class="sd"> :class:`.Table` is already present in the given :class:`.MetaData`,</span>
<span class="sd"> apply further arguments within the constructor to the existing</span>
<span class="sd"> :class:`.Table`.</span>
<span class="sd"> If :paramref:`.Table.extend_existing` or</span>
<span class="sd"> :paramref:`.Table.keep_existing` are not set, and the given name</span>
<span class="sd"> of the new :class:`.Table` refers to a :class:`.Table` that is</span>
<span class="sd"> already present in the target :class:`.MetaData` collection, and</span>
<span class="sd"> this :class:`.Table` specifies additional columns or other constructs</span>
<span class="sd"> or flags that modify the table's state, an</span>
<span class="sd"> error is raised. The purpose of these two mutually-exclusive flags</span>
<span class="sd"> is to specify what action should be taken when a :class:`.Table`</span>
<span class="sd"> is specified that matches an existing :class:`.Table`, yet specifies</span>
<span class="sd"> additional constructs.</span>
<span class="sd"> :paramref:`.Table.extend_existing` will also work in conjunction</span>
<span class="sd"> with :paramref:`.Table.autoload` to run a new reflection</span>
<span class="sd"> operation against the database, even if a :class:`.Table`</span>
<span class="sd"> of the same name is already present in the target</span>
<span class="sd"> :class:`.MetaData`; newly reflected :class:`.Column` objects</span>
<span class="sd"> and other options will be added into the state of the</span>
<span class="sd"> :class:`.Table`, potentially overwriting existing columns</span>
<span class="sd"> and options of the same name.</span>
<span class="sd"> .. versionchanged:: 0.7.4 :paramref:`.Table.extend_existing` will</span>
<span class="sd"> invoke a new reflection operation when combined with</span>
<span class="sd"> :paramref:`.Table.autoload` set to True.</span>
<span class="sd"> As is always the case with :paramref:`.Table.autoload`,</span>
<span class="sd"> :class:`.Column` objects can be specified in the same :class:`.Table`</span>
<span class="sd"> constructor, which will take precedence. Below, the existing</span>
<span class="sd"> table ``mytable`` will be augmented with :class:`.Column` objects</span>
<span class="sd"> both reflected from the database, as well as the given :class:`.Column`</span>
<span class="sd"> named "y"::</span>
<span class="sd"> Table("mytable", metadata,</span>
<span class="sd"> Column('y', Integer),</span>
<span class="sd"> extend_existing=True,</span>
<span class="sd"> autoload=True,</span>
<span class="sd"> autoload_with=engine</span>
<span class="sd"> )</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.Table.autoload`</span>
<span class="sd"> :paramref:`.Table.autoload_replace`</span>
<span class="sd"> :paramref:`.Table.keep_existing`</span>
<span class="sd"> :param implicit_returning: True by default - indicates that</span>
<span class="sd"> RETURNING can be used by default to fetch newly inserted primary key</span>
<span class="sd"> values, for backends which support this. Note that</span>
<span class="sd"> create_engine() also provides an implicit_returning flag.</span>
<span class="sd"> :param include_columns: A list of strings indicating a subset of</span>
<span class="sd"> columns to be loaded via the ``autoload`` operation; table columns who</span>
<span class="sd"> aren't present in this list will not be represented on the resulting</span>
<span class="sd"> ``Table`` object. Defaults to ``None`` which indicates all columns</span>
<span class="sd"> should be reflected.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> :param keep_existing: When ``True``, indicates that if this Table</span>
<span class="sd"> is already present in the given :class:`.MetaData`, ignore</span>
<span class="sd"> further arguments within the constructor to the existing</span>
<span class="sd"> :class:`.Table`, and return the :class:`.Table` object as</span>
<span class="sd"> originally created. This is to allow a function that wishes</span>
<span class="sd"> to define a new :class:`.Table` on first call, but on</span>
<span class="sd"> subsequent calls will return the same :class:`.Table`,</span>
<span class="sd"> without any of the declarations (particularly constraints)</span>
<span class="sd"> being applied a second time.</span>
<span class="sd"> If :paramref:`.Table.extend_existing` or</span>
<span class="sd"> :paramref:`.Table.keep_existing` are not set, and the given name</span>
<span class="sd"> of the new :class:`.Table` refers to a :class:`.Table` that is</span>
<span class="sd"> already present in the target :class:`.MetaData` collection, and</span>
<span class="sd"> this :class:`.Table` specifies additional columns or other constructs</span>
<span class="sd"> or flags that modify the table's state, an</span>
<span class="sd"> error is raised. The purpose of these two mutually-exclusive flags</span>
<span class="sd"> is to specify what action should be taken when a :class:`.Table`</span>
<span class="sd"> is specified that matches an existing :class:`.Table`, yet specifies</span>
<span class="sd"> additional constructs.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.Table.extend_existing`</span>
<span class="sd"> :param listeners: A list of tuples of the form ``(<eventname>, <fn>)``</span>
<span class="sd"> which will be passed to :func:`.event.listen` upon construction.</span>
<span class="sd"> This alternate hook to :func:`.event.listen` allows the establishment</span>
<span class="sd"> of a listener function specific to this :class:`.Table` before</span>
<span class="sd"> the "autoload" process begins. Particularly useful for</span>
<span class="sd"> the :meth:`.DDLEvents.column_reflect` event::</span>
<span class="sd"> def listen_for_reflect(table, column_info):</span>
<span class="sd"> "handle the column reflection event"</span>
<span class="sd"> # ...</span>
<span class="sd"> t = Table(</span>
<span class="sd"> 'sometable',</span>
<span class="sd"> autoload=True,</span>
<span class="sd"> listeners=[</span>
<span class="sd"> ('column_reflect', listen_for_reflect)</span>
<span class="sd"> ])</span>
<span class="sd"> :param mustexist: When ``True``, indicates that this Table must already</span>
<span class="sd"> be present in the given :class:`.MetaData` collection, else</span>
<span class="sd"> an exception is raised.</span>
<span class="sd"> :param prefixes:</span>
<span class="sd"> A list of strings to insert after CREATE in the CREATE TABLE</span>
<span class="sd"> statement. They will be separated by spaces.</span>
<span class="sd"> :param quote: Force quoting of this table's name on or off, corresponding</span>
<span class="sd"> to ``True`` or ``False``. When left at its default of ``None``,</span>
<span class="sd"> the column identifier will be quoted according to whether the name is</span>
<span class="sd"> case sensitive (identifiers with at least one upper case character are</span>
<span class="sd"> treated as case sensitive), or if it's a reserved word. This flag</span>
<span class="sd"> is only needed to force quoting of a reserved word which is not known</span>
<span class="sd"> by the SQLAlchemy dialect.</span>
<span class="sd"> :param quote_schema: same as 'quote' but applies to the schema identifier.</span>
<span class="sd"> :param schema: The schema name for this table, which is required if</span>
<span class="sd"> the table resides in a schema other than the default selected schema</span>
<span class="sd"> for the engine's database connection. Defaults to ``None``.</span>
<span class="sd"> If the owning :class:`.MetaData` of this :class:`.Table` specifies</span>
<span class="sd"> its own :paramref:`.MetaData.schema` parameter, then that schema</span>
<span class="sd"> name will be applied to this :class:`.Table` if the schema parameter</span>
<span class="sd"> here is set to ``None``. To set a blank schema name on a :class:`.Table`</span>
<span class="sd"> that would otherwise use the schema set on the owning :class:`.MetaData`,</span>
<span class="sd"> specify the special symbol :attr:`.BLANK_SCHEMA`.</span>
<span class="sd"> .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to</span>
<span class="sd"> allow a :class:`.Table` to have a blank schema name even when the</span>
<span class="sd"> parent :class:`.MetaData` specifies :paramref:`.MetaData.schema`.</span>
<span class="sd"> The quoting rules for the schema name are the same as those for the</span>
<span class="sd"> ``name`` parameter, in that quoting is applied for reserved words or</span>
<span class="sd"> case-sensitive names; to enable unconditional quoting for the</span>
<span class="sd"> schema name, specify the flag</span>
<span class="sd"> ``quote_schema=True`` to the constructor, or use the</span>
<span class="sd"> :class:`.quoted_name` construct to specify the name.</span>
<span class="sd"> :param useexisting: Deprecated. Use :paramref:`.Table.extend_existing`.</span>
<span class="sd"> :param \**kw: Additional keyword arguments not mentioned above are</span>
<span class="sd"> dialect specific, and passed in the form ``<dialectname>_<argname>``.</span>
<span class="sd"> See the documentation regarding an individual dialect at</span>
<span class="sd"> :ref:`dialect_toplevel` for detail on documented arguments.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'table'</span>
<span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">args</span><span class="p">:</span>
<span class="c1"># python3k pickle seems to call this</span>
<span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">name</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span>
<span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">"Table() takes at least two arguments"</span><span class="p">)</span>
<span class="n">schema</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'schema'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="n">metadata</span><span class="o">.</span><span class="n">schema</span>
<span class="k">elif</span> <span class="n">schema</span> <span class="ow">is</span> <span class="n">BLANK_SCHEMA</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">keep_existing</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'keep_existing'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="n">extend_existing</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'extend_existing'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'useexisting'</span> <span class="ow">in</span> <span class="n">kw</span><span class="p">:</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s2">"useexisting is deprecated. Use extend_existing."</span>
<span class="n">util</span><span class="o">.</span><span class="n">warn_deprecated</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="k">if</span> <span class="n">extend_existing</span><span class="p">:</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s2">"useexisting is synonymous with extend_existing."</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="n">extend_existing</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'useexisting'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="k">if</span> <span class="n">keep_existing</span> <span class="ow">and</span> <span class="n">extend_existing</span><span class="p">:</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s2">"keep_existing and extend_existing are mutually exclusive."</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="n">mustexist</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'mustexist'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">keep_existing</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">extend_existing</span> <span class="ow">and</span> <span class="nb">bool</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"Table '</span><span class="si">%s</span><span class="s2">' is already defined for this MetaData "</span>
<span class="s2">"instance. Specify 'extend_existing=True' "</span>
<span class="s2">"to redefine "</span>
<span class="s2">"options and columns on an "</span>
<span class="s2">"existing Table object."</span> <span class="o">%</span> <span class="n">key</span><span class="p">)</span>
<span class="n">table</span> <span class="o">=</span> <span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="k">if</span> <span class="n">extend_existing</span><span class="p">:</span>
<span class="n">table</span><span class="o">.</span><span class="n">_init_existing</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="k">return</span> <span class="n">table</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="n">mustexist</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"Table '</span><span class="si">%s</span><span class="s2">' not defined"</span> <span class="o">%</span> <span class="p">(</span><span class="n">key</span><span class="p">))</span>
<span class="n">table</span> <span class="o">=</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">before_parent_attach</span><span class="p">(</span><span class="n">table</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">_add_table</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">table</span><span class="o">.</span><span class="n">_init</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">after_parent_attach</span><span class="p">(</span><span class="n">table</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
<span class="k">return</span> <span class="n">table</span>
<span class="k">except</span><span class="p">:</span>
<span class="k">with</span> <span class="n">util</span><span class="o">.</span><span class="n">safe_reraise</span><span class="p">():</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">_remove_table</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">deprecated</span><span class="p">(</span><span class="s1">'0.9'</span><span class="p">,</span> <span class="s1">'Use ``table.schema.quote``'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">quote_schema</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the value of the ``quote_schema`` flag passed</span>
<span class="sd"> to this :class:`.Table`.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="o">.</span><span class="n">quote</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="sd">"""Constructor for :class:`~.schema.Table`.</span>
<span class="sd"> This method is a no-op. See the top-level</span>
<span class="sd"> documentation for :class:`~.schema.Table`</span>
<span class="sd"> for constructor arguments.</span>
<span class="sd"> """</span>
<span class="c1"># __init__ is overridden to prevent __new__ from</span>
<span class="c1"># calling the superclass constructor.</span>
<span class="k">def</span> <span class="nf">_init</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">Table</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span>
<span class="n">quoted_name</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'quote'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span> <span class="o">=</span> <span class="n">metadata</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'schema'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">metadata</span><span class="o">.</span><span class="n">schema</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="ow">is</span> <span class="n">BLANK_SCHEMA</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">quote_schema</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'quote_schema'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">,</span> <span class="n">quote_schema</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">indexes</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraints</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_columns</span> <span class="o">=</span> <span class="n">ColumnCollection</span><span class="p">()</span>
<span class="n">PrimaryKeyConstraint</span><span class="p">(</span><span class="n">_implicit_generated</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span><span class="o">.</span>\
<span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_extra_dependencies</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">fullname</span> <span class="o">=</span> <span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">fullname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
<span class="n">autoload_with</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload_with'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">autoload</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload'</span><span class="p">,</span> <span class="n">autoload_with</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">)</span>
<span class="c1"># this argument is only used with _init_existing()</span>
<span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload_replace'</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="n">_extend_on</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s2">"_extend_on"</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">include_columns</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'include_columns'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">implicit_returning</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'implicit_returning'</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'info'</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'info'</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'listeners'</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="n">listeners</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'listeners'</span><span class="p">)</span>
<span class="k">for</span> <span class="n">evt</span><span class="p">,</span> <span class="n">fn</span> <span class="ow">in</span> <span class="n">listeners</span><span class="p">:</span>
<span class="n">event</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">evt</span><span class="p">,</span> <span class="n">fn</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_prefixes</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'prefixes'</span><span class="p">,</span> <span class="p">[])</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_extra_kwargs</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="c1"># load column definitions from the database if 'autoload' is defined</span>
<span class="c1"># we do it after the table is in the singleton dictionary to support</span>
<span class="c1"># circular foreign keys</span>
<span class="k">if</span> <span class="n">autoload</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_autoload</span><span class="p">(</span>
<span class="n">metadata</span><span class="p">,</span> <span class="n">autoload_with</span><span class="p">,</span>
<span class="n">include_columns</span><span class="p">,</span> <span class="n">_extend_on</span><span class="o">=</span><span class="n">_extend_on</span><span class="p">)</span>
<span class="c1"># initialize all the column, etc. objects. done after reflection to</span>
<span class="c1"># allow user-overrides</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_init_items</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_autoload</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">autoload_with</span><span class="p">,</span> <span class="n">include_columns</span><span class="p">,</span>
<span class="n">exclude_columns</span><span class="o">=</span><span class="p">(),</span> <span class="n">_extend_on</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">autoload_with</span><span class="p">:</span>
<span class="n">autoload_with</span><span class="o">.</span><span class="n">run_callable</span><span class="p">(</span>
<span class="n">autoload_with</span><span class="o">.</span><span class="n">dialect</span><span class="o">.</span><span class="n">reflecttable</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">include_columns</span><span class="p">,</span> <span class="n">exclude_columns</span><span class="p">,</span>
<span class="n">_extend_on</span><span class="o">=</span><span class="n">_extend_on</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span>
<span class="n">metadata</span><span class="p">,</span>
<span class="n">msg</span><span class="o">=</span><span class="s2">"No engine is bound to this Table's MetaData. "</span>
<span class="s2">"Pass an engine to the Table via "</span>
<span class="s2">"autoload_with=<someengine>, "</span>
<span class="s2">"or associate the MetaData with an engine via "</span>
<span class="s2">"metadata.bind=<someengine>"</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">run_callable</span><span class="p">(</span>
<span class="n">bind</span><span class="o">.</span><span class="n">dialect</span><span class="o">.</span><span class="n">reflecttable</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">include_columns</span><span class="p">,</span> <span class="n">exclude_columns</span><span class="p">,</span>
<span class="n">_extend_on</span><span class="o">=</span><span class="n">_extend_on</span>
<span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_sorted_constraints</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the set of constraints as a list, sorted by creation</span>
<span class="sd"> order.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">constraints</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">c</span><span class="p">:</span> <span class="n">c</span><span class="o">.</span><span class="n">_creation_order</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">foreign_key_constraints</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">""":class:`.ForeignKeyConstraint` objects referred to by this</span>
<span class="sd"> :class:`.Table`.</span>
<span class="sd"> This list is produced from the collection of :class:`.ForeignKey`</span>
<span class="sd"> objects currently associated.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="nb">set</span><span class="p">(</span><span class="n">fkc</span><span class="o">.</span><span class="n">constraint</span> <span class="k">for</span> <span class="n">fkc</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_init_existing</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">autoload_with</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload_with'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">autoload</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload'</span><span class="p">,</span> <span class="n">autoload_with</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">autoload_replace</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoload_replace'</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="n">schema</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'schema'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">_extend_on</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'_extend_on'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">and</span> <span class="n">schema</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Can't change schema of existing table from '</span><span class="si">%s</span><span class="s2">' to '</span><span class="si">%s</span><span class="s2">'"</span><span class="p">,</span>
<span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">,</span> <span class="n">schema</span><span class="p">))</span>
<span class="n">include_columns</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'include_columns'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">include_columns</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">c</span><span class="p">:</span>
<span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">include_columns</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_columns</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">'quote'</span><span class="p">,</span> <span class="s1">'quote_schema'</span><span class="p">):</span>
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Can't redefine 'quote' or 'quote_schema' arguments"</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'info'</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'info'</span><span class="p">)</span>
<span class="k">if</span> <span class="n">autoload</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">autoload_replace</span><span class="p">:</span>
<span class="c1"># don't replace columns already present.</span>
<span class="c1"># we'd like to do this for constraints also however we don't</span>
<span class="c1"># have simple de-duping for unnamed constraints.</span>
<span class="n">exclude_columns</span> <span class="o">=</span> <span class="p">[</span><span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">c</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">exclude_columns</span> <span class="o">=</span> <span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_autoload</span><span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="p">,</span> <span class="n">autoload_with</span><span class="p">,</span>
<span class="n">include_columns</span><span class="p">,</span> <span class="n">exclude_columns</span><span class="p">,</span> <span class="n">_extend_on</span><span class="o">=</span><span class="n">_extend_on</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_extra_kwargs</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_init_items</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_extra_kwargs</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_validate_dialect_kwargs</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_init_collections</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">def</span> <span class="nf">_reset_exported</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">pass</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_autoincrement_column</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="o">.</span><span class="n">_autoincrement_column</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">key</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the 'key' for this :class:`.Table`.</span>
<span class="sd"> This value is used as the dictionary key within the</span>
<span class="sd"> :attr:`.MetaData.tables` collection. It is typically the same</span>
<span class="sd"> as that of :attr:`.Table.name` for a table with no</span>
<span class="sd"> :attr:`.Table.schema` set; otherwise it is typically of the form</span>
<span class="sd"> ``schemaname.tablename``.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"Table(</span><span class="si">%s</span><span class="s2">)"</span> <span class="o">%</span> <span class="s1">', '</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)]</span> <span class="o">+</span> <span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="p">)]</span> <span class="o">+</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">]</span> <span class="o">+</span>
<span class="p">[</span><span class="s2">"</span><span class="si">%s</span><span class="s2">=</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">)))</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'schema'</span><span class="p">]])</span>
<span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">description</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the connectable associated with this Table."""</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">metadata</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">bind</span> <span class="ow">or</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">add_is_dependent_on</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="sd">"""Add a 'dependency' for this Table.</span>
<span class="sd"> This is another Table object which must be created</span>
<span class="sd"> first before this one can, or dropped after this one.</span>
<span class="sd"> Usually, dependencies between tables are determined via</span>
<span class="sd"> ForeignKey objects. However, for other situations that</span>
<span class="sd"> create dependencies outside of foreign keys (rules, inheriting),</span>
<span class="sd"> this method can manually establish such a link.</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_extra_dependencies</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">append_column</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="sd">"""Append a :class:`~.schema.Column` to this :class:`~.schema.Table`.</span>
<span class="sd"> The "key" of the newly added :class:`~.schema.Column`, i.e. the</span>
<span class="sd"> value of its ``.key`` attribute, will then be available</span>
<span class="sd"> in the ``.c`` collection of this :class:`~.schema.Table`, and the</span>
<span class="sd"> column definition will be included in any CREATE TABLE, SELECT,</span>
<span class="sd"> UPDATE, etc. statements generated from this :class:`~.schema.Table`</span>
<span class="sd"> construct.</span>
<span class="sd"> Note that this does **not** change the definition of the table</span>
<span class="sd"> as it exists within any underlying database, assuming that</span>
<span class="sd"> table has already been created in the database. Relational</span>
<span class="sd"> databases support the addition of columns to existing tables</span>
<span class="sd"> using the SQL ALTER command, which would need to be</span>
<span class="sd"> emitted for an already-existing table that doesn't contain</span>
<span class="sd"> the newly added column.</span>
<span class="sd"> """</span>
<span class="n">column</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">append_constraint</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">constraint</span><span class="p">):</span>
<span class="sd">"""Append a :class:`~.schema.Constraint` to this</span>
<span class="sd"> :class:`~.schema.Table`.</span>
<span class="sd"> This has the effect of the constraint being included in any</span>
<span class="sd"> future CREATE TABLE statement, assuming specific DDL creation</span>
<span class="sd"> events have not been associated with the given</span>
<span class="sd"> :class:`~.schema.Constraint` object.</span>
<span class="sd"> Note that this does **not** produce the constraint within the</span>
<span class="sd"> relational database automatically, for a table that already exists</span>
<span class="sd"> in the database. To add a constraint to an</span>
<span class="sd"> existing relational database table, the SQL ALTER command must</span>
<span class="sd"> be used. SQLAlchemy also provides the</span>
<span class="sd"> :class:`.AddConstraint` construct which can produce this SQL when</span>
<span class="sd"> invoked as an executable clause.</span>
<span class="sd"> """</span>
<span class="n">constraint</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">append_ddl_listener</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">event_name</span><span class="p">,</span> <span class="n">listener</span><span class="p">):</span>
<span class="sd">"""Append a DDL event listener to this ``Table``.</span>
<span class="sd"> .. deprecated:: 0.7</span>
<span class="sd"> See :class:`.DDLEvents`.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">adapt_listener</span><span class="p">(</span><span class="n">target</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">listener</span><span class="p">(</span><span class="n">event_name</span><span class="p">,</span> <span class="n">target</span><span class="p">,</span> <span class="n">connection</span><span class="p">)</span>
<span class="n">event</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s2">""</span> <span class="o">+</span> <span class="n">event_name</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">'-'</span><span class="p">,</span> <span class="s1">'_'</span><span class="p">),</span> <span class="n">adapt_listener</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">metadata</span><span class="p">):</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">_add_table</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span> <span class="o">=</span> <span class="n">metadata</span>
<span class="k">def</span> <span class="nf">get_children</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column_collections</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="n">schema_visitor</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">schema_visitor</span><span class="p">:</span>
<span class="k">return</span> <span class="n">TableClause</span><span class="o">.</span><span class="n">get_children</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">column_collections</span><span class="o">=</span><span class="n">column_collections</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="n">column_collections</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="p">[]</span>
<span class="k">def</span> <span class="nf">exists</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Return True if this table exists."""</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">return</span> <span class="n">bind</span><span class="o">.</span><span class="n">run_callable</span><span class="p">(</span><span class="n">bind</span><span class="o">.</span><span class="n">dialect</span><span class="o">.</span><span class="n">has_table</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="sd">"""Issue a ``CREATE`` statement for this</span>
<span class="sd"> :class:`.Table`, using the given :class:`.Connectable`</span>
<span class="sd"> for connectivity.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :meth:`.MetaData.create_all`.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaGenerator</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">drop</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="sd">"""Issue a ``DROP`` statement for this</span>
<span class="sd"> :class:`.Table`, using the given :class:`.Connectable`</span>
<span class="sd"> for connectivity.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :meth:`.MetaData.drop_all`.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaDropper</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">tometadata</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="n">RETAIN_SCHEMA</span><span class="p">,</span>
<span class="n">referred_schema_fn</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Return a copy of this :class:`.Table` associated with a different</span>
<span class="sd"> :class:`.MetaData`.</span>
<span class="sd"> E.g.::</span>
<span class="sd"> m1 = MetaData()</span>
<span class="sd"> user = Table('user', m1, Column('id', Integer, priamry_key=True))</span>
<span class="sd"> m2 = MetaData()</span>
<span class="sd"> user_copy = user.tometadata(m2)</span>
<span class="sd"> :param metadata: Target :class:`.MetaData` object, into which the</span>
<span class="sd"> new :class:`.Table` object will be created.</span>
<span class="sd"> :param schema: optional string name indicating the target schema.</span>
<span class="sd"> Defaults to the special symbol :attr:`.RETAIN_SCHEMA` which indicates</span>
<span class="sd"> that no change to the schema name should be made in the new</span>
<span class="sd"> :class:`.Table`. If set to a string name, the new :class:`.Table`</span>
<span class="sd"> will have this new name as the ``.schema``. If set to ``None``, the</span>
<span class="sd"> schema will be set to that of the schema set on the target</span>
<span class="sd"> :class:`.MetaData`, which is typically ``None`` as well, unless</span>
<span class="sd"> set explicitly::</span>
<span class="sd"> m2 = MetaData(schema='newschema')</span>
<span class="sd"> # user_copy_one will have "newschema" as the schema name</span>
<span class="sd"> user_copy_one = user.tometadata(m2, schema=None)</span>
<span class="sd"> m3 = MetaData() # schema defaults to None</span>
<span class="sd"> # user_copy_two will have None as the schema name</span>
<span class="sd"> user_copy_two = user.tometadata(m3, schema=None)</span>
<span class="sd"> :param referred_schema_fn: optional callable which can be supplied</span>
<span class="sd"> in order to provide for the schema name that should be assigned</span>
<span class="sd"> to the referenced table of a :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> The callable accepts this parent :class:`.Table`, the</span>
<span class="sd"> target schema that we are changing to, the</span>
<span class="sd"> :class:`.ForeignKeyConstraint` object, and the existing</span>
<span class="sd"> "target schema" of that constraint. The function should return the</span>
<span class="sd"> string schema name that should be applied.</span>
<span class="sd"> E.g.::</span>
<span class="sd"> def referred_schema_fn(table, to_schema,</span>
<span class="sd"> constraint, referred_schema):</span>
<span class="sd"> if referred_schema == 'base_tables':</span>
<span class="sd"> return referred_schema</span>
<span class="sd"> else:</span>
<span class="sd"> return to_schema</span>
<span class="sd"> new_table = table.tometadata(m2, schema="alt_schema",</span>
<span class="sd"> referred_schema_fn=referred_schema_fn)</span>
<span class="sd"> .. versionadded:: 0.9.2</span>
<span class="sd"> :param name: optional string name indicating the target table name.</span>
<span class="sd"> If not specified or None, the table name is retained. This allows</span>
<span class="sd"> a :class:`.Table` to be copied to the same :class:`.MetaData` target</span>
<span class="sd"> with a new name.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="n">RETAIN_SCHEMA</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span>
<span class="k">elif</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="n">metadata</span><span class="o">.</span><span class="n">schema</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">:</span>
<span class="n">util</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">"Table '</span><span class="si">%s</span><span class="s2">' already exists within the given "</span>
<span class="s2">"MetaData - not copying."</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">description</span><span class="p">)</span>
<span class="k">return</span> <span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="n">args</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">:</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="n">schema</span><span class="o">=</span><span class="n">schema</span><span class="p">))</span>
<span class="n">table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span>
<span class="n">name</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="n">schema</span><span class="p">,</span>
<span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">constraints</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">ForeignKeyConstraint</span><span class="p">):</span>
<span class="n">referred_schema</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">_referred_schema</span>
<span class="k">if</span> <span class="n">referred_schema_fn</span><span class="p">:</span>
<span class="n">fk_constraint_schema</span> <span class="o">=</span> <span class="n">referred_schema_fn</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">schema</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">referred_schema</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">fk_constraint_schema</span> <span class="o">=</span> <span class="p">(</span>
<span class="n">schema</span> <span class="k">if</span> <span class="n">referred_schema</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="k">else</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">append_constraint</span><span class="p">(</span>
<span class="n">c</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="n">schema</span><span class="o">=</span><span class="n">fk_constraint_schema</span><span class="p">,</span> <span class="n">target_table</span><span class="o">=</span><span class="n">table</span><span class="p">))</span>
<span class="k">elif</span> <span class="ow">not</span> <span class="n">c</span><span class="o">.</span><span class="n">_type_bound</span><span class="p">:</span>
<span class="c1"># skip unique constraints that would be generated</span>
<span class="c1"># by the 'unique' flag on Column</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">UniqueConstraint</span><span class="p">)</span> <span class="ow">and</span> \
<span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span> <span class="ow">and</span> \
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">columns</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">unique</span><span class="p">:</span>
<span class="k">continue</span>
<span class="n">table</span><span class="o">.</span><span class="n">append_constraint</span><span class="p">(</span>
<span class="n">c</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="n">schema</span><span class="o">=</span><span class="n">schema</span><span class="p">,</span> <span class="n">target_table</span><span class="o">=</span><span class="n">table</span><span class="p">))</span>
<span class="k">for</span> <span class="n">index</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">indexes</span><span class="p">:</span>
<span class="c1"># skip indexes that would be generated</span>
<span class="c1"># by the 'index' flag on Column</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">index</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span> <span class="ow">and</span> \
<span class="nb">list</span><span class="p">(</span><span class="n">index</span><span class="o">.</span><span class="n">columns</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">index</span><span class="p">:</span>
<span class="k">continue</span>
<span class="n">Index</span><span class="p">(</span><span class="n">index</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">unique</span><span class="o">=</span><span class="n">index</span><span class="o">.</span><span class="n">unique</span><span class="p">,</span>
<span class="o">*</span><span class="p">[</span><span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="p">[</span><span class="n">col</span><span class="p">]</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">index</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">keys</span><span class="p">()],</span>
<span class="o">**</span><span class="n">index</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Column</span><span class="p">(</span><span class="n">SchemaItem</span><span class="p">,</span> <span class="n">ColumnClause</span><span class="p">):</span>
<span class="sd">"""Represents a column in a database table."""</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'column'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""</span>
<span class="sd"> Construct a new ``Column`` object.</span>
<span class="sd"> :param name: The name of this column as represented in the database.</span>
<span class="sd"> This argument may be the first positional argument, or specified</span>
<span class="sd"> via keyword.</span>
<span class="sd"> Names which contain no upper case characters</span>
<span class="sd"> will be treated as case insensitive names, and will not be quoted</span>
<span class="sd"> unless they are a reserved word. Names with any number of upper</span>
<span class="sd"> case characters will be quoted and sent exactly. Note that this</span>
<span class="sd"> behavior applies even for databases which standardize upper</span>
<span class="sd"> case names as case insensitive such as Oracle.</span>
<span class="sd"> The name field may be omitted at construction time and applied</span>
<span class="sd"> later, at any time before the Column is associated with a</span>
<span class="sd"> :class:`.Table`. This is to support convenient</span>
<span class="sd"> usage within the :mod:`~sqlalchemy.ext.declarative` extension.</span>
<span class="sd"> :param type\_: The column's type, indicated using an instance which</span>
<span class="sd"> subclasses :class:`~sqlalchemy.types.TypeEngine`. If no arguments</span>
<span class="sd"> are required for the type, the class of the type can be sent</span>
<span class="sd"> as well, e.g.::</span>
<span class="sd"> # use a type with arguments</span>
<span class="sd"> Column('data', String(50))</span>
<span class="sd"> # use no arguments</span>
<span class="sd"> Column('level', Integer)</span>
<span class="sd"> The ``type`` argument may be the second positional argument</span>
<span class="sd"> or specified by keyword.</span>
<span class="sd"> If the ``type`` is ``None`` or is omitted, it will first default to</span>
<span class="sd"> the special type :class:`.NullType`. If and when this</span>
<span class="sd"> :class:`.Column` is made to refer to another column using</span>
<span class="sd"> :class:`.ForeignKey` and/or :class:`.ForeignKeyConstraint`, the type</span>
<span class="sd"> of the remote-referenced column will be copied to this column as</span>
<span class="sd"> well, at the moment that the foreign key is resolved against that</span>
<span class="sd"> remote :class:`.Column` object.</span>
<span class="sd"> .. versionchanged:: 0.9.0</span>
<span class="sd"> Support for propagation of type to a :class:`.Column` from its</span>
<span class="sd"> :class:`.ForeignKey` object has been improved and should be</span>
<span class="sd"> more reliable and timely.</span>
<span class="sd"> :param \*args: Additional positional arguments include various</span>
<span class="sd"> :class:`.SchemaItem` derived constructs which will be applied</span>
<span class="sd"> as options to the column. These include instances of</span>
<span class="sd"> :class:`.Constraint`, :class:`.ForeignKey`, :class:`.ColumnDefault`,</span>
<span class="sd"> and :class:`.Sequence`. In some cases an equivalent keyword</span>
<span class="sd"> argument is available such as ``server_default``, ``default``</span>
<span class="sd"> and ``unique``.</span>
<span class="sd"> :param autoincrement: Set up "auto increment" semantics for an integer</span>
<span class="sd"> primary key column. The default value is the string ``"auto"``</span>
<span class="sd"> which indicates that a single-column primary key that is of</span>
<span class="sd"> an INTEGER type with no stated client-side or python-side defaults</span>
<span class="sd"> should receive auto increment semantics automatically;</span>
<span class="sd"> all other varieties of primary key columns will not. This</span>
<span class="sd"> includes that :term:`DDL` such as PostgreSQL SERIAL or MySQL</span>
<span class="sd"> AUTO_INCREMENT will be emitted for this column during a table</span>
<span class="sd"> create, as well as that the column is assumed to generate new</span>
<span class="sd"> integer primary key values when an INSERT statement invokes which</span>
<span class="sd"> will be retrieved by the dialect.</span>
<span class="sd"> The flag may be set to ``True`` to indicate that a column which</span>
<span class="sd"> is part of a composite (e.g. multi-column) primary key should</span>
<span class="sd"> have autoincrement semantics, though note that only one column</span>
<span class="sd"> within a primary key may have this setting. It can also</span>
<span class="sd"> be set to ``True`` to indicate autoincrement semantics on a</span>
<span class="sd"> column that has a client-side or server-side default configured,</span>
<span class="sd"> however note that not all dialects can accommodate all styles</span>
<span class="sd"> of default as an "autoincrement". It can also be</span>
<span class="sd"> set to ``False`` on a single-column primary key that has a</span>
<span class="sd"> datatype of INTEGER in order to disable auto increment semantics</span>
<span class="sd"> for that column.</span>
<span class="sd"> .. versionchanged:: 1.1 The autoincrement flag now defaults to</span>
<span class="sd"> ``"auto"`` which indicates autoincrement semantics by default</span>
<span class="sd"> for single-column integer primary keys only; for composite</span>
<span class="sd"> (multi-column) primary keys, autoincrement is never implicitly</span>
<span class="sd"> enabled; as always, ``autoincrement=True`` will allow for</span>
<span class="sd"> at most one of those columns to be an "autoincrement" column.</span>
<span class="sd"> ``autoincrement=True`` may also be set on a :class:`.Column`</span>
<span class="sd"> that has an explicit client-side or server-side default,</span>
<span class="sd"> subject to limitations of the backend database and dialect.</span>
<span class="sd"> The setting *only* has an effect for columns which are:</span>
<span class="sd"> * Integer derived (i.e. INT, SMALLINT, BIGINT).</span>
<span class="sd"> * Part of the primary key</span>
<span class="sd"> * Not referring to another column via :class:`.ForeignKey`, unless</span>
<span class="sd"> the value is specified as ``'ignore_fk'``::</span>
<span class="sd"> # turn on autoincrement for this column despite</span>
<span class="sd"> # the ForeignKey()</span>
<span class="sd"> Column('id', ForeignKey('other.id'),</span>
<span class="sd"> primary_key=True, autoincrement='ignore_fk')</span>
<span class="sd"> It is typically not desirable to have "autoincrement" enabled</span>
<span class="sd"> on a column that refers to another via foreign key, as such a column</span>
<span class="sd"> is required to refer to a value that originates from elsewhere.</span>
<span class="sd"> The setting has these two effects on columns that meet the</span>
<span class="sd"> above criteria:</span>
<span class="sd"> * DDL issued for the column will include database-specific</span>
<span class="sd"> keywords intended to signify this column as an</span>
<span class="sd"> "autoincrement" column, such as AUTO INCREMENT on MySQL,</span>
<span class="sd"> SERIAL on PostgreSQL, and IDENTITY on MS-SQL. It does</span>
<span class="sd"> *not* issue AUTOINCREMENT for SQLite since this is a</span>
<span class="sd"> special SQLite flag that is not required for autoincrementing</span>
<span class="sd"> behavior.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`sqlite_autoincrement`</span>
<span class="sd"> * The column will be considered to be available using an</span>
<span class="sd"> "autoincrement" method specific to the backend database, such</span>
<span class="sd"> as calling upon ``cursor.lastrowid``, using RETURNING in an</span>
<span class="sd"> INSERT statement to get at a sequence-generated value, or using</span>
<span class="sd"> special functions such as "SELECT scope_identity()".</span>
<span class="sd"> These methods are highly specific to the DBAPIs and databases in</span>
<span class="sd"> use and vary greatly, so care should be taken when associating</span>
<span class="sd"> ``autoincrement=True`` with a custom default generation function.</span>
<span class="sd"> :param default: A scalar, Python callable, or</span>
<span class="sd"> :class:`.ColumnElement` expression representing the</span>
<span class="sd"> *default value* for this column, which will be invoked upon insert</span>
<span class="sd"> if this column is otherwise not specified in the VALUES clause of</span>
<span class="sd"> the insert. This is a shortcut to using :class:`.ColumnDefault` as</span>
<span class="sd"> a positional argument; see that class for full detail on the</span>
<span class="sd"> structure of the argument.</span>
<span class="sd"> Contrast this argument to :paramref:`.Column.server_default`</span>
<span class="sd"> which creates a default generator on the database side.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`metadata_defaults_toplevel`</span>
<span class="sd"> :param doc: optional String that can be used by the ORM or similar</span>
<span class="sd"> to document attributes. This attribute does not render SQL</span>
<span class="sd"> comments (a future attribute 'comment' will achieve that).</span>
<span class="sd"> :param key: An optional string identifier which will identify this</span>
<span class="sd"> ``Column`` object on the :class:`.Table`. When a key is provided,</span>
<span class="sd"> this is the only identifier referencing the ``Column`` within the</span>
<span class="sd"> application, including ORM attribute mapping; the ``name`` field</span>
<span class="sd"> is used only when rendering SQL.</span>
<span class="sd"> :param index: When ``True``, indicates that the column is indexed.</span>
<span class="sd"> This is a shortcut for using a :class:`.Index` construct on the</span>
<span class="sd"> table. To specify indexes with explicit names or indexes that</span>
<span class="sd"> contain multiple columns, use the :class:`.Index` construct</span>
<span class="sd"> instead.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> :param nullable: When set to ``False``, will cause the "NOT NULL"</span>
<span class="sd"> phrase to be added when generating DDL for the column. When</span>
<span class="sd"> ``True``, will normally generate nothing (in SQL this defaults to</span>
<span class="sd"> "NULL"), except in some very specific backend-specific edge cases</span>
<span class="sd"> where "NULL" may render explicitly. Defaults to ``True`` unless</span>
<span class="sd"> :paramref:`~.Column.primary_key` is also ``True``, in which case it</span>
<span class="sd"> defaults to ``False``. This parameter is only used when issuing</span>
<span class="sd"> CREATE TABLE statements.</span>
<span class="sd"> :param onupdate: A scalar, Python callable, or</span>
<span class="sd"> :class:`~sqlalchemy.sql.expression.ClauseElement` representing a</span>
<span class="sd"> default value to be applied to the column within UPDATE</span>
<span class="sd"> statements, which wil be invoked upon update if this column is not</span>
<span class="sd"> present in the SET clause of the update. This is a shortcut to</span>
<span class="sd"> using :class:`.ColumnDefault` as a positional argument with</span>
<span class="sd"> ``for_update=True``.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`metadata_defaults` - complete discussion of onupdate</span>
<span class="sd"> :param primary_key: If ``True``, marks this column as a primary key</span>
<span class="sd"> column. Multiple columns can have this flag set to specify</span>
<span class="sd"> composite primary keys. As an alternative, the primary key of a</span>
<span class="sd"> :class:`.Table` can be specified via an explicit</span>
<span class="sd"> :class:`.PrimaryKeyConstraint` object.</span>
<span class="sd"> :param server_default: A :class:`.FetchedValue` instance, str, Unicode</span>
<span class="sd"> or :func:`~sqlalchemy.sql.expression.text` construct representing</span>
<span class="sd"> the DDL DEFAULT value for the column.</span>
<span class="sd"> String types will be emitted as-is, surrounded by single quotes::</span>
<span class="sd"> Column('x', Text, server_default="val")</span>
<span class="sd"> x TEXT DEFAULT 'val'</span>
<span class="sd"> A :func:`~sqlalchemy.sql.expression.text` expression will be</span>
<span class="sd"> rendered as-is, without quotes::</span>
<span class="sd"> Column('y', DateTime, server_default=text('NOW()'))</span>
<span class="sd"> y DATETIME DEFAULT NOW()</span>
<span class="sd"> Strings and text() will be converted into a</span>
<span class="sd"> :class:`.DefaultClause` object upon initialization.</span>
<span class="sd"> Use :class:`.FetchedValue` to indicate that an already-existing</span>
<span class="sd"> column will generate a default value on the database side which</span>
<span class="sd"> will be available to SQLAlchemy for post-fetch after inserts. This</span>
<span class="sd"> construct does not specify any DDL and the implementation is left</span>
<span class="sd"> to the database, such as via a trigger.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`server_defaults` - complete discussion of server side</span>
<span class="sd"> defaults</span>
<span class="sd"> :param server_onupdate: A :class:`.FetchedValue` instance</span>
<span class="sd"> representing a database-side default generation function,</span>
<span class="sd"> such as a trigger. This</span>
<span class="sd"> indicates to SQLAlchemy that a newly generated value will be</span>
<span class="sd"> available after updates. This construct does not actually</span>
<span class="sd"> implement any kind of generation function within the database,</span>
<span class="sd"> which instead must be specified separately.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`triggered_columns`</span>
<span class="sd"> :param quote: Force quoting of this column's name on or off,</span>
<span class="sd"> corresponding to ``True`` or ``False``. When left at its default</span>
<span class="sd"> of ``None``, the column identifier will be quoted according to</span>
<span class="sd"> whether the name is case sensitive (identifiers with at least one</span>
<span class="sd"> upper case character are treated as case sensitive), or if it's a</span>
<span class="sd"> reserved word. This flag is only needed to force quoting of a</span>
<span class="sd"> reserved word which is not known by the SQLAlchemy dialect.</span>
<span class="sd"> :param unique: When ``True``, indicates that this column contains a</span>
<span class="sd"> unique constraint, or if ``index`` is ``True`` as well, indicates</span>
<span class="sd"> that the :class:`.Index` should be created with the unique flag.</span>
<span class="sd"> To specify multiple columns in the constraint/index or to specify</span>
<span class="sd"> an explicit name, use the :class:`.UniqueConstraint` or</span>
<span class="sd"> :class:`.Index` constructs explicitly.</span>
<span class="sd"> :param system: When ``True``, indicates this is a "system" column,</span>
<span class="sd"> that is a column which is automatically made available by the</span>
<span class="sd"> database, and should not be included in the columns list for a</span>
<span class="sd"> ``CREATE TABLE`` statement.</span>
<span class="sd"> For more elaborate scenarios where columns should be</span>
<span class="sd"> conditionally rendered differently on different backends,</span>
<span class="sd"> consider custom compilation rules for :class:`.CreateColumn`.</span>
<span class="sd"> .. versionadded:: 0.8.3 Added the ``system=True`` parameter to</span>
<span class="sd"> :class:`.Column`.</span>
<span class="sd"> """</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'name'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">type_</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'type_'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="k">if</span> <span class="n">args</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="k">if</span> <span class="n">name</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"May not pass name positionally and as a keyword."</span><span class="p">)</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">if</span> <span class="n">args</span><span class="p">:</span>
<span class="n">coltype</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">coltype</span><span class="p">,</span> <span class="s2">"_sqla_type"</span><span class="p">):</span>
<span class="k">if</span> <span class="n">type_</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"May not pass type_ positionally and as a keyword."</span><span class="p">)</span>
<span class="n">type_</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">if</span> <span class="n">name</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'quote'</span><span class="p">,</span> <span class="kc">None</span><span class="p">))</span>
<span class="k">elif</span> <span class="s2">"quote"</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span><span class="s2">"Explicit 'name' is required when "</span>
<span class="s2">"sending 'quote' argument"</span><span class="p">)</span>
<span class="nb">super</span><span class="p">(</span><span class="n">Column</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">type_</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'key'</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'primary_key'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">nullable</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'nullable'</span><span class="p">,</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">default</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'default'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">server_default</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'server_default'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'server_onupdate'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="c1"># these default to None because .index and .unique is *not*</span>
<span class="c1"># an informational flag about Column - there can still be an</span>
<span class="c1"># Index or UniqueConstraint referring to this Column.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'index'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">unique</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'unique'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">system</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'system'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">doc</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'doc'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'onupdate'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">autoincrement</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'autoincrement'</span><span class="p">,</span> <span class="s2">"auto"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraints</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="c1"># check if this Column is proxying another column</span>
<span class="k">if</span> <span class="s1">'_proxies'</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_proxies</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'_proxies'</span><span class="p">)</span>
<span class="c1"># otherwise, add DDL-related events</span>
<span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">type</span><span class="p">,</span> <span class="n">SchemaEventTarget</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">type</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">default</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">,</span> <span class="p">(</span><span class="n">ColumnDefault</span><span class="p">,</span> <span class="n">Sequence</span><span class="p">)):</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">type</span><span class="p">,</span> <span class="s1">'_warn_on_bytestring'</span><span class="p">,</span> <span class="kc">False</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">binary_type</span><span class="p">):</span>
<span class="n">util</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span>
<span class="s2">"Unicode column '</span><span class="si">%s</span><span class="s2">' has non-unicode "</span>
<span class="s2">"default value </span><span class="si">%r</span><span class="s2"> specified."</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">default</span>
<span class="p">))</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">ColumnDefault</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">))</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server_default</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_default</span><span class="p">,</span> <span class="n">FetchedValue</span><span class="p">):</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_default</span><span class="o">.</span><span class="n">_as_for_update</span><span class="p">(</span><span class="kc">False</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">DefaultClause</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_default</span><span class="p">))</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span> <span class="p">(</span><span class="n">ColumnDefault</span><span class="p">,</span> <span class="n">Sequence</span><span class="p">)):</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">ColumnDefault</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span> <span class="n">for_update</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span><span class="p">,</span> <span class="n">FetchedValue</span><span class="p">):</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span><span class="o">.</span><span class="n">_as_for_update</span><span class="p">(</span><span class="kc">True</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">DefaultClause</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span><span class="p">,</span>
<span class="n">for_update</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_init_items</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="n">util</span><span class="o">.</span><span class="n">set_creation_order</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'info'</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'info'</span><span class="p">)</span>
<span class="k">if</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Unknown arguments passed to Column: "</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)))</span>
<span class="c1"># @property</span>
<span class="c1"># def quote(self):</span>
<span class="c1"># return getattr(self.name, "quote", None)</span>
<span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"(no name)"</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">named_with_column</span><span class="p">:</span>
<span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">description</span> <span class="o">+</span> <span class="s2">"."</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">description</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">description</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">description</span>
<span class="k">def</span> <span class="nf">references</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="sd">"""Return True if this Column references the given column via foreign</span>
<span class="sd"> key."""</span>
<span class="k">for</span> <span class="n">fk</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">:</span>
<span class="k">if</span> <span class="n">fk</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">proxy_set</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">column</span><span class="o">.</span><span class="n">proxy_set</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">def</span> <span class="nf">append_foreign_key</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fk</span><span class="p">):</span>
<span class="n">fk</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">kwarg</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'key'</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'primary_key'</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">nullable</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'nullable'</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'onupdate'</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'default'</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server_default</span><span class="p">:</span>
<span class="n">kwarg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'server_default'</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">"Column(</span><span class="si">%s</span><span class="s2">)"</span> <span class="o">%</span> <span class="s1">', '</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)]</span> <span class="o">+</span> <span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">type</span><span class="p">)]</span> <span class="o">+</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span> <span class="k">if</span> <span class="n">x</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">]</span> <span class="o">+</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">constraints</span><span class="p">]</span> <span class="o">+</span>
<span class="p">[(</span><span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="s2">"table=<</span><span class="si">%s</span><span class="s2">>"</span> <span class="o">%</span>
<span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">description</span> <span class="ow">or</span> <span class="s2">"table=None"</span><span class="p">)]</span> <span class="o">+</span>
<span class="p">[</span><span class="s2">"</span><span class="si">%s</span><span class="s2">=</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">)))</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">kwarg</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Column must be constructed with a non-blank name or "</span>
<span class="s2">"assign a non-blank .name before adding to a Table."</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
<span class="n">existing</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s1">'table'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">existing</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">existing</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">table</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Column object '</span><span class="si">%s</span><span class="s2">' already assigned to Table '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="n">existing</span><span class="o">.</span><span class="n">description</span>
<span class="p">))</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">_columns</span><span class="p">:</span>
<span class="n">col</span> <span class="o">=</span> <span class="n">table</span><span class="o">.</span><span class="n">_columns</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">)</span>
<span class="k">if</span> <span class="n">col</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">self</span><span class="p">:</span>
<span class="k">for</span> <span class="n">fk</span> <span class="ow">in</span> <span class="n">col</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">:</span>
<span class="n">table</span><span class="o">.</span><span class="n">foreign_keys</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">fk</span><span class="p">)</span>
<span class="k">if</span> <span class="n">fk</span><span class="o">.</span><span class="n">constraint</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">constraints</span><span class="p">:</span>
<span class="c1"># this might have been removed</span>
<span class="c1"># already, if it's a composite constraint</span>
<span class="c1"># and more than one col being replaced</span>
<span class="n">table</span><span class="o">.</span><span class="n">constraints</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">fk</span><span class="o">.</span><span class="n">constraint</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">_columns</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">:</span>
<span class="n">table</span><span class="o">.</span><span class="n">primary_key</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">primary_key</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Trying to redefine primary-key column '</span><span class="si">%s</span><span class="s2">' as a "</span>
<span class="s2">"non-primary-key column on table '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">,</span> <span class="n">table</span><span class="o">.</span><span class="n">fullname</span><span class="p">))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="o">=</span> <span class="n">table</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"The 'index' keyword argument on Column is boolean only. "</span>
<span class="s2">"To create indexes with a specific name, create an "</span>
<span class="s2">"explicit Index object external to the Table."</span><span class="p">)</span>
<span class="n">Index</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="bp">self</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="nb">bool</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">unique</span><span class="p">))</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">unique</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">unique</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"The 'unique' keyword argument on Column is boolean "</span>
<span class="s2">"only. To create unique constraints or indexes with a "</span>
<span class="s2">"specific name, append an explicit UniqueConstraint to "</span>
<span class="s2">"the Table's list of elements, or create an explicit "</span>
<span class="s2">"Index object external to the Table."</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">append_constraint</span><span class="p">(</span><span class="n">UniqueConstraint</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_setup_on_memoized_fks</span><span class="p">(</span><span class="k">lambda</span> <span class="n">fk</span><span class="p">:</span> <span class="n">fk</span><span class="o">.</span><span class="n">_set_remote_table</span><span class="p">(</span><span class="n">table</span><span class="p">))</span>
<span class="k">def</span> <span class="nf">_setup_on_memoized_fks</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fn</span><span class="p">):</span>
<span class="n">fk_keys</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">key</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">),</span> <span class="kc">False</span><span class="p">),</span>
<span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">key</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">),</span> <span class="kc">True</span><span class="p">),</span>
<span class="p">]</span>
<span class="k">for</span> <span class="n">fk_key</span><span class="p">,</span> <span class="n">link_to_name</span> <span class="ow">in</span> <span class="n">fk_keys</span><span class="p">:</span>
<span class="k">if</span> <span class="n">fk_key</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">:</span>
<span class="k">for</span> <span class="n">fk</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">[</span><span class="n">fk_key</span><span class="p">]:</span>
<span class="k">if</span> <span class="n">fk</span><span class="o">.</span><span class="n">link_to_name</span> <span class="ow">is</span> <span class="n">link_to_name</span><span class="p">:</span>
<span class="n">fn</span><span class="p">(</span><span class="n">fk</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_on_table_attach</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fn</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">fn</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">event</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s1">'after_parent_attach'</span><span class="p">,</span> <span class="n">fn</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="sd">"""Create a copy of this ``Column``, unitialized.</span>
<span class="sd"> This is used in ``Table.tometadata``.</span>
<span class="sd"> """</span>
<span class="c1"># Constraint objects plus non-constraint-bound ForeignKey objects</span>
<span class="n">args</span> <span class="o">=</span> \
<span class="p">[</span><span class="n">c</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">constraints</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">c</span><span class="o">.</span><span class="n">_type_bound</span><span class="p">]</span> <span class="o">+</span> \
<span class="p">[</span><span class="n">c</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">c</span><span class="o">.</span><span class="n">constraint</span><span class="p">]</span>
<span class="n">type_</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">type</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">type_</span><span class="p">,</span> <span class="n">SchemaEventTarget</span><span class="p">):</span>
<span class="n">type_</span> <span class="o">=</span> <span class="n">type_</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="n">c</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_constructor</span><span class="p">(</span>
<span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">type_</span><span class="o">=</span><span class="n">type_</span><span class="p">,</span>
<span class="n">key</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="n">primary_key</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">,</span>
<span class="n">nullable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">nullable</span><span class="p">,</span>
<span class="n">unique</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">unique</span><span class="p">,</span>
<span class="n">system</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">system</span><span class="p">,</span>
<span class="c1"># quote=self.quote,</span>
<span class="n">index</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">,</span>
<span class="n">autoincrement</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">autoincrement</span><span class="p">,</span>
<span class="n">default</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">,</span>
<span class="n">server_default</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">server_default</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span>
<span class="n">server_onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">server_onupdate</span><span class="p">,</span>
<span class="n">doc</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">doc</span><span class="p">,</span>
<span class="o">*</span><span class="n">args</span>
<span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_make_proxy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">selectable</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">name_is_truncatable</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="sd">"""Create a *proxy* for this column.</span>
<span class="sd"> This is a copy of this ``Column`` referenced by a different parent</span>
<span class="sd"> (such as an alias or select statement). The column should</span>
<span class="sd"> be used only in select scenarios, as its full DDL/default</span>
<span class="sd"> information is not transferred.</span>
<span class="sd"> """</span>
<span class="n">fk</span> <span class="o">=</span> <span class="p">[</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">column</span><span class="p">,</span> <span class="n">_constraint</span><span class="o">=</span><span class="n">f</span><span class="o">.</span><span class="n">constraint</span><span class="p">)</span>
<span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">]</span>
<span class="k">if</span> <span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"Cannot initialize a sub-selectable"</span>
<span class="s2">" with this Column object until its 'name' has "</span>
<span class="s2">"been assigned."</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">c</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_constructor</span><span class="p">(</span>
<span class="n">_as_truncated</span><span class="p">(</span><span class="n">name</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">if</span>
<span class="n">name_is_truncatable</span> <span class="k">else</span> <span class="p">(</span><span class="n">name</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">),</span>
<span class="bp">self</span><span class="o">.</span><span class="n">type</span><span class="p">,</span>
<span class="n">key</span><span class="o">=</span><span class="n">key</span> <span class="k">if</span> <span class="n">key</span> <span class="k">else</span> <span class="n">name</span> <span class="k">if</span> <span class="n">name</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="n">primary_key</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">,</span>
<span class="n">nullable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">nullable</span><span class="p">,</span>
<span class="n">_proxies</span><span class="o">=</span><span class="p">[</span><span class="bp">self</span><span class="p">],</span> <span class="o">*</span><span class="n">fk</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
<span class="n">util</span><span class="o">.</span><span class="n">raise_from_cause</span><span class="p">(</span>
<span class="ne">TypeError</span><span class="p">(</span>
<span class="s2">"Could not create a copy of this </span><span class="si">%r</span><span class="s2"> object. "</span>
<span class="s2">"Ensure the class includes a _constructor() "</span>
<span class="s2">"attribute or method which accepts the "</span>
<span class="s2">"standard Column constructor arguments, or "</span>
<span class="s2">"references the Column class itself."</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">)</span>
<span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">table</span> <span class="o">=</span> <span class="n">selectable</span>
<span class="n">selectable</span><span class="o">.</span><span class="n">_columns</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">if</span> <span class="n">selectable</span><span class="o">.</span><span class="n">_is_clone_of</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">c</span><span class="o">.</span><span class="n">_is_clone_of</span> <span class="o">=</span> <span class="n">selectable</span><span class="o">.</span><span class="n">_is_clone_of</span><span class="o">.</span><span class="n">columns</span><span class="p">[</span><span class="n">c</span><span class="o">.</span><span class="n">key</span><span class="p">]</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">primary_key</span><span class="p">:</span>
<span class="n">selectable</span><span class="o">.</span><span class="n">primary_key</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">dispatch</span><span class="o">.</span><span class="n">after_parent_attach</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">selectable</span><span class="p">)</span>
<span class="k">return</span> <span class="n">c</span>
<span class="k">def</span> <span class="nf">get_children</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">schema_visitor</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="k">if</span> <span class="n">schema_visitor</span><span class="p">:</span>
<span class="k">return</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">default</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">)</span>
<span class="k">if</span> <span class="n">x</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">]</span> <span class="o">+</span> \
<span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">)</span> <span class="o">+</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">constraints</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">ColumnClause</span><span class="o">.</span><span class="n">get_children</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ForeignKey</span><span class="p">(</span><span class="n">DialectKWArgs</span><span class="p">,</span> <span class="n">SchemaItem</span><span class="p">):</span>
<span class="sd">"""Defines a dependency between two columns.</span>
<span class="sd"> ``ForeignKey`` is specified as an argument to a :class:`.Column` object,</span>
<span class="sd"> e.g.::</span>
<span class="sd"> t = Table("remote_table", metadata,</span>
<span class="sd"> Column("remote_id", ForeignKey("main_table.id"))</span>
<span class="sd"> )</span>
<span class="sd"> Note that ``ForeignKey`` is only a marker object that defines</span>
<span class="sd"> a dependency between two columns. The actual constraint</span>
<span class="sd"> is in all cases represented by the :class:`.ForeignKeyConstraint`</span>
<span class="sd"> object. This object will be generated automatically when</span>
<span class="sd"> a ``ForeignKey`` is associated with a :class:`.Column` which</span>
<span class="sd"> in turn is associated with a :class:`.Table`. Conversely,</span>
<span class="sd"> when :class:`.ForeignKeyConstraint` is applied to a :class:`.Table`,</span>
<span class="sd"> ``ForeignKey`` markers are automatically generated to be</span>
<span class="sd"> present on each associated :class:`.Column`, which are also</span>
<span class="sd"> associated with the constraint object.</span>
<span class="sd"> Note that you cannot define a "composite" foreign key constraint,</span>
<span class="sd"> that is a constraint between a grouping of multiple parent/child</span>
<span class="sd"> columns, using ``ForeignKey`` objects. To define this grouping,</span>
<span class="sd"> the :class:`.ForeignKeyConstraint` object must be used, and applied</span>
<span class="sd"> to the :class:`.Table`. The associated ``ForeignKey`` objects</span>
<span class="sd"> are created automatically.</span>
<span class="sd"> The ``ForeignKey`` objects associated with an individual</span>
<span class="sd"> :class:`.Column` object are available in the `foreign_keys` collection</span>
<span class="sd"> of that column.</span>
<span class="sd"> Further examples of foreign key configuration are in</span>
<span class="sd"> :ref:`metadata_foreignkeys`.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'foreign_key'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">_constraint</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">use_alter</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">ondelete</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">link_to_name</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">match</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">info</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="o">**</span><span class="n">dialect_kw</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""</span>
<span class="sd"> Construct a column-level FOREIGN KEY.</span>
<span class="sd"> The :class:`.ForeignKey` object when constructed generates a</span>
<span class="sd"> :class:`.ForeignKeyConstraint` which is associated with the parent</span>
<span class="sd"> :class:`.Table` object's collection of constraints.</span>
<span class="sd"> :param column: A single target column for the key relationship. A</span>
<span class="sd"> :class:`.Column` object or a column name as a string:</span>
<span class="sd"> ``tablename.columnkey`` or ``schema.tablename.columnkey``.</span>
<span class="sd"> ``columnkey`` is the ``key`` which has been assigned to the column</span>
<span class="sd"> (defaults to the column name itself), unless ``link_to_name`` is</span>
<span class="sd"> ``True`` in which case the rendered name of the column is used.</span>
<span class="sd"> .. versionadded:: 0.7.4</span>
<span class="sd"> Note that if the schema name is not included, and the</span>
<span class="sd"> underlying :class:`.MetaData` has a "schema", that value will</span>
<span class="sd"> be used.</span>
<span class="sd"> :param name: Optional string. An in-database name for the key if</span>
<span class="sd"> `constraint` is not provided.</span>
<span class="sd"> :param onupdate: Optional string. If set, emit ON UPDATE <value> when</span>
<span class="sd"> issuing DDL for this constraint. Typical values include CASCADE,</span>
<span class="sd"> DELETE and RESTRICT.</span>
<span class="sd"> :param ondelete: Optional string. If set, emit ON DELETE <value> when</span>
<span class="sd"> issuing DDL for this constraint. Typical values include CASCADE,</span>
<span class="sd"> DELETE and RESTRICT.</span>
<span class="sd"> :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT</span>
<span class="sd"> DEFERRABLE when issuing DDL for this constraint.</span>
<span class="sd"> :param initially: Optional string. If set, emit INITIALLY <value> when</span>
<span class="sd"> issuing DDL for this constraint.</span>
<span class="sd"> :param link_to_name: if True, the string name given in ``column`` is</span>
<span class="sd"> the rendered name of the referenced column, not its locally</span>
<span class="sd"> assigned ``key``.</span>
<span class="sd"> :param use_alter: passed to the underlying</span>
<span class="sd"> :class:`.ForeignKeyConstraint` to indicate the constraint should</span>
<span class="sd"> be generated/dropped externally from the CREATE TABLE/ DROP TABLE</span>
<span class="sd"> statement. See :paramref:`.ForeignKeyConstraint.use_alter`</span>
<span class="sd"> for further description.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.ForeignKeyConstraint.use_alter`</span>
<span class="sd"> :ref:`use_alter`</span>
<span class="sd"> :param match: Optional string. If set, emit MATCH <value> when issuing</span>
<span class="sd"> DDL for this constraint. Typical values include SIMPLE, PARTIAL</span>
<span class="sd"> and FULL.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> :param \**dialect_kw: Additional keyword arguments are dialect</span>
<span class="sd"> specific, and passed in the form ``<dialectname>_<argname>``. The</span>
<span class="sd"> arguments are ultimately handled by a corresponding</span>
<span class="sd"> :class:`.ForeignKeyConstraint`. See the documentation regarding</span>
<span class="sd"> an individual dialect at :ref:`dialect_toplevel` for detail on</span>
<span class="sd"> documented arguments.</span>
<span class="sd"> .. versionadded:: 0.9.2</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span> <span class="o">=</span> <span class="n">column</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="p">,</span> <span class="n">ColumnClause</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"String, Column, or Column-bound argument "</span>
<span class="s2">"expected, got </span><span class="si">%r</span><span class="s2">"</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="p">)</span>
<span class="k">elif</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">table</span><span class="p">,</span> <span class="p">(</span><span class="n">util</span><span class="o">.</span><span class="n">NoneType</span><span class="p">,</span> <span class="n">TableClause</span><span class="p">)):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"ForeignKey received Column not bound "</span>
<span class="s2">"to a Table, got: </span><span class="si">%r</span><span class="s2">"</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">table</span>
<span class="p">)</span>
<span class="c1"># the linked ForeignKeyConstraint.</span>
<span class="c1"># ForeignKey will create this when parent Column</span>
<span class="c1"># is attached to a Table, *or* ForeignKeyConstraint</span>
<span class="c1"># object passes itself in when creating ForeignKey</span>
<span class="c1"># markers.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span> <span class="o">=</span> <span class="n">_constraint</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="o">=</span> <span class="kc">None</span>
<span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span> <span class="o">=</span> <span class="n">use_alter</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span> <span class="o">=</span> <span class="n">onupdate</span>
<span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span> <span class="o">=</span> <span class="n">ondelete</span>
<span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span> <span class="o">=</span> <span class="n">deferrable</span>
<span class="bp">self</span><span class="o">.</span><span class="n">initially</span> <span class="o">=</span> <span class="n">initially</span>
<span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span> <span class="o">=</span> <span class="n">link_to_name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">match</span> <span class="o">=</span> <span class="n">match</span>
<span class="k">if</span> <span class="n">info</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">info</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_unvalidated_dialect_kw</span> <span class="o">=</span> <span class="n">dialect_kw</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"ForeignKey(</span><span class="si">%r</span><span class="s2">)"</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_colspec</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Produce a copy of this :class:`.ForeignKey` object.</span>
<span class="sd"> The new :class:`.ForeignKey` will not be bound</span>
<span class="sd"> to any :class:`.Column`.</span>
<span class="sd"> This method is usually used by the internal</span>
<span class="sd"> copy procedures of :class:`.Column`, :class:`.Table`,</span>
<span class="sd"> and :class:`.MetaData`.</span>
<span class="sd"> :param schema: The returned :class:`.ForeignKey` will</span>
<span class="sd"> reference the original table and column name, qualified</span>
<span class="sd"> by the given string schema name.</span>
<span class="sd"> """</span>
<span class="n">fk</span> <span class="o">=</span> <span class="n">ForeignKey</span><span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_get_colspec</span><span class="p">(</span><span class="n">schema</span><span class="o">=</span><span class="n">schema</span><span class="p">),</span>
<span class="n">use_alter</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span><span class="p">,</span>
<span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span>
<span class="n">ondelete</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span><span class="p">,</span>
<span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span>
<span class="n">link_to_name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span><span class="p">,</span>
<span class="n">match</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">match</span><span class="p">,</span>
<span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">_unvalidated_dialect_kw</span>
<span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">fk</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_get_colspec</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">table_name</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Return a string based 'column specification' for this</span>
<span class="sd"> :class:`.ForeignKey`.</span>
<span class="sd"> This is usually the equivalent of the string-based "tablename.colname"</span>
<span class="sd"> argument first passed to the object's constructor.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">schema</span><span class="p">:</span>
<span class="n">_schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_column_tokens</span>
<span class="k">if</span> <span class="n">table_name</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">tname</span> <span class="o">=</span> <span class="n">table_name</span>
<span class="k">return</span> <span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">table_name</span><span class="p">:</span>
<span class="n">schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_column_tokens</span>
<span class="k">if</span> <span class="n">schema</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">table_name</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">table_name</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">fullname</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">key</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_referred_schema</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_column_tokens</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">_table_key</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_table_column</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">key</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_column_tokens</span>
<span class="k">return</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">tname</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="n">target_fullname</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_colspec</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">references</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="sd">"""Return True if the given :class:`.Table` is referenced by this</span>
<span class="sd"> :class:`.ForeignKey`."""</span>
<span class="k">return</span> <span class="n">table</span><span class="o">.</span><span class="n">corresponding_column</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="p">)</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">get_referent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="sd">"""Return the :class:`.Column` in the given :class:`.Table`</span>
<span class="sd"> referenced by this :class:`.ForeignKey`.</span>
<span class="sd"> Returns None if this :class:`.ForeignKey` does not reference the given</span>
<span class="sd"> :class:`.Table`.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">table</span><span class="o">.</span><span class="n">corresponding_column</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">_column_tokens</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""parse a string-based _colspec into its component parts."""</span>
<span class="n">m</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_colspec</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">'.'</span><span class="p">)</span>
<span class="k">if</span> <span class="n">m</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Invalid foreign key column specification: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">)</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">):</span>
<span class="n">tname</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="n">colname</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">colname</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="n">tname</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="c1"># A FK between column 'bar' and table 'foo' can be</span>
<span class="c1"># specified as 'foo', 'foo.bar', 'dbo.foo.bar',</span>
<span class="c1"># 'otherdb.dbo.foo.bar'. Once we have the column name and</span>
<span class="c1"># the table name, treat everything else as the schema</span>
<span class="c1"># name. Some databases (e.g. Sybase) support</span>
<span class="c1"># inter-database foreign keys. See tickets#1341 and --</span>
<span class="c1"># indirectly related -- Ticket #594. This assumes that '.'</span>
<span class="c1"># will never appear *within* any component of the FK.</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span> <span class="o">></span> <span class="mi">0</span><span class="p">):</span>
<span class="n">schema</span> <span class="o">=</span> <span class="s1">'.'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">return</span> <span class="n">schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span>
<span class="k">def</span> <span class="nf">_resolve_col_tokens</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"this ForeignKey object does not yet have a "</span>
<span class="s2">"parent Column associated with it."</span><span class="p">)</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"this ForeignKey's parent column is not yet associated "</span>
<span class="s2">"with a Table."</span><span class="p">)</span>
<span class="n">parenttable</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">table</span>
<span class="c1"># assertion, can be commented out.</span>
<span class="c1"># basically Column._make_proxy() sends the actual</span>
<span class="c1"># target Column to the ForeignKey object, so the</span>
<span class="c1"># string resolution here is never called.</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">base_columns</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">Column</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">c</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="n">parenttable</span>
<span class="k">break</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">assert</span> <span class="kc">False</span>
<span class="c1">######################</span>
<span class="n">schema</span><span class="p">,</span> <span class="n">tname</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_column_tokens</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">schema</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">schema</span>
<span class="n">tablekey</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">tname</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="k">return</span> <span class="n">parenttable</span><span class="p">,</span> <span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span>
<span class="k">def</span> <span class="nf">_link_to_col_by_colstring</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parenttable</span><span class="p">,</span> <span class="n">table</span><span class="p">,</span> <span class="n">colname</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="p">,</span> <span class="s1">'_referred_table'</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="o">.</span><span class="n">_referred_table</span> <span class="o">=</span> <span class="n">table</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="o">.</span><span class="n">_referred_table</span> <span class="ow">is</span> <span class="n">table</span>
<span class="n">_column</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">if</span> <span class="n">colname</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="c1"># colname is None in the case that ForeignKey argument</span>
<span class="c1"># was specified as table name only, in which case we</span>
<span class="c1"># match the column name to the same column on the</span>
<span class="c1"># parent.</span>
<span class="n">key</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span>
<span class="n">_column</span> <span class="o">=</span> <span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">key</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span><span class="p">:</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">colname</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="p">:</span>
<span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">colname</span><span class="p">:</span>
<span class="n">_column</span> <span class="o">=</span> <span class="n">c</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">colname</span>
<span class="n">_column</span> <span class="o">=</span> <span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">colname</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">_column</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">NoReferencedColumnError</span><span class="p">(</span>
<span class="s2">"Could not initialize target column "</span>
<span class="s2">"for ForeignKey '</span><span class="si">%s</span><span class="s2">' on table '</span><span class="si">%s</span><span class="s2">': "</span>
<span class="s2">"table '</span><span class="si">%s</span><span class="s2">' has no column named '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span>
<span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">table</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">key</span><span class="p">),</span>
<span class="n">table</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_target_column</span><span class="p">(</span><span class="n">_column</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_target_column</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="c1"># propagate TypeEngine to parent if it didn't have one</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">type</span><span class="o">.</span><span class="n">_isnull</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="n">column</span><span class="o">.</span><span class="n">type</span>
<span class="c1"># super-edgy case, if other FKs point to our column,</span>
<span class="c1"># they'd get the type propagated out also.</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">table</span><span class="p">,</span> <span class="n">Table</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">set_type</span><span class="p">(</span><span class="n">fk</span><span class="p">):</span>
<span class="k">if</span> <span class="n">fk</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">type</span><span class="o">.</span><span class="n">_isnull</span><span class="p">:</span>
<span class="n">fk</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="n">column</span><span class="o">.</span><span class="n">type</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">_setup_on_memoized_fks</span><span class="p">(</span><span class="n">set_type</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span> <span class="o">=</span> <span class="n">column</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">column</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the target :class:`.Column` referenced by this</span>
<span class="sd"> :class:`.ForeignKey`.</span>
<span class="sd"> If no target column has been established, an exception</span>
<span class="sd"> is raised.</span>
<span class="sd"> .. versionchanged:: 0.9.0</span>
<span class="sd"> Foreign key target column resolution now occurs as soon as both</span>
<span class="sd"> the ForeignKey object and the remote Column to which it refers</span>
<span class="sd"> are both associated with the same MetaData object.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="n">parenttable</span><span class="p">,</span> <span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_resolve_col_tokens</span><span class="p">()</span>
<span class="k">if</span> <span class="n">tablekey</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">NoReferencedTableError</span><span class="p">(</span>
<span class="s2">"Foreign key associated with column '</span><span class="si">%s</span><span class="s2">' could not find "</span>
<span class="s2">"table '</span><span class="si">%s</span><span class="s2">' with which to generate a "</span>
<span class="s2">"foreign key to target column '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span>
<span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="p">,</span> <span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span><span class="p">),</span>
<span class="n">tablekey</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">key</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"Table </span><span class="si">%s</span><span class="s2"> is no longer associated with its "</span>
<span class="s2">"parent MetaData"</span> <span class="o">%</span> <span class="n">parenttable</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">NoReferencedColumnError</span><span class="p">(</span>
<span class="s2">"Could not initialize target column for "</span>
<span class="s2">"ForeignKey '</span><span class="si">%s</span><span class="s2">' on table '</span><span class="si">%s</span><span class="s2">': "</span>
<span class="s2">"table '</span><span class="si">%s</span><span class="s2">' has no column named '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span><span class="p">),</span>
<span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">elif</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="n">_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="k">return</span> <span class="n">_column</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span>
<span class="k">return</span> <span class="n">_column</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">column</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"This ForeignKey already has a parent !"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="o">=</span> <span class="n">column</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">foreign_keys</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">_on_table_attach</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_set_table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_remote_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">parenttable</span><span class="p">,</span> <span class="n">tablekey</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_resolve_col_tokens</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_link_to_col_by_colstring</span><span class="p">(</span><span class="n">parenttable</span><span class="p">,</span> <span class="n">table</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="o">.</span><span class="n">_validate_dest_table</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_remove_from_metadata</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">metadata</span><span class="p">):</span>
<span class="n">parenttable</span><span class="p">,</span> <span class="n">table_key</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_resolve_col_tokens</span><span class="p">()</span>
<span class="n">fk_key</span> <span class="o">=</span> <span class="p">(</span><span class="n">table_key</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span> <span class="ow">in</span> <span class="n">metadata</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">[</span><span class="n">fk_key</span><span class="p">]:</span>
<span class="c1"># TODO: no test coverage for self not in memos</span>
<span class="n">metadata</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">[</span><span class="n">fk_key</span><span class="p">]</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="c1"># standalone ForeignKey - create ForeignKeyConstraint</span>
<span class="c1"># on the hosting Table when attached to the Table.</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">constraint</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">table</span><span class="p">,</span> <span class="n">Table</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span> <span class="o">=</span> <span class="n">ForeignKeyConstraint</span><span class="p">(</span>
<span class="p">[],</span> <span class="p">[],</span> <span class="n">use_alter</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span> <span class="n">ondelete</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span><span class="p">,</span>
<span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span> <span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span>
<span class="n">match</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">match</span><span class="p">,</span>
<span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">_unvalidated_dialect_kw</span>
<span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="o">.</span><span class="n">_append_element</span><span class="p">(</span><span class="n">column</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constraint</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">foreign_keys</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="c1"># set up remote ".column" attribute, or a note to pick it</span>
<span class="c1"># up when the other Table/Column shows up</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="n">parenttable</span><span class="p">,</span> <span class="n">table_key</span><span class="p">,</span> <span class="n">colname</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_resolve_col_tokens</span><span class="p">()</span>
<span class="n">fk_key</span> <span class="o">=</span> <span class="p">(</span><span class="n">table_key</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">if</span> <span class="n">table_key</span> <span class="ow">in</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">:</span>
<span class="n">table</span> <span class="o">=</span> <span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">tables</span><span class="p">[</span><span class="n">table_key</span><span class="p">]</span>
<span class="k">try</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_link_to_col_by_colstring</span><span class="p">(</span>
<span class="n">parenttable</span><span class="p">,</span> <span class="n">table</span><span class="p">,</span> <span class="n">colname</span><span class="p">)</span>
<span class="k">except</span> <span class="n">exc</span><span class="o">.</span><span class="n">NoReferencedColumnError</span><span class="p">:</span>
<span class="c1"># this is OK, we'll try later</span>
<span class="k">pass</span>
<span class="n">parenttable</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">[</span><span class="n">fk_key</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">elif</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="n">_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_target_column</span><span class="p">(</span><span class="n">_column</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">_column</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_colspec</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_target_column</span><span class="p">(</span><span class="n">_column</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">_NotAColumnExpr</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">_not_a_column_expr</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"This </span><span class="si">%s</span><span class="s2"> cannot be used directly "</span>
<span class="s2">"as a column expression."</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="n">__clause_element__</span> <span class="o">=</span> <span class="n">self_group</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_not_a_column_expr</span><span class="p">()</span>
<span class="n">_from_objects</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="k">lambda</span> <span class="bp">self</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_not_a_column_expr</span><span class="p">())</span>
<span class="k">class</span> <span class="nc">DefaultGenerator</span><span class="p">(</span><span class="n">_NotAColumnExpr</span><span class="p">,</span> <span class="n">SchemaItem</span><span class="p">):</span>
<span class="sd">"""Base class for column *default* values."""</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'default_generator'</span>
<span class="n">is_sequence</span> <span class="o">=</span> <span class="kc">False</span>
<span class="n">is_server_default</span> <span class="o">=</span> <span class="kc">False</span>
<span class="n">column</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">for_update</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">for_update</span> <span class="o">=</span> <span class="n">for_update</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span> <span class="o">=</span> <span class="n">column</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">for_update</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">onupdate</span> <span class="o">=</span> <span class="bp">self</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">default</span> <span class="o">=</span> <span class="bp">self</span>
<span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">return</span> <span class="n">bind</span><span class="o">.</span><span class="n">_execute_default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_execute_on_connection</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">multiparams</span><span class="p">,</span> <span class="n">params</span><span class="p">):</span>
<span class="k">return</span> <span class="n">connection</span><span class="o">.</span><span class="n">_execute_default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">multiparams</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the connectable associated with this default."""</span>
<span class="k">if</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s1">'column'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">bind</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="k">class</span> <span class="nc">ColumnDefault</span><span class="p">(</span><span class="n">DefaultGenerator</span><span class="p">):</span>
<span class="sd">"""A plain default value on a column.</span>
<span class="sd"> This could correspond to a constant, a callable function,</span>
<span class="sd"> or a SQL clause.</span>
<span class="sd"> :class:`.ColumnDefault` is generated automatically</span>
<span class="sd"> whenever the ``default``, ``onupdate`` arguments of</span>
<span class="sd"> :class:`.Column` are used. A :class:`.ColumnDefault`</span>
<span class="sd"> can be passed positionally as well.</span>
<span class="sd"> For example, the following::</span>
<span class="sd"> Column('foo', Integer, default=50)</span>
<span class="sd"> Is equivalent to::</span>
<span class="sd"> Column('foo', Integer, ColumnDefault(50))</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="sd">""""Construct a new :class:`.ColumnDefault`.</span>
<span class="sd"> :param arg: argument representing the default value.</span>
<span class="sd"> May be one of the following:</span>
<span class="sd"> * a plain non-callable Python value, such as a</span>
<span class="sd"> string, integer, boolean, or other simple type.</span>
<span class="sd"> The default value will be used as is each time.</span>
<span class="sd"> * a SQL expression, that is one which derives from</span>
<span class="sd"> :class:`.ColumnElement`. The SQL expression will</span>
<span class="sd"> be rendered into the INSERT or UPDATE statement,</span>
<span class="sd"> or in the case of a primary key column when</span>
<span class="sd"> RETURNING is not used may be</span>
<span class="sd"> pre-executed before an INSERT within a SELECT.</span>
<span class="sd"> * A Python callable. The function will be invoked for each</span>
<span class="sd"> new row subject to an INSERT or UPDATE.</span>
<span class="sd"> The callable must accept exactly</span>
<span class="sd"> zero or one positional arguments. The one-argument form</span>
<span class="sd"> will receive an instance of the :class:`.ExecutionContext`,</span>
<span class="sd"> which provides contextual information as to the current</span>
<span class="sd"> :class:`.Connection` in use as well as the current</span>
<span class="sd"> statement and parameters.</span>
<span class="sd"> """</span>
<span class="nb">super</span><span class="p">(</span><span class="n">ColumnDefault</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="n">FetchedValue</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"ColumnDefault may not be a server-side default type."</span><span class="p">)</span>
<span class="k">if</span> <span class="n">util</span><span class="o">.</span><span class="n">callable</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span>
<span class="n">arg</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_maybe_wrap_callable</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">arg</span> <span class="o">=</span> <span class="n">arg</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">is_callable</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">callable</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">is_clause_element</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">arg</span><span class="p">,</span> <span class="n">ClauseElement</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">is_scalar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_callable</span> <span class="ow">and</span> \
<span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_clause_element</span> <span class="ow">and</span> \
<span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_sequence</span>
<span class="k">def</span> <span class="nf">_maybe_wrap_callable</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fn</span><span class="p">):</span>
<span class="sd">"""Wrap callables that don't accept a context.</span>
<span class="sd"> This is to allow easy compatibility with default callables</span>
<span class="sd"> that aren't specific to accepting of a context.</span>
<span class="sd"> """</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">argspec</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">get_callable_argspec</span><span class="p">(</span><span class="n">fn</span><span class="p">,</span> <span class="n">no_self</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">wrap_callable</span><span class="p">(</span><span class="k">lambda</span> <span class="n">ctx</span><span class="p">:</span> <span class="n">fn</span><span class="p">(),</span> <span class="n">fn</span><span class="p">)</span>
<span class="n">defaulted</span> <span class="o">=</span> <span class="n">argspec</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">argspec</span><span class="p">[</span><span class="mi">3</span><span class="p">])</span> <span class="ow">or</span> <span class="mi">0</span>
<span class="n">positionals</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">argspec</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">-</span> <span class="n">defaulted</span>
<span class="k">if</span> <span class="n">positionals</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">wrap_callable</span><span class="p">(</span><span class="k">lambda</span> <span class="n">ctx</span><span class="p">:</span> <span class="n">fn</span><span class="p">(),</span> <span class="n">fn</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">positionals</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="k">return</span> <span class="n">fn</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"ColumnDefault Python function takes zero or one "</span>
<span class="s2">"positional arguments"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_visit_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">for_update</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"column_onupdate"</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"column_default"</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_visit_name</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"ColumnDefault(</span><span class="si">%r</span><span class="s2">)"</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">arg</span>
<span class="k">class</span> <span class="nc">Sequence</span><span class="p">(</span><span class="n">DefaultGenerator</span><span class="p">):</span>
<span class="sd">"""Represents a named database sequence.</span>
<span class="sd"> The :class:`.Sequence` object represents the name and configurational</span>
<span class="sd"> parameters of a database sequence. It also represents</span>
<span class="sd"> a construct that can be "executed" by a SQLAlchemy :class:`.Engine`</span>
<span class="sd"> or :class:`.Connection`, rendering the appropriate "next value" function</span>
<span class="sd"> for the target database and returning a result.</span>
<span class="sd"> The :class:`.Sequence` is typically associated with a primary key column::</span>
<span class="sd"> some_table = Table(</span>
<span class="sd"> 'some_table', metadata,</span>
<span class="sd"> Column('id', Integer, Sequence('some_table_seq'),</span>
<span class="sd"> primary_key=True)</span>
<span class="sd"> )</span>
<span class="sd"> When CREATE TABLE is emitted for the above :class:`.Table`, if the</span>
<span class="sd"> target platform supports sequences, a CREATE SEQUENCE statement will</span>
<span class="sd"> be emitted as well. For platforms that don't support sequences,</span>
<span class="sd"> the :class:`.Sequence` construct is ignored.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :class:`.CreateSequence`</span>
<span class="sd"> :class:`.DropSequence`</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'sequence'</span>
<span class="n">is_sequence</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">increment</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">minvalue</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">maxvalue</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">nominvalue</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">nomaxvalue</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">cycle</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">optional</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">quote</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">metadata</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">quote_schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">for_update</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="sd">"""Construct a :class:`.Sequence` object.</span>
<span class="sd"> :param name: The name of the sequence.</span>
<span class="sd"> :param start: the starting index of the sequence. This value is</span>
<span class="sd"> used when the CREATE SEQUENCE command is emitted to the database</span>
<span class="sd"> as the value of the "START WITH" clause. If ``None``, the</span>
<span class="sd"> clause is omitted, which on most platforms indicates a starting</span>
<span class="sd"> value of 1.</span>
<span class="sd"> :param increment: the increment value of the sequence. This</span>
<span class="sd"> value is used when the CREATE SEQUENCE command is emitted to</span>
<span class="sd"> the database as the value of the "INCREMENT BY" clause. If ``None``,</span>
<span class="sd"> the clause is omitted, which on most platforms indicates an</span>
<span class="sd"> increment of 1.</span>
<span class="sd"> :param minvalue: the minimum value of the sequence. This</span>
<span class="sd"> value is used when the CREATE SEQUENCE command is emitted to</span>
<span class="sd"> the database as the value of the "MINVALUE" clause. If ``None``,</span>
<span class="sd"> the clause is omitted, which on most platforms indicates a</span>
<span class="sd"> minvalue of 1 and -2^63-1 for ascending and descending sequences,</span>
<span class="sd"> respectively.</span>
<span class="sd"> .. versionadded:: 1.0.7</span>
<span class="sd"> :param maxvalue: the maximum value of the sequence. This</span>
<span class="sd"> value is used when the CREATE SEQUENCE command is emitted to</span>
<span class="sd"> the database as the value of the "MAXVALUE" clause. If ``None``,</span>
<span class="sd"> the clause is omitted, which on most platforms indicates a</span>
<span class="sd"> maxvalue of 2^63-1 and -1 for ascending and descending sequences,</span>
<span class="sd"> respectively.</span>
<span class="sd"> .. versionadded:: 1.0.7</span>
<span class="sd"> :param nominvalue: no minimum value of the sequence. This</span>
<span class="sd"> value is used when the CREATE SEQUENCE command is emitted to</span>
<span class="sd"> the database as the value of the "NO MINVALUE" clause. If ``None``,</span>
<span class="sd"> the clause is omitted, which on most platforms indicates a</span>
<span class="sd"> minvalue of 1 and -2^63-1 for ascending and descending sequences,</span>
<span class="sd"> respectively.</span>
<span class="sd"> .. versionadded:: 1.0.7</span>
<span class="sd"> :param nomaxvalue: no maximum value of the sequence. This</span>
<span class="sd"> value is used when the CREATE SEQUENCE command is emitted to</span>
<span class="sd"> the database as the value of the "NO MAXVALUE" clause. If ``None``,</span>
<span class="sd"> the clause is omitted, which on most platforms indicates a</span>
<span class="sd"> maxvalue of 2^63-1 and -1 for ascending and descending sequences,</span>
<span class="sd"> respectively.</span>
<span class="sd"> .. versionadded:: 1.0.7</span>
<span class="sd"> :param cycle: allows the sequence to wrap around when the maxvalue</span>
<span class="sd"> or minvalue has been reached by an ascending or descending sequence</span>
<span class="sd"> respectively. This value is used when the CREATE SEQUENCE command</span>
<span class="sd"> is emitted to the database as the "CYCLE" clause. If the limit is</span>
<span class="sd"> reached, the next number generated will be the minvalue or maxvalue,</span>
<span class="sd"> respectively. If cycle=False (the default) any calls to nextval</span>
<span class="sd"> after the sequence has reached its maximum value will return an</span>
<span class="sd"> error.</span>
<span class="sd"> .. versionadded:: 1.0.7</span>
<span class="sd"> :param schema: Optional schema name for the sequence, if located</span>
<span class="sd"> in a schema other than the default. The rules for selecting the</span>
<span class="sd"> schema name when a :class:`.MetaData` is also present are the same</span>
<span class="sd"> as that of :paramref:`.Table.schema`.</span>
<span class="sd"> :param optional: boolean value, when ``True``, indicates that this</span>
<span class="sd"> :class:`.Sequence` object only needs to be explicitly generated</span>
<span class="sd"> on backends that don't provide another way to generate primary</span>
<span class="sd"> key identifiers. Currently, it essentially means, "don't create</span>
<span class="sd"> this sequence on the PostgreSQL backend, where the SERIAL keyword</span>
<span class="sd"> creates a sequence for us automatically".</span>
<span class="sd"> :param quote: boolean value, when ``True`` or ``False``, explicitly</span>
<span class="sd"> forces quoting of the schema name on or off. When left at its</span>
<span class="sd"> default of ``None``, normal quoting rules based on casing and</span>
<span class="sd"> reserved words take place.</span>
<span class="sd"> :param quote_schema: set the quoting preferences for the ``schema``</span>
<span class="sd"> name.</span>
<span class="sd"> :param metadata: optional :class:`.MetaData` object which this</span>
<span class="sd"> :class:`.Sequence` will be associated with. A :class:`.Sequence`</span>
<span class="sd"> that is associated with a :class:`.MetaData` gains the following</span>
<span class="sd"> capabilities:</span>
<span class="sd"> * The :class:`.Sequence` will inherit the :paramref:`.MetaData.schema`</span>
<span class="sd"> parameter specified to the target :class:`.MetaData`, which</span>
<span class="sd"> affects the production of CREATE / DROP DDL, if any.</span>
<span class="sd"> * The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods</span>
<span class="sd"> automatically use the engine bound to the :class:`.MetaData`</span>
<span class="sd"> object, if any.</span>
<span class="sd"> * The :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all`</span>
<span class="sd"> methods will emit CREATE / DROP for this :class:`.Sequence`,</span>
<span class="sd"> even if the :class:`.Sequence` is not associated with any</span>
<span class="sd"> :class:`.Table` / :class:`.Column` that's a member of this</span>
<span class="sd"> :class:`.MetaData`.</span>
<span class="sd"> The above behaviors can only occur if the :class:`.Sequence` is</span>
<span class="sd"> explicitly associated with the :class:`.MetaData` via this parameter.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`sequence_metadata` - full discussion of the</span>
<span class="sd"> :paramref:`.Sequence.metadata` parameter.</span>
<span class="sd"> :param for_update: Indicates this :class:`.Sequence`, when associated</span>
<span class="sd"> with a :class:`.Column`, should be invoked for UPDATE statements</span>
<span class="sd"> on that column's table, rather than for INSERT statements, when</span>
<span class="sd"> no value is otherwise present for that column in the statement.</span>
<span class="sd"> """</span>
<span class="nb">super</span><span class="p">(</span><span class="n">Sequence</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">for_update</span><span class="o">=</span><span class="n">for_update</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">quote</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">start</span> <span class="o">=</span> <span class="n">start</span>
<span class="bp">self</span><span class="o">.</span><span class="n">increment</span> <span class="o">=</span> <span class="n">increment</span>
<span class="bp">self</span><span class="o">.</span><span class="n">minvalue</span> <span class="o">=</span> <span class="n">minvalue</span>
<span class="bp">self</span><span class="o">.</span><span class="n">maxvalue</span> <span class="o">=</span> <span class="n">maxvalue</span>
<span class="bp">self</span><span class="o">.</span><span class="n">nominvalue</span> <span class="o">=</span> <span class="n">nominvalue</span>
<span class="bp">self</span><span class="o">.</span><span class="n">nomaxvalue</span> <span class="o">=</span> <span class="n">nomaxvalue</span>
<span class="bp">self</span><span class="o">.</span><span class="n">cycle</span> <span class="o">=</span> <span class="n">cycle</span>
<span class="bp">self</span><span class="o">.</span><span class="n">optional</span> <span class="o">=</span> <span class="n">optional</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="n">BLANK_SCHEMA</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">schema</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">elif</span> <span class="n">metadata</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">metadata</span><span class="o">.</span><span class="n">schema</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">schema</span> <span class="o">=</span> <span class="n">metadata</span><span class="o">.</span><span class="n">schema</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">quote_schema</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span> <span class="o">=</span> <span class="n">metadata</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_key</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="k">if</span> <span class="n">metadata</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_metadata</span><span class="p">(</span><span class="n">metadata</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">is_callable</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">is_clause_element</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">dependencies</span><span class="p">(</span><span class="s2">"sqlalchemy.sql.functions.func"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">next_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">func</span><span class="p">):</span>
<span class="sd">"""Return a :class:`.next_value` function element</span>
<span class="sd"> which will render the appropriate increment function</span>
<span class="sd"> for this :class:`.Sequence` within any SQL expression.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">func</span><span class="o">.</span><span class="n">next_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">bind</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">Sequence</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="n">column</span><span class="p">)</span>
<span class="n">column</span><span class="o">.</span><span class="n">_on_table_attach</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_set_table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_metadata</span><span class="p">(</span><span class="n">table</span><span class="o">.</span><span class="n">metadata</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_metadata</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">metadata</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span> <span class="o">=</span> <span class="n">metadata</span>
<span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">_sequences</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_key</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">metadata</span><span class="o">.</span><span class="n">bind</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="sd">"""Creates this sequence in the database."""</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaGenerator</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">drop</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="sd">"""Drops this sequence from the database."""</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaDropper</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_not_a_column_expr</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"This </span><span class="si">%s</span><span class="s2"> cannot be used directly "</span>
<span class="s2">"as a column expression. Use func.next_value(sequence) "</span>
<span class="s2">"to produce a 'next value' function that's usable "</span>
<span class="s2">"as a column element."</span>
<span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="nd">@inspection</span><span class="o">.</span><span class="n">_self_inspects</span>
<span class="k">class</span> <span class="nc">FetchedValue</span><span class="p">(</span><span class="n">_NotAColumnExpr</span><span class="p">,</span> <span class="n">SchemaEventTarget</span><span class="p">):</span>
<span class="sd">"""A marker for a transparent database-side default.</span>
<span class="sd"> Use :class:`.FetchedValue` when the database is configured</span>
<span class="sd"> to provide some automatic default for a column.</span>
<span class="sd"> E.g.::</span>
<span class="sd"> Column('foo', Integer, FetchedValue())</span>
<span class="sd"> Would indicate that some trigger or default generator</span>
<span class="sd"> will create a new value for the ``foo`` column during an</span>
<span class="sd"> INSERT.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`triggered_columns`</span>
<span class="sd"> """</span>
<span class="n">is_server_default</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">reflected</span> <span class="o">=</span> <span class="kc">False</span>
<span class="n">has_argument</span> <span class="o">=</span> <span class="kc">False</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">for_update</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">for_update</span> <span class="o">=</span> <span class="n">for_update</span>
<span class="k">def</span> <span class="nf">_as_for_update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">for_update</span><span class="p">):</span>
<span class="k">if</span> <span class="n">for_update</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">for_update</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_clone</span><span class="p">(</span><span class="n">for_update</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_clone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">for_update</span><span class="p">):</span>
<span class="n">n</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">)</span>
<span class="n">n</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">)</span>
<span class="n">n</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'column'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">n</span><span class="o">.</span><span class="n">for_update</span> <span class="o">=</span> <span class="n">for_update</span>
<span class="k">return</span> <span class="n">n</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span> <span class="o">=</span> <span class="n">column</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">for_update</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">server_onupdate</span> <span class="o">=</span> <span class="bp">self</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">server_default</span> <span class="o">=</span> <span class="bp">self</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">generic_repr</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">DefaultClause</span><span class="p">(</span><span class="n">FetchedValue</span><span class="p">):</span>
<span class="sd">"""A DDL-specified DEFAULT column value.</span>
<span class="sd"> :class:`.DefaultClause` is a :class:`.FetchedValue`</span>
<span class="sd"> that also generates a "DEFAULT" clause when</span>
<span class="sd"> "CREATE TABLE" is emitted.</span>
<span class="sd"> :class:`.DefaultClause` is generated automatically</span>
<span class="sd"> whenever the ``server_default``, ``server_onupdate`` arguments of</span>
<span class="sd"> :class:`.Column` are used. A :class:`.DefaultClause`</span>
<span class="sd"> can be passed positionally as well.</span>
<span class="sd"> For example, the following::</span>
<span class="sd"> Column('foo', Integer, server_default="50")</span>
<span class="sd"> Is equivalent to::</span>
<span class="sd"> Column('foo', Integer, DefaultClause("50"))</span>
<span class="sd"> """</span>
<span class="n">has_argument</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">,</span> <span class="n">for_update</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">_reflected</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="n">util</span><span class="o">.</span><span class="n">assert_arg_type</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="p">(</span><span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span>
<span class="n">ClauseElement</span><span class="p">,</span>
<span class="n">TextClause</span><span class="p">),</span> <span class="s1">'arg'</span><span class="p">)</span>
<span class="nb">super</span><span class="p">(</span><span class="n">DefaultClause</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">for_update</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">arg</span> <span class="o">=</span> <span class="n">arg</span>
<span class="bp">self</span><span class="o">.</span><span class="n">reflected</span> <span class="o">=</span> <span class="n">_reflected</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"DefaultClause(</span><span class="si">%r</span><span class="s2">, for_update=</span><span class="si">%r</span><span class="s2">)"</span> <span class="o">%</span> \
<span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">arg</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">for_update</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">PassiveDefault</span><span class="p">(</span><span class="n">DefaultClause</span><span class="p">):</span>
<span class="sd">"""A DDL-specified DEFAULT column value.</span>
<span class="sd"> .. deprecated:: 0.6</span>
<span class="sd"> :class:`.PassiveDefault` is deprecated.</span>
<span class="sd"> Use :class:`.DefaultClause`.</span>
<span class="sd"> """</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">deprecated</span><span class="p">(</span><span class="s2">"0.6"</span><span class="p">,</span>
<span class="s2">":class:`.PassiveDefault` is deprecated. "</span>
<span class="s2">"Use :class:`.DefaultClause`."</span><span class="p">,</span>
<span class="kc">False</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">DefaultClause</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Constraint</span><span class="p">(</span><span class="n">DialectKWArgs</span><span class="p">,</span> <span class="n">SchemaItem</span><span class="p">):</span>
<span class="sd">"""A table-level SQL constraint."""</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'constraint'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">initially</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">_create_rule</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">info</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">_type_bound</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
<span class="o">**</span><span class="n">dialect_kw</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Create a SQL constraint.</span>
<span class="sd"> :param name:</span>
<span class="sd"> Optional, the in-database name of this ``Constraint``.</span>
<span class="sd"> :param deferrable:</span>
<span class="sd"> Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when</span>
<span class="sd"> issuing DDL for this constraint.</span>
<span class="sd"> :param initially:</span>
<span class="sd"> Optional string. If set, emit INITIALLY <value> when issuing DDL</span>
<span class="sd"> for this constraint.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> :param _create_rule:</span>
<span class="sd"> a callable which is passed the DDLCompiler object during</span>
<span class="sd"> compilation. Returns True or False to signal inline generation of</span>
<span class="sd"> this Constraint.</span>
<span class="sd"> The AddConstraint and DropConstraint DDL constructs provide</span>
<span class="sd"> DDLElement's more comprehensive "conditional DDL" approach that is</span>
<span class="sd"> passed a database connection when DDL is being issued. _create_rule</span>
<span class="sd"> is instead called during any CREATE TABLE compilation, where there</span>
<span class="sd"> may not be any transaction/connection in progress. However, it</span>
<span class="sd"> allows conditional compilation of the constraint even for backends</span>
<span class="sd"> which do not support addition of constraints through ALTER TABLE,</span>
<span class="sd"> which currently includes SQLite.</span>
<span class="sd"> _create_rule is used by some types to create constraints.</span>
<span class="sd"> Currently, its call signature is subject to change at any time.</span>
<span class="sd"> :param \**dialect_kw: Additional keyword arguments are dialect</span>
<span class="sd"> specific, and passed in the form ``<dialectname>_<argname>``. See</span>
<span class="sd"> the documentation regarding an individual dialect at</span>
<span class="sd"> :ref:`dialect_toplevel` for detail on documented arguments.</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span> <span class="o">=</span> <span class="n">deferrable</span>
<span class="bp">self</span><span class="o">.</span><span class="n">initially</span> <span class="o">=</span> <span class="n">initially</span>
<span class="k">if</span> <span class="n">info</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">info</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_create_rule</span> <span class="o">=</span> <span class="n">_create_rule</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_type_bound</span> <span class="o">=</span> <span class="n">_type_bound</span>
<span class="n">util</span><span class="o">.</span><span class="n">set_creation_order</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_validate_dialect_kwargs</span><span class="p">(</span><span class="n">dialect_kw</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">table</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="p">,</span> <span class="n">Table</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span>
<span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
<span class="k">pass</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s2">"This constraint is not bound to a table. Did you "</span>
<span class="s2">"mean to call table.append_constraint(constraint) ?"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parent</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">parent</span> <span class="o">=</span> <span class="n">parent</span>
<span class="n">parent</span><span class="o">.</span><span class="n">constraints</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">_to_schema_column</span><span class="p">(</span><span class="n">element</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="n">element</span> <span class="o">=</span> <span class="n">element</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">Column</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span><span class="s2">"schema.Column object expected"</span><span class="p">)</span>
<span class="k">return</span> <span class="n">element</span>
<span class="k">def</span> <span class="nf">_to_schema_column_or_string</span><span class="p">(</span><span class="n">element</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="n">element</span> <span class="o">=</span> <span class="n">element</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span> <span class="o">+</span> <span class="p">(</span><span class="n">ColumnElement</span><span class="p">,</span> <span class="p">)):</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s2">"Element </span><span class="si">%r</span><span class="s2"> is not a string name or column element"</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span><span class="n">msg</span> <span class="o">%</span> <span class="n">element</span><span class="p">)</span>
<span class="k">return</span> <span class="n">element</span>
<span class="k">class</span> <span class="nc">ColumnCollectionMixin</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="n">columns</span> <span class="o">=</span> <span class="kc">None</span>
<span class="sd">"""A :class:`.ColumnCollection` of :class:`.Column` objects.</span>
<span class="sd"> This collection represents the columns which are referred to by</span>
<span class="sd"> this object.</span>
<span class="sd"> """</span>
<span class="n">_allow_multiple_tables</span> <span class="o">=</span> <span class="kc">False</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">_autoattach</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'_autoattach'</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span> <span class="o">=</span> <span class="n">ColumnCollection</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span> <span class="o">=</span> <span class="p">[</span><span class="n">_to_schema_column_or_string</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">columns</span><span class="p">]</span>
<span class="k">if</span> <span class="n">_autoattach</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_check_attach</span><span class="p">()</span>
<span class="nd">@classmethod</span>
<span class="k">def</span> <span class="nf">_extract_col_expression_collection</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">expressions</span><span class="p">):</span>
<span class="k">for</span> <span class="n">expr</span> <span class="ow">in</span> <span class="n">expressions</span><span class="p">:</span>
<span class="n">strname</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">column</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">expr</span><span class="p">,</span> <span class="s1">'__clause_element__'</span><span class="p">):</span>
<span class="n">expr</span> <span class="o">=</span> <span class="n">expr</span><span class="o">.</span><span class="n">__clause_element__</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">expr</span><span class="p">,</span> <span class="p">(</span><span class="n">ColumnElement</span><span class="p">,</span> <span class="n">TextClause</span><span class="p">)):</span>
<span class="c1"># this assumes a string</span>
<span class="n">strname</span> <span class="o">=</span> <span class="n">expr</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">cols</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">visitors</span><span class="o">.</span><span class="n">traverse</span><span class="p">(</span><span class="n">expr</span><span class="p">,</span> <span class="p">{},</span> <span class="p">{</span><span class="s1">'column'</span><span class="p">:</span> <span class="n">cols</span><span class="o">.</span><span class="n">append</span><span class="p">})</span>
<span class="k">if</span> <span class="n">cols</span><span class="p">:</span>
<span class="n">column</span> <span class="o">=</span> <span class="n">cols</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">add_element</span> <span class="o">=</span> <span class="n">column</span> <span class="k">if</span> <span class="n">column</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="k">else</span> <span class="n">strname</span>
<span class="k">yield</span> <span class="n">expr</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">strname</span><span class="p">,</span> <span class="n">add_element</span>
<span class="k">def</span> <span class="nf">_check_attach</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">evt</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="n">col_objs</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">Column</span><span class="p">)</span>
<span class="p">]</span>
<span class="n">cols_w_table</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">col_objs</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">table</span><span class="p">,</span> <span class="n">Table</span><span class="p">)</span>
<span class="p">]</span>
<span class="n">cols_wo_table</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">col_objs</span><span class="p">)</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="n">cols_w_table</span><span class="p">)</span>
<span class="k">if</span> <span class="n">cols_wo_table</span><span class="p">:</span>
<span class="c1"># feature #3341 - place event listeners for Column objects</span>
<span class="c1"># such that when all those cols are attached, we autoattach.</span>
<span class="k">assert</span> <span class="ow">not</span> <span class="n">evt</span><span class="p">,</span> <span class="s2">"Should not reach here on event call"</span>
<span class="c1"># issue #3411 - don't do the per-column auto-attach if some of the</span>
<span class="c1"># columns are specified as strings.</span>
<span class="n">has_string_cols</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span><span class="p">)</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="n">col_objs</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">has_string_cols</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">_col_attached</span><span class="p">(</span><span class="n">column</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="c1"># this isinstance() corresponds with the</span>
<span class="c1"># isinstance() above; only want to count Table-bound</span>
<span class="c1"># columns</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">table</span><span class="p">,</span> <span class="n">Table</span><span class="p">):</span>
<span class="n">cols_wo_table</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="n">column</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">cols_wo_table</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_check_attach</span><span class="p">(</span><span class="n">evt</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_cols_wo_table</span> <span class="o">=</span> <span class="n">cols_wo_table</span>
<span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">cols_wo_table</span><span class="p">:</span>
<span class="n">col</span><span class="o">.</span><span class="n">_on_table_attach</span><span class="p">(</span><span class="n">_col_attached</span><span class="p">)</span>
<span class="k">return</span>
<span class="n">columns</span> <span class="o">=</span> <span class="n">cols_w_table</span>
<span class="n">tables</span> <span class="o">=</span> <span class="nb">set</span><span class="p">([</span><span class="n">c</span><span class="o">.</span><span class="n">table</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">columns</span><span class="p">])</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">tables</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="n">tables</span><span class="o">.</span><span class="n">pop</span><span class="p">())</span>
<span class="k">elif</span> <span class="nb">len</span><span class="p">(</span><span class="n">tables</span><span class="p">)</span> <span class="o">></span> <span class="mi">1</span> <span class="ow">and</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_allow_multiple_tables</span><span class="p">:</span>
<span class="n">table</span> <span class="o">=</span> <span class="n">columns</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">table</span>
<span class="n">others</span> <span class="o">=</span> <span class="p">[</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">columns</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span> <span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">table</span><span class="p">]</span>
<span class="k">if</span> <span class="n">others</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Column(s) </span><span class="si">%s</span><span class="s2"> are not part of table '</span><span class="si">%s</span><span class="s2">'."</span> <span class="o">%</span>
<span class="p">(</span><span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">"'</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">others</span><span class="p">),</span>
<span class="n">table</span><span class="o">.</span><span class="n">description</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="n">col</span> <span class="o">=</span> <span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="p">[</span><span class="n">col</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">col</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ColumnCollectionConstraint</span><span class="p">(</span><span class="n">ColumnCollectionMixin</span><span class="p">,</span> <span class="n">Constraint</span><span class="p">):</span>
<span class="sd">"""A constraint that proxies a ColumnCollection."""</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""</span>
<span class="sd"> :param \*columns:</span>
<span class="sd"> A sequence of column names or Column objects.</span>
<span class="sd"> :param name:</span>
<span class="sd"> Optional, the in-database name of this constraint.</span>
<span class="sd"> :param deferrable:</span>
<span class="sd"> Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when</span>
<span class="sd"> issuing DDL for this constraint.</span>
<span class="sd"> :param initially:</span>
<span class="sd"> Optional string. If set, emit INITIALLY <value> when issuing DDL</span>
<span class="sd"> for this constraint.</span>
<span class="sd"> :param \**kw: other keyword arguments including dialect-specific</span>
<span class="sd"> arguments are propagated to the :class:`.Constraint` superclass.</span>
<span class="sd"> """</span>
<span class="n">_autoattach</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'_autoattach'</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="n">Constraint</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="n">ColumnCollectionMixin</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">,</span> <span class="n">_autoattach</span><span class="o">=</span><span class="n">_autoattach</span><span class="p">)</span>
<span class="n">columns</span> <span class="o">=</span> <span class="kc">None</span>
<span class="sd">"""A :class:`.ColumnCollection` representing the set of columns</span>
<span class="sd"> for this constraint.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">Constraint</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="n">ColumnCollectionMixin</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">c</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span> <span class="o">*</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">contains_column</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">col</span><span class="p">):</span>
<span class="sd">"""Return True if this constraint contains the given column.</span>
<span class="sd"> Note that this object also contains an attribute ``.columns``</span>
<span class="sd"> which is a :class:`.ColumnCollection` of :class:`.Column` objects.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">contains_column</span><span class="p">(</span><span class="n">col</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c1"># inlining of</span>
<span class="c1"># return iter(self.columns)</span>
<span class="c1"># ColumnCollection->OrderedProperties->OrderedDict</span>
<span class="n">ordered_dict</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">_data</span>
<span class="k">return</span> <span class="p">(</span><span class="n">ordered_dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">ordered_dict</span><span class="o">.</span><span class="n">_list</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">_data</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">CheckConstraint</span><span class="p">(</span><span class="n">ColumnCollectionConstraint</span><span class="p">):</span>
<span class="sd">"""A table- or column-level CHECK constraint.</span>
<span class="sd"> Can be included in the definition of a Table or Column.</span>
<span class="sd"> """</span>
<span class="n">_allow_multiple_tables</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sqltext</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">table</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">info</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">_create_rule</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">_autoattach</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">_type_bound</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Construct a CHECK constraint.</span>
<span class="sd"> :param sqltext:</span>
<span class="sd"> A string containing the constraint definition, which will be used</span>
<span class="sd"> verbatim, or a SQL expression construct. If given as a string,</span>
<span class="sd"> the object is converted to a :class:`.Text` object. If the textual</span>
<span class="sd"> string includes a colon character, escape this using a backslash::</span>
<span class="sd"> CheckConstraint(r"foo ~ E'a(?\:b|c)d")</span>
<span class="sd"> :param name:</span>
<span class="sd"> Optional, the in-database name of the constraint.</span>
<span class="sd"> :param deferrable:</span>
<span class="sd"> Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when</span>
<span class="sd"> issuing DDL for this constraint.</span>
<span class="sd"> :param initially:</span>
<span class="sd"> Optional string. If set, emit INITIALLY <value> when issuing DDL</span>
<span class="sd"> for this constraint.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">sqltext</span> <span class="o">=</span> <span class="n">_literal_as_text</span><span class="p">(</span><span class="n">sqltext</span><span class="p">,</span> <span class="n">warn</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="n">columns</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">visitors</span><span class="o">.</span><span class="n">traverse</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">sqltext</span><span class="p">,</span> <span class="p">{},</span> <span class="p">{</span><span class="s1">'column'</span><span class="p">:</span> <span class="n">columns</span><span class="o">.</span><span class="n">append</span><span class="p">})</span>
<span class="nb">super</span><span class="p">(</span><span class="n">CheckConstraint</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span>\
<span class="fm">__init__</span><span class="p">(</span>
<span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="n">initially</span><span class="p">,</span> <span class="n">_create_rule</span><span class="o">=</span><span class="n">_create_rule</span><span class="p">,</span> <span class="n">info</span><span class="o">=</span><span class="n">info</span><span class="p">,</span>
<span class="n">_type_bound</span><span class="o">=</span><span class="n">_type_bound</span><span class="p">,</span> <span class="n">_autoattach</span><span class="o">=</span><span class="n">_autoattach</span><span class="p">,</span>
<span class="o">*</span><span class="n">columns</span><span class="p">)</span>
<span class="k">if</span> <span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__visit_name__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">parent</span><span class="p">,</span> <span class="n">Table</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"check_constraint"</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="s2">"column_check_constraint"</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">__visit_name__</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target_table</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="k">if</span> <span class="n">target_table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">replace</span><span class="p">(</span><span class="n">col</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">contains_column</span><span class="p">(</span><span class="n">col</span><span class="p">):</span>
<span class="k">return</span> <span class="n">target_table</span><span class="o">.</span><span class="n">c</span><span class="p">[</span><span class="n">col</span><span class="o">.</span><span class="n">key</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="n">sqltext</span> <span class="o">=</span> <span class="n">visitors</span><span class="o">.</span><span class="n">replacement_traverse</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">sqltext</span><span class="p">,</span> <span class="p">{},</span> <span class="n">replace</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">sqltext</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">sqltext</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">CheckConstraint</span><span class="p">(</span><span class="n">sqltext</span><span class="p">,</span>
<span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span>
<span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">_create_rule</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_create_rule</span><span class="p">,</span>
<span class="n">table</span><span class="o">=</span><span class="n">target_table</span><span class="p">,</span>
<span class="n">_autoattach</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
<span class="n">_type_bound</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_type_bound</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ForeignKeyConstraint</span><span class="p">(</span><span class="n">ColumnCollectionConstraint</span><span class="p">):</span>
<span class="sd">"""A table-level FOREIGN KEY constraint.</span>
<span class="sd"> Defines a single column or composite FOREIGN KEY ... REFERENCES</span>
<span class="sd"> constraint. For a no-frills, single column foreign key, adding a</span>
<span class="sd"> :class:`.ForeignKey` to the definition of a :class:`.Column` is a</span>
<span class="sd"> shorthand equivalent for an unnamed, single column</span>
<span class="sd"> :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> Examples of foreign key configuration are in :ref:`metadata_foreignkeys`.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'foreign_key_constraint'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">columns</span><span class="p">,</span> <span class="n">refcolumns</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">onupdate</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">ondelete</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">initially</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">use_alter</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">link_to_name</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">match</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">table</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">info</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">dialect_kw</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Construct a composite-capable FOREIGN KEY.</span>
<span class="sd"> :param columns: A sequence of local column names. The named columns</span>
<span class="sd"> must be defined and present in the parent Table. The names should</span>
<span class="sd"> match the ``key`` given to each column (defaults to the name) unless</span>
<span class="sd"> ``link_to_name`` is True.</span>
<span class="sd"> :param refcolumns: A sequence of foreign column names or Column</span>
<span class="sd"> objects. The columns must all be located within the same Table.</span>
<span class="sd"> :param name: Optional, the in-database name of the key.</span>
<span class="sd"> :param onupdate: Optional string. If set, emit ON UPDATE <value> when</span>
<span class="sd"> issuing DDL for this constraint. Typical values include CASCADE,</span>
<span class="sd"> DELETE and RESTRICT.</span>
<span class="sd"> :param ondelete: Optional string. If set, emit ON DELETE <value> when</span>
<span class="sd"> issuing DDL for this constraint. Typical values include CASCADE,</span>
<span class="sd"> DELETE and RESTRICT.</span>
<span class="sd"> :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT</span>
<span class="sd"> DEFERRABLE when issuing DDL for this constraint.</span>
<span class="sd"> :param initially: Optional string. If set, emit INITIALLY <value> when</span>
<span class="sd"> issuing DDL for this constraint.</span>
<span class="sd"> :param link_to_name: if True, the string name given in ``column`` is</span>
<span class="sd"> the rendered name of the referenced column, not its locally assigned</span>
<span class="sd"> ``key``.</span>
<span class="sd"> :param use_alter: If True, do not emit the DDL for this constraint as</span>
<span class="sd"> part of the CREATE TABLE definition. Instead, generate it via an</span>
<span class="sd"> ALTER TABLE statement issued after the full collection of tables</span>
<span class="sd"> have been created, and drop it via an ALTER TABLE statement before</span>
<span class="sd"> the full collection of tables are dropped.</span>
<span class="sd"> The use of :paramref:`.ForeignKeyConstraint.use_alter` is</span>
<span class="sd"> particularly geared towards the case where two or more tables</span>
<span class="sd"> are established within a mutually-dependent foreign key constraint</span>
<span class="sd"> relationship; however, the :meth:`.MetaData.create_all` and</span>
<span class="sd"> :meth:`.MetaData.drop_all` methods will perform this resolution</span>
<span class="sd"> automatically, so the flag is normally not needed.</span>
<span class="sd"> .. versionchanged:: 1.0.0 Automatic resolution of foreign key</span>
<span class="sd"> cycles has been added, removing the need to use the</span>
<span class="sd"> :paramref:`.ForeignKeyConstraint.use_alter` in typical use</span>
<span class="sd"> cases.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`use_alter`</span>
<span class="sd"> :param match: Optional string. If set, emit MATCH <value> when issuing</span>
<span class="sd"> DDL for this constraint. Typical values include SIMPLE, PARTIAL</span>
<span class="sd"> and FULL.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> :param \**dialect_kw: Additional keyword arguments are dialect</span>
<span class="sd"> specific, and passed in the form ``<dialectname>_<argname>``. See</span>
<span class="sd"> the documentation regarding an individual dialect at</span>
<span class="sd"> :ref:`dialect_toplevel` for detail on documented arguments.</span>
<span class="sd"> .. versionadded:: 0.9.2</span>
<span class="sd"> """</span>
<span class="n">Constraint</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span>
<span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">,</span> <span class="n">deferrable</span><span class="o">=</span><span class="n">deferrable</span><span class="p">,</span> <span class="n">initially</span><span class="o">=</span><span class="n">initially</span><span class="p">,</span>
<span class="n">info</span><span class="o">=</span><span class="n">info</span><span class="p">,</span> <span class="o">**</span><span class="n">dialect_kw</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span> <span class="o">=</span> <span class="n">onupdate</span>
<span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span> <span class="o">=</span> <span class="n">ondelete</span>
<span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span> <span class="o">=</span> <span class="n">link_to_name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span> <span class="o">=</span> <span class="n">use_alter</span>
<span class="bp">self</span><span class="o">.</span><span class="n">match</span> <span class="o">=</span> <span class="n">match</span>
<span class="c1"># standalone ForeignKeyConstraint - create</span>
<span class="c1"># associated ForeignKey objects which will be applied to hosted</span>
<span class="c1"># Column objects (in col.foreign_keys), either now or when attached</span>
<span class="c1"># to the Table for string-specified names</span>
<span class="bp">self</span><span class="o">.</span><span class="n">elements</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">ForeignKey</span><span class="p">(</span>
<span class="n">refcol</span><span class="p">,</span>
<span class="n">_constraint</span><span class="o">=</span><span class="bp">self</span><span class="p">,</span>
<span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span>
<span class="n">ondelete</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span><span class="p">,</span>
<span class="n">use_alter</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span><span class="p">,</span>
<span class="n">link_to_name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span><span class="p">,</span>
<span class="n">match</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">match</span><span class="p">,</span>
<span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span>
<span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">dialect_kwargs</span>
<span class="p">)</span> <span class="k">for</span> <span class="n">refcol</span> <span class="ow">in</span> <span class="n">refcolumns</span>
<span class="p">]</span>
<span class="n">ColumnCollectionMixin</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">)</span>
<span class="k">if</span> <span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s2">"parent"</span><span class="p">):</span>
<span class="k">assert</span> <span class="n">table</span> <span class="ow">is</span> <span class="bp">self</span><span class="o">.</span><span class="n">parent</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_append_element</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">fk</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">column</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">fk</span><span class="p">)</span>
<span class="n">columns</span> <span class="o">=</span> <span class="kc">None</span>
<span class="sd">"""A :class:`.ColumnCollection` representing the set of columns</span>
<span class="sd"> for this constraint.</span>
<span class="sd"> """</span>
<span class="n">elements</span> <span class="o">=</span> <span class="kc">None</span>
<span class="sd">"""A sequence of :class:`.ForeignKey` objects.</span>
<span class="sd"> Each :class:`.ForeignKey` represents a single referring column/referred</span>
<span class="sd"> column pair.</span>
<span class="sd"> This collection is intended to be read-only.</span>
<span class="sd"> """</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_elements</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c1"># legacy - provide a dictionary view of (column_key, fk)</span>
<span class="k">return</span> <span class="n">util</span><span class="o">.</span><span class="n">OrderedDict</span><span class="p">(</span>
<span class="nb">zip</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">column_keys</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>
<span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_referred_schema</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">:</span>
<span class="k">return</span> <span class="n">elem</span><span class="o">.</span><span class="n">_referred_schema</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">referred_table</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""The :class:`.Table` object to which this</span>
<span class="sd"> :class:`.ForeignKeyConstraint` references.</span>
<span class="sd"> This is a dynamically calculated attribute which may not be available</span>
<span class="sd"> if the constraint and/or parent table is not yet associated with</span>
<span class="sd"> a metadata collection that contains the referred table.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">column</span><span class="o">.</span><span class="n">table</span>
<span class="k">def</span> <span class="nf">_validate_dest_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">table_keys</span> <span class="o">=</span> <span class="nb">set</span><span class="p">([</span><span class="n">elem</span><span class="o">.</span><span class="n">_table_key</span><span class="p">()</span>
<span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">])</span>
<span class="k">if</span> <span class="kc">None</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">table_keys</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">table_keys</span><span class="p">)</span> <span class="o">></span> <span class="mi">1</span><span class="p">:</span>
<span class="n">elem0</span><span class="p">,</span> <span class="n">elem1</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">table_keys</span><span class="p">)[</span><span class="mi">0</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s1">'ForeignKeyConstraint on </span><span class="si">%s</span><span class="s1">(</span><span class="si">%s</span><span class="s1">) refers to '</span>
<span class="s1">'multiple remote tables: </span><span class="si">%s</span><span class="s1"> and </span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span>
<span class="n">table</span><span class="o">.</span><span class="n">fullname</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_col_description</span><span class="p">,</span>
<span class="n">elem0</span><span class="p">,</span>
<span class="n">elem1</span>
<span class="p">))</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">column_keys</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return a list of string keys representing the local</span>
<span class="sd"> columns in this :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> This list is either the original string arguments sent</span>
<span class="sd"> to the constructor of the :class:`.ForeignKeyConstraint`,</span>
<span class="sd"> or if the constraint has been initialized with :class:`.Column`</span>
<span class="sd"> objects, is the string .key of each element.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s2">"parent"</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="p">[</span>
<span class="n">col</span><span class="o">.</span><span class="n">key</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="n">ColumnElement</span><span class="p">)</span>
<span class="k">else</span> <span class="nb">str</span><span class="p">(</span><span class="n">col</span><span class="p">)</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pending_colargs</span>
<span class="p">]</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">_col_description</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">column_keys</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">Constraint</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">ColumnCollectionConstraint</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">KeyError</span> <span class="k">as</span> <span class="n">ke</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Can't create ForeignKeyConstraint "</span>
<span class="s2">"on table '</span><span class="si">%s</span><span class="s2">': no column "</span>
<span class="s2">"named '</span><span class="si">%s</span><span class="s2">' is present."</span> <span class="o">%</span> <span class="p">(</span><span class="n">table</span><span class="o">.</span><span class="n">description</span><span class="p">,</span> <span class="n">ke</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
<span class="k">for</span> <span class="n">col</span><span class="p">,</span> <span class="n">fk</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">fk</span><span class="p">,</span> <span class="s1">'parent'</span><span class="p">)</span> <span class="ow">or</span> \
<span class="n">fk</span><span class="o">.</span><span class="n">parent</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">col</span><span class="p">:</span>
<span class="n">fk</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="n">col</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_validate_dest_table</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">copy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">target_table</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">fkc</span> <span class="o">=</span> <span class="n">ForeignKeyConstraint</span><span class="p">(</span>
<span class="p">[</span><span class="n">x</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">key</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">],</span>
<span class="p">[</span><span class="n">x</span><span class="o">.</span><span class="n">_get_colspec</span><span class="p">(</span>
<span class="n">schema</span><span class="o">=</span><span class="n">schema</span><span class="p">,</span>
<span class="n">table_name</span><span class="o">=</span><span class="n">target_table</span><span class="o">.</span><span class="n">name</span>
<span class="k">if</span> <span class="n">target_table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
<span class="ow">and</span> <span class="n">x</span><span class="o">.</span><span class="n">_table_key</span><span class="p">()</span> <span class="o">==</span> <span class="n">x</span><span class="o">.</span><span class="n">parent</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">key</span>
<span class="k">else</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">],</span>
<span class="n">name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="n">onupdate</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">onupdate</span><span class="p">,</span>
<span class="n">ondelete</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">ondelete</span><span class="p">,</span>
<span class="n">use_alter</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">use_alter</span><span class="p">,</span>
<span class="n">deferrable</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">deferrable</span><span class="p">,</span>
<span class="n">initially</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">initially</span><span class="p">,</span>
<span class="n">link_to_name</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">link_to_name</span><span class="p">,</span>
<span class="n">match</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">match</span>
<span class="p">)</span>
<span class="k">for</span> <span class="n">self_fk</span><span class="p">,</span> <span class="n">other_fk</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">,</span>
<span class="n">fkc</span><span class="o">.</span><span class="n">elements</span><span class="p">):</span>
<span class="n">self_fk</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">other_fk</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schema_item_copy</span><span class="p">(</span><span class="n">fkc</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">PrimaryKeyConstraint</span><span class="p">(</span><span class="n">ColumnCollectionConstraint</span><span class="p">):</span>
<span class="sd">"""A table-level PRIMARY KEY constraint.</span>
<span class="sd"> The :class:`.PrimaryKeyConstraint` object is present automatically</span>
<span class="sd"> on any :class:`.Table` object; it is assigned a set of</span>
<span class="sd"> :class:`.Column` objects corresponding to those marked with</span>
<span class="sd"> the :paramref:`.Column.primary_key` flag::</span>
<span class="sd"> >>> my_table = Table('mytable', metadata,</span>
<span class="sd"> ... Column('id', Integer, primary_key=True),</span>
<span class="sd"> ... Column('version_id', Integer, primary_key=True),</span>
<span class="sd"> ... Column('data', String(50))</span>
<span class="sd"> ... )</span>
<span class="sd"> >>> my_table.primary_key</span>
<span class="sd"> PrimaryKeyConstraint(</span>
<span class="sd"> Column('id', Integer(), table=<mytable>,</span>
<span class="sd"> primary_key=True, nullable=False),</span>
<span class="sd"> Column('version_id', Integer(), table=<mytable>,</span>
<span class="sd"> primary_key=True, nullable=False)</span>
<span class="sd"> )</span>
<span class="sd"> The primary key of a :class:`.Table` can also be specified by using</span>
<span class="sd"> a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage,</span>
<span class="sd"> the "name" of the constraint can also be specified, as well as other</span>
<span class="sd"> options which may be recognized by dialects::</span>
<span class="sd"> my_table = Table('mytable', metadata,</span>
<span class="sd"> Column('id', Integer),</span>
<span class="sd"> Column('version_id', Integer),</span>
<span class="sd"> Column('data', String(50)),</span>
<span class="sd"> PrimaryKeyConstraint('id', 'version_id',</span>
<span class="sd"> name='mytable_pk')</span>
<span class="sd"> )</span>
<span class="sd"> The two styles of column-specification should generally not be mixed.</span>
<span class="sd"> An warning is emitted if the columns present in the</span>
<span class="sd"> :class:`.PrimaryKeyConstraint`</span>
<span class="sd"> don't match the columns that were marked as ``primary_key=True``, if both</span>
<span class="sd"> are present; in this case, the columns are taken strictly from the</span>
<span class="sd"> :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise</span>
<span class="sd"> marked as ``primary_key=True`` are ignored. This behavior is intended to</span>
<span class="sd"> be backwards compatible with previous behavior.</span>
<span class="sd"> .. versionchanged:: 0.9.2 Using a mixture of columns within a</span>
<span class="sd"> :class:`.PrimaryKeyConstraint` in addition to columns marked as</span>
<span class="sd"> ``primary_key=True`` now emits a warning if the lists don't match.</span>
<span class="sd"> The ultimate behavior of ignoring those columns marked with the flag</span>
<span class="sd"> only is currently maintained for backwards compatibility; this warning</span>
<span class="sd"> may raise an exception in a future release.</span>
<span class="sd"> For the use case where specific options are to be specified on the</span>
<span class="sd"> :class:`.PrimaryKeyConstraint`, but the usual style of using</span>
<span class="sd"> ``primary_key=True`` flags is still desirable, an empty</span>
<span class="sd"> :class:`.PrimaryKeyConstraint` may be specified, which will take on the</span>
<span class="sd"> primary key column collection from the :class:`.Table` based on the</span>
<span class="sd"> flags::</span>
<span class="sd"> my_table = Table('mytable', metadata,</span>
<span class="sd"> Column('id', Integer, primary_key=True),</span>
<span class="sd"> Column('version_id', Integer, primary_key=True),</span>
<span class="sd"> Column('data', String(50)),</span>
<span class="sd"> PrimaryKeyConstraint(name='mytable_pk',</span>
<span class="sd"> mssql_clustered=True)</span>
<span class="sd"> )</span>
<span class="sd"> .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now</span>
<span class="sd"> be specified for the purposes of establishing keyword arguments with</span>
<span class="sd"> the constraint, independently of the specification of "primary key"</span>
<span class="sd"> columns within the :class:`.Table` itself; columns marked as</span>
<span class="sd"> ``primary_key=True`` will be gathered into the empty constraint's</span>
<span class="sd"> column collection.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'primary_key_constraint'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_implicit_generated</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'_implicit_generated'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="nb">super</span><span class="p">(</span><span class="n">PrimaryKeyConstraint</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">columns</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">PrimaryKeyConstraint</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
<span class="k">if</span> <span class="n">table</span><span class="o">.</span><span class="n">primary_key</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">self</span><span class="p">:</span>
<span class="n">table</span><span class="o">.</span><span class="n">constraints</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="n">table</span><span class="o">.</span><span class="n">primary_key</span><span class="p">)</span>
<span class="n">table</span><span class="o">.</span><span class="n">primary_key</span> <span class="o">=</span> <span class="bp">self</span>
<span class="n">table</span><span class="o">.</span><span class="n">constraints</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">table_pks</span> <span class="o">=</span> <span class="p">[</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">c</span> <span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">primary_key</span><span class="p">]</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span> <span class="ow">and</span> <span class="n">table_pks</span> <span class="ow">and</span> \
<span class="nb">set</span><span class="p">(</span><span class="n">table_pks</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">values</span><span class="p">()):</span>
<span class="n">util</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span>
<span class="s2">"Table '</span><span class="si">%s</span><span class="s2">' specifies columns </span><span class="si">%s</span><span class="s2"> as primary_key=True, "</span>
<span class="s2">"not matching locally specified columns </span><span class="si">%s</span><span class="s2">; setting the "</span>
<span class="s2">"current primary key columns to </span><span class="si">%s</span><span class="s2">. This warning "</span>
<span class="s2">"may become an exception in a future release"</span> <span class="o">%</span>
<span class="p">(</span>
<span class="n">table</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">"'</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">table_pks</span><span class="p">),</span>
<span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">"'</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">),</span>
<span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s2">"'</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
<span class="p">)</span>
<span class="p">)</span>
<span class="n">table_pks</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">:</span>
<span class="n">c</span><span class="o">.</span><span class="n">primary_key</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">c</span><span class="o">.</span><span class="n">nullable</span> <span class="o">=</span> <span class="kc">False</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">table_pks</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_reload</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">columns</span><span class="p">):</span>
<span class="sd">"""repopulate this :class:`.PrimaryKeyConstraint` given</span>
<span class="sd"> a set of columns.</span>
<span class="sd"> Existing columns in the table that are marked as primary_key=True</span>
<span class="sd"> are maintained.</span>
<span class="sd"> Also fires a new event.</span>
<span class="sd"> This is basically like putting a whole new</span>
<span class="sd"> :class:`.PrimaryKeyConstraint` object on the parent</span>
<span class="sd"> :class:`.Table` object without actually replacing the object.</span>
<span class="sd"> The ordering of the given list of columns is also maintained; these</span>
<span class="sd"> columns will be appended to the list of columns after any which</span>
<span class="sd"> are already present.</span>
<span class="sd"> """</span>
<span class="c1"># set the primary key flag on new columns.</span>
<span class="c1"># note any existing PK cols on the table also have their</span>
<span class="c1"># flag still set.</span>
<span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">columns</span><span class="p">:</span>
<span class="n">col</span><span class="o">.</span><span class="n">primary_key</span> <span class="o">=</span> <span class="kc">True</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">columns</span><span class="p">)</span>
<span class="n">PrimaryKeyConstraint</span><span class="o">.</span><span class="n">_autoincrement_column</span><span class="o">.</span><span class="n">_reset</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_set_parent_with_dispatch</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_replace</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">col</span><span class="p">):</span>
<span class="n">PrimaryKeyConstraint</span><span class="o">.</span><span class="n">_autoincrement_column</span><span class="o">.</span><span class="n">_reset</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">col</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">columns_autoinc_first</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">autoinc</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_autoincrement_column</span>
<span class="k">if</span> <span class="n">autoinc</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="p">[</span><span class="n">autoinc</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span> <span class="k">if</span> <span class="n">c</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">autoinc</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">memoized_property</span>
<span class="k">def</span> <span class="nf">_autoincrement_column</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">_validate_autoinc</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="n">autoinc_true</span><span class="p">):</span>
<span class="k">if</span> <span class="n">col</span><span class="o">.</span><span class="n">type</span><span class="o">.</span><span class="n">_type_affinity</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="ow">not</span> <span class="nb">issubclass</span><span class="p">(</span>
<span class="n">col</span><span class="o">.</span><span class="n">type</span><span class="o">.</span><span class="n">_type_affinity</span><span class="p">,</span>
<span class="n">type_api</span><span class="o">.</span><span class="n">INTEGERTYPE</span><span class="o">.</span><span class="n">_type_affinity</span><span class="p">):</span>
<span class="k">if</span> <span class="n">autoinc_true</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Column type </span><span class="si">%s</span><span class="s2"> on column '</span><span class="si">%s</span><span class="s2">' is not "</span>
<span class="s2">"compatible with autoincrement=True"</span> <span class="o">%</span> <span class="p">(</span>
<span class="n">col</span><span class="o">.</span><span class="n">type</span><span class="p">,</span>
<span class="n">col</span>
<span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">elif</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">col</span><span class="o">.</span><span class="n">default</span><span class="p">,</span> <span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="kc">None</span><span class="p">),</span> <span class="n">Sequence</span><span class="p">))</span> <span class="ow">and</span> \
<span class="ow">not</span> <span class="n">autoinc_true</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">elif</span> <span class="n">col</span><span class="o">.</span><span class="n">server_default</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">autoinc_true</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">elif</span> <span class="p">(</span>
<span class="n">col</span><span class="o">.</span><span class="n">foreign_keys</span> <span class="ow">and</span> <span class="n">col</span><span class="o">.</span><span class="n">autoincrement</span>
<span class="ow">not</span> <span class="ow">in</span> <span class="p">(</span><span class="kc">True</span><span class="p">,</span> <span class="s1">'ignore_fk'</span><span class="p">)):</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">col</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">if</span> <span class="n">col</span><span class="o">.</span><span class="n">autoincrement</span> <span class="ow">is</span> <span class="kc">True</span><span class="p">:</span>
<span class="n">_validate_autoinc</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="k">return</span> <span class="n">col</span>
<span class="k">elif</span> <span class="p">(</span>
<span class="n">col</span><span class="o">.</span><span class="n">autoincrement</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">'auto'</span><span class="p">,</span> <span class="s1">'ignore_fk'</span><span class="p">)</span> <span class="ow">and</span>
<span class="n">_validate_autoinc</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="p">):</span>
<span class="k">return</span> <span class="n">col</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">autoinc</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">:</span>
<span class="k">if</span> <span class="n">col</span><span class="o">.</span><span class="n">autoincrement</span> <span class="ow">is</span> <span class="kc">True</span><span class="p">:</span>
<span class="n">_validate_autoinc</span><span class="p">(</span><span class="n">col</span><span class="p">,</span> <span class="kc">True</span><span class="p">)</span>
<span class="k">if</span> <span class="n">autoinc</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Only one Column may be marked "</span>
<span class="s2">"autoincrement=True, found both </span><span class="si">%s</span><span class="s2"> and </span><span class="si">%s</span><span class="s2">."</span> <span class="o">%</span>
<span class="p">(</span><span class="n">col</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">autoinc</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">autoinc</span> <span class="o">=</span> <span class="n">col</span>
<span class="k">return</span> <span class="n">autoinc</span>
<span class="k">class</span> <span class="nc">UniqueConstraint</span><span class="p">(</span><span class="n">ColumnCollectionConstraint</span><span class="p">):</span>
<span class="sd">"""A table-level UNIQUE constraint.</span>
<span class="sd"> Defines a single column or composite UNIQUE constraint. For a no-frills,</span>
<span class="sd"> single column constraint, adding ``unique=True`` to the ``Column``</span>
<span class="sd"> definition is a shorthand equivalent for an unnamed, single column</span>
<span class="sd"> UniqueConstraint.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'unique_constraint'</span>
<span class="k">class</span> <span class="nc">Index</span><span class="p">(</span><span class="n">DialectKWArgs</span><span class="p">,</span> <span class="n">ColumnCollectionMixin</span><span class="p">,</span> <span class="n">SchemaItem</span><span class="p">):</span>
<span class="sd">"""A table-level INDEX.</span>
<span class="sd"> Defines a composite (one or more column) INDEX.</span>
<span class="sd"> E.g.::</span>
<span class="sd"> sometable = Table("sometable", metadata,</span>
<span class="sd"> Column("name", String(50)),</span>
<span class="sd"> Column("address", String(100))</span>
<span class="sd"> )</span>
<span class="sd"> Index("some_index", sometable.c.name)</span>
<span class="sd"> For a no-frills, single column index, adding</span>
<span class="sd"> :class:`.Column` also supports ``index=True``::</span>
<span class="sd"> sometable = Table("sometable", metadata,</span>
<span class="sd"> Column("name", String(50), index=True)</span>
<span class="sd"> )</span>
<span class="sd"> For a composite index, multiple columns can be specified::</span>
<span class="sd"> Index("some_index", sometable.c.name, sometable.c.address)</span>
<span class="sd"> Functional indexes are supported as well, typically by using the</span>
<span class="sd"> :data:`.func` construct in conjunction with table-bound</span>
<span class="sd"> :class:`.Column` objects::</span>
<span class="sd"> Index("some_index", func.lower(sometable.c.name))</span>
<span class="sd"> .. versionadded:: 0.8 support for functional and expression-based indexes.</span>
<span class="sd"> An :class:`.Index` can also be manually associated with a :class:`.Table`,</span>
<span class="sd"> either through inline declaration or using</span>
<span class="sd"> :meth:`.Table.append_constraint`. When this approach is used, the names</span>
<span class="sd"> of the indexed columns can be specified as strings::</span>
<span class="sd"> Table("sometable", metadata,</span>
<span class="sd"> Column("name", String(50)),</span>
<span class="sd"> Column("address", String(100)),</span>
<span class="sd"> Index("some_index", "name", "address")</span>
<span class="sd"> )</span>
<span class="sd"> To support functional or expression-based indexes in this form, the</span>
<span class="sd"> :func:`.text` construct may be used::</span>
<span class="sd"> from sqlalchemy import text</span>
<span class="sd"> Table("sometable", metadata,</span>
<span class="sd"> Column("name", String(50)),</span>
<span class="sd"> Column("address", String(100)),</span>
<span class="sd"> Index("some_index", text("lower(name)"))</span>
<span class="sd"> )</span>
<span class="sd"> .. versionadded:: 0.9.5 the :func:`.text` construct may be used to</span>
<span class="sd"> specify :class:`.Index` expressions, provided the :class:`.Index`</span>
<span class="sd"> is explicitly associated with the :class:`.Table`.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`schema_indexes` - General information on :class:`.Index`.</span>
<span class="sd"> :ref:`postgresql_indexes` - PostgreSQL-specific options available for</span>
<span class="sd"> the :class:`.Index` construct.</span>
<span class="sd"> :ref:`mysql_indexes` - MySQL-specific options available for the</span>
<span class="sd"> :class:`.Index` construct.</span>
<span class="sd"> :ref:`mssql_indexes` - MSSQL-specific options available for the</span>
<span class="sd"> :class:`.Index` construct.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'index'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="o">*</span><span class="n">expressions</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Construct an index object.</span>
<span class="sd"> :param name:</span>
<span class="sd"> The name of the index</span>
<span class="sd"> :param \*expressions:</span>
<span class="sd"> Column expressions to include in the index. The expressions</span>
<span class="sd"> are normally instances of :class:`.Column`, but may also</span>
<span class="sd"> be arbitrary SQL expressions which ultimately refer to a</span>
<span class="sd"> :class:`.Column`.</span>
<span class="sd"> :param unique=False:</span>
<span class="sd"> Keyword only argument; if True, create a unique index.</span>
<span class="sd"> :param quote=None:</span>
<span class="sd"> Keyword only argument; whether to apply quoting to the name of</span>
<span class="sd"> the index. Works in the same manner as that of</span>
<span class="sd"> :paramref:`.Column.quote`.</span>
<span class="sd"> :param info=None: Optional data dictionary which will be populated</span>
<span class="sd"> into the :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> :param \**kw: Additional keyword arguments not mentioned above are</span>
<span class="sd"> dialect specific, and passed in the form</span>
<span class="sd"> ``<dialectname>_<argname>``. See the documentation regarding an</span>
<span class="sd"> individual dialect at :ref:`dialect_toplevel` for detail on</span>
<span class="sd"> documented arguments.</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">columns</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">processed_expressions</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">expr</span><span class="p">,</span> <span class="n">column</span><span class="p">,</span> <span class="n">strname</span><span class="p">,</span> <span class="n">add_element</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span>\
<span class="n">_extract_col_expression_collection</span><span class="p">(</span><span class="n">expressions</span><span class="p">):</span>
<span class="k">if</span> <span class="n">add_element</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">columns</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">add_element</span><span class="p">)</span>
<span class="n">processed_expressions</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">expr</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">expressions</span> <span class="o">=</span> <span class="n">processed_expressions</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s2">"quote"</span><span class="p">,</span> <span class="kc">None</span><span class="p">))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">unique</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'unique'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
<span class="k">if</span> <span class="s1">'info'</span> <span class="ow">in</span> <span class="n">kw</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">kw</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'info'</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_validate_dialect_kwargs</span><span class="p">(</span><span class="n">kw</span><span class="p">)</span>
<span class="c1"># will call _set_parent() if table-bound column</span>
<span class="c1"># objects are present</span>
<span class="n">ColumnCollectionMixin</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">columns</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">ColumnCollectionMixin</span><span class="o">.</span><span class="n">_set_parent</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">table</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"Index '</span><span class="si">%s</span><span class="s2">' is against table '</span><span class="si">%s</span><span class="s2">', and "</span>
<span class="s2">"cannot be associated with table '</span><span class="si">%s</span><span class="s2">'."</span> <span class="o">%</span> <span class="p">(</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">description</span><span class="p">,</span>
<span class="n">table</span><span class="o">.</span><span class="n">description</span>
<span class="p">)</span>
<span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">table</span> <span class="o">=</span> <span class="n">table</span>
<span class="n">table</span><span class="o">.</span><span class="n">indexes</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">expressions</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">expr</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">expr</span><span class="p">,</span> <span class="n">ClauseElement</span><span class="p">)</span>
<span class="k">else</span> <span class="n">colexpr</span>
<span class="k">for</span> <span class="n">expr</span><span class="p">,</span> <span class="n">colexpr</span> <span class="ow">in</span> <span class="n">util</span><span class="o">.</span><span class="n">zip_longest</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">expressions</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
<span class="p">]</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Return the connectable associated with this Index."""</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">table</span><span class="o">.</span><span class="n">bind</span>
<span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Issue a ``CREATE`` statement for this</span>
<span class="sd"> :class:`.Index`, using the given :class:`.Connectable`</span>
<span class="sd"> for connectivity.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :meth:`.MetaData.create_all`.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaGenerator</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">self</span>
<span class="k">def</span> <span class="nf">drop</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="sd">"""Issue a ``DROP`` statement for this</span>
<span class="sd"> :class:`.Index`, using the given :class:`.Connectable`</span>
<span class="sd"> for connectivity.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :meth:`.MetaData.drop_all`.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaDropper</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'Index(</span><span class="si">%s</span><span class="s1">)'</span> <span class="o">%</span> <span class="p">(</span>
<span class="s2">", "</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)]</span> <span class="o">+</span>
<span class="p">[</span><span class="nb">repr</span><span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">expressions</span><span class="p">]</span> <span class="o">+</span>
<span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">unique</span> <span class="ow">and</span> <span class="p">[</span><span class="s2">"unique=True"</span><span class="p">]</span> <span class="ow">or</span> <span class="p">[])</span>
<span class="p">))</span>
<span class="n">DEFAULT_NAMING_CONVENTION</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">immutabledict</span><span class="p">({</span>
<span class="s2">"ix"</span><span class="p">:</span> <span class="s1">'ix_</span><span class="si">%(column_0_label)s</span><span class="s1">'</span>
<span class="p">})</span>
<span class="k">class</span> <span class="nc">MetaData</span><span class="p">(</span><span class="n">SchemaItem</span><span class="p">):</span>
<span class="sd">"""A collection of :class:`.Table` objects and their associated schema</span>
<span class="sd"> constructs.</span>
<span class="sd"> Holds a collection of :class:`.Table` objects as well as</span>
<span class="sd"> an optional binding to an :class:`.Engine` or</span>
<span class="sd"> :class:`.Connection`. If bound, the :class:`.Table` objects</span>
<span class="sd"> in the collection and their columns may participate in implicit SQL</span>
<span class="sd"> execution.</span>
<span class="sd"> The :class:`.Table` objects themselves are stored in the</span>
<span class="sd"> :attr:`.MetaData.tables` dictionary.</span>
<span class="sd"> :class:`.MetaData` is a thread-safe object for read operations.</span>
<span class="sd"> Construction of new tables within a single :class:`.MetaData` object,</span>
<span class="sd"> either explicitly or via reflection, may not be completely thread-safe.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`metadata_describing` - Introduction to database metadata</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'metadata'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">reflect</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">quote_schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">naming_convention</span><span class="o">=</span><span class="n">DEFAULT_NAMING_CONVENTION</span><span class="p">,</span>
<span class="n">info</span><span class="o">=</span><span class="kc">None</span>
<span class="p">):</span>
<span class="sd">"""Create a new MetaData object.</span>
<span class="sd"> :param bind:</span>
<span class="sd"> An Engine or Connection to bind to. May also be a string or URL</span>
<span class="sd"> instance, these are passed to create_engine() and this MetaData will</span>
<span class="sd"> be bound to the resulting engine.</span>
<span class="sd"> :param reflect:</span>
<span class="sd"> Optional, automatically load all tables from the bound database.</span>
<span class="sd"> Defaults to False. ``bind`` is required when this option is set.</span>
<span class="sd"> .. deprecated:: 0.8</span>
<span class="sd"> Please use the :meth:`.MetaData.reflect` method.</span>
<span class="sd"> :param schema:</span>
<span class="sd"> The default schema to use for the :class:`.Table`,</span>
<span class="sd"> :class:`.Sequence`, and potentially other objects associated with</span>
<span class="sd"> this :class:`.MetaData`. Defaults to ``None``.</span>
<span class="sd"> When this value is set, any :class:`.Table` or :class:`.Sequence`</span>
<span class="sd"> which specifies ``None`` for the schema parameter will instead</span>
<span class="sd"> have this schema name defined. To build a :class:`.Table`</span>
<span class="sd"> or :class:`.Sequence` that still has ``None`` for the schema</span>
<span class="sd"> even when this parameter is present, use the :attr:`.BLANK_SCHEMA`</span>
<span class="sd"> symbol.</span>
<span class="sd"> .. note::</span>
<span class="sd"> As refered above, the :paramref:`.MetaData.schema` parameter</span>
<span class="sd"> only refers to the **default value** that will be applied to</span>
<span class="sd"> the :paramref:`.Table.schema` parameter of an incoming</span>
<span class="sd"> :class:`.Table` object. It does not refer to how the</span>
<span class="sd"> :class:`.Table` is catalogued within the :class:`.MetaData`,</span>
<span class="sd"> which remains consistent vs. a :class:`.MetaData` collection</span>
<span class="sd"> that does not define this parameter. The :class:`.Table`</span>
<span class="sd"> within the :class:`.MetaData` will still be keyed based on its</span>
<span class="sd"> schema-qualified name, e.g.</span>
<span class="sd"> ``my_metadata.tables["some_schema.my_table"]``.</span>
<span class="sd"> The current behavior of the :class:`.ForeignKey` object is to</span>
<span class="sd"> circumvent this restriction, where it can locate a table given</span>
<span class="sd"> the table name alone, where the schema will be assumed to be</span>
<span class="sd"> present from this value as specified on the owning</span>
<span class="sd"> :class:`.MetaData` collection. However, this implies that a</span>
<span class="sd"> table qualified with BLANK_SCHEMA cannot currently be referred</span>
<span class="sd"> to by string name from :class:`.ForeignKey`. Other parts of</span>
<span class="sd"> SQLAlchemy such as Declarative may not have similar behaviors</span>
<span class="sd"> built in, however may do so in a future release, along with a</span>
<span class="sd"> consistent method of referring to a table in BLANK_SCHEMA.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :paramref:`.Table.schema`</span>
<span class="sd"> :paramref:`.Sequence.schema`</span>
<span class="sd"> :param quote_schema:</span>
<span class="sd"> Sets the ``quote_schema`` flag for those :class:`.Table`,</span>
<span class="sd"> :class:`.Sequence`, and other objects which make usage of the</span>
<span class="sd"> local ``schema`` name.</span>
<span class="sd"> :param info: Optional data dictionary which will be populated into the</span>
<span class="sd"> :attr:`.SchemaItem.info` attribute of this object.</span>
<span class="sd"> .. versionadded:: 1.0.0</span>
<span class="sd"> :param naming_convention: a dictionary referring to values which</span>
<span class="sd"> will establish default naming conventions for :class:`.Constraint`</span>
<span class="sd"> and :class:`.Index` objects, for those objects which are not given</span>
<span class="sd"> a name explicitly.</span>
<span class="sd"> The keys of this dictionary may be:</span>
<span class="sd"> * a constraint or Index class, e.g. the :class:`.UniqueConstraint`,</span>
<span class="sd"> :class:`.ForeignKeyConstraint` class, the :class:`.Index` class</span>
<span class="sd"> * a string mnemonic for one of the known constraint classes;</span>
<span class="sd"> ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key,</span>
<span class="sd"> primary key, index, check, and unique constraint, respectively.</span>
<span class="sd"> * the string name of a user-defined "token" that can be used</span>
<span class="sd"> to define new naming tokens.</span>
<span class="sd"> The values associated with each "constraint class" or "constraint</span>
<span class="sd"> mnemonic" key are string naming templates, such as</span>
<span class="sd"> ``"uq_%(table_name)s_%(column_0_name)s"``,</span>
<span class="sd"> which describe how the name should be composed. The values</span>
<span class="sd"> associated with user-defined "token" keys should be callables of the</span>
<span class="sd"> form ``fn(constraint, table)``, which accepts the constraint/index</span>
<span class="sd"> object and :class:`.Table` as arguments, returning a string</span>
<span class="sd"> result.</span>
<span class="sd"> The built-in names are as follows, some of which may only be</span>
<span class="sd"> available for certain types of constraint:</span>
<span class="sd"> * ``%(table_name)s`` - the name of the :class:`.Table` object</span>
<span class="sd"> associated with the constraint.</span>
<span class="sd"> * ``%(referred_table_name)s`` - the name of the :class:`.Table`</span>
<span class="sd"> object associated with the referencing target of a</span>
<span class="sd"> :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> * ``%(column_0_name)s`` - the name of the :class:`.Column` at</span>
<span class="sd"> index position "0" within the constraint.</span>
<span class="sd"> * ``%(column_0_label)s`` - the label of the :class:`.Column` at</span>
<span class="sd"> index position "0", e.g. :attr:`.Column.label`</span>
<span class="sd"> * ``%(column_0_key)s`` - the key of the :class:`.Column` at</span>
<span class="sd"> index position "0", e.g. :attr:`.Column.key`</span>
<span class="sd"> * ``%(referred_column_0_name)s`` - the name of a :class:`.Column`</span>
<span class="sd"> at index position "0" referenced by a</span>
<span class="sd"> :class:`.ForeignKeyConstraint`.</span>
<span class="sd"> * ``%(constraint_name)s`` - a special key that refers to the</span>
<span class="sd"> existing name given to the constraint. When this key is</span>
<span class="sd"> present, the :class:`.Constraint` object's existing name will be</span>
<span class="sd"> replaced with one that is composed from template string that</span>
<span class="sd"> uses this token. When this token is present, it is required that</span>
<span class="sd"> the :class:`.Constraint` is given an explicit name ahead of time.</span>
<span class="sd"> * user-defined: any additional token may be implemented by passing</span>
<span class="sd"> it along with a ``fn(constraint, table)`` callable to the</span>
<span class="sd"> naming_convention dictionary.</span>
<span class="sd"> .. versionadded:: 0.9.2</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`constraint_naming_conventions` - for detailed usage</span>
<span class="sd"> examples.</span>
<span class="sd"> """</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tables</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">immutabledict</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">quoted_name</span><span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">quote_schema</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">naming_convention</span> <span class="o">=</span> <span class="n">naming_convention</span>
<span class="k">if</span> <span class="n">info</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">info</span> <span class="o">=</span> <span class="n">info</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_sequences</span> <span class="o">=</span> <span class="p">{}</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_fk_memos</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">bind</span> <span class="o">=</span> <span class="n">bind</span>
<span class="k">if</span> <span class="n">reflect</span><span class="p">:</span>
<span class="n">util</span><span class="o">.</span><span class="n">warn_deprecated</span><span class="p">(</span><span class="s2">"reflect=True is deprecate; please "</span>
<span class="s2">"use the reflect() method."</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">bind</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">ArgumentError</span><span class="p">(</span>
<span class="s2">"A bind must be supplied in conjunction "</span>
<span class="s2">"with reflect=True"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">reflect</span><span class="p">()</span>
<span class="n">tables</span> <span class="o">=</span> <span class="kc">None</span>
<span class="sd">"""A dictionary of :class:`.Table` objects keyed to their name or "table key".</span>
<span class="sd"> The exact key is that determined by the :attr:`.Table.key` attribute;</span>
<span class="sd"> for a table with no :attr:`.Table.schema` attribute, this is the same</span>
<span class="sd"> as :attr:`.Table.name`. For a table with a schema, it is typically of the</span>
<span class="sd"> form ``schemaname.tablename``.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :attr:`.MetaData.sorted_tables`</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s1">'MetaData(bind=</span><span class="si">%r</span><span class="s1">)'</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">bind</span>
<span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table_or_key</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">table_or_key</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span><span class="p">):</span>
<span class="n">table_or_key</span> <span class="o">=</span> <span class="n">table_or_key</span><span class="o">.</span><span class="n">key</span>
<span class="k">return</span> <span class="n">table_or_key</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">tables</span>
<span class="k">def</span> <span class="nf">_add_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="nb">dict</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">table</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schema</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">schema</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_remove_table</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">):</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">_get_table_key</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="n">removed</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">removed</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">for</span> <span class="n">fk</span> <span class="ow">in</span> <span class="n">removed</span><span class="o">.</span><span class="n">foreign_keys</span><span class="p">:</span>
<span class="n">fk</span><span class="o">.</span><span class="n">_remove_from_metadata</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span> <span class="o">=</span> <span class="nb">set</span><span class="p">([</span><span class="n">t</span><span class="o">.</span><span class="n">schema</span>
<span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="k">if</span> <span class="n">t</span><span class="o">.</span><span class="n">schema</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">__getstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="p">{</span><span class="s1">'tables'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="p">,</span>
<span class="s1">'schema'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span><span class="p">,</span>
<span class="s1">'schemas'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span><span class="p">,</span>
<span class="s1">'sequences'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_sequences</span><span class="p">,</span>
<span class="s1">'fk_memos'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">_fk_memos</span><span class="p">,</span>
<span class="s1">'naming_convention'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">naming_convention</span>
<span class="p">}</span>
<span class="k">def</span> <span class="nf">__setstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">tables</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'tables'</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">schema</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'schema'</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">naming_convention</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'naming_convention'</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_bind</span> <span class="o">=</span> <span class="kc">None</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_sequences</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'sequences'</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'schemas'</span><span class="p">]</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_fk_memos</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">'fk_memos'</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">is_bound</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""True if this MetaData is bound to an Engine or Connection."""</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_bind</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""An :class:`.Engine` or :class:`.Connection` to which this</span>
<span class="sd"> :class:`.MetaData` is bound.</span>
<span class="sd"> Typically, a :class:`.Engine` is assigned to this attribute</span>
<span class="sd"> so that "implicit execution" may be used, or alternatively</span>
<span class="sd"> as a means of providing engine binding information to an</span>
<span class="sd"> ORM :class:`.Session` object::</span>
<span class="sd"> engine = create_engine("someurl://")</span>
<span class="sd"> metadata.bind = engine</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :ref:`dbengine_implicit` - background on "bound metadata"</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_bind</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">dependencies</span><span class="p">(</span><span class="s2">"sqlalchemy.engine.url"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_bind_to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">bind</span><span class="p">):</span>
<span class="sd">"""Bind this MetaData to an Engine, Connection, string or URL."""</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">bind</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span> <span class="o">+</span> <span class="p">(</span><span class="n">url</span><span class="o">.</span><span class="n">URL</span><span class="p">,</span> <span class="p">)):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_bind</span> <span class="o">=</span> <span class="n">sqlalchemy</span><span class="o">.</span><span class="n">create_engine</span><span class="p">(</span><span class="n">bind</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_bind</span> <span class="o">=</span> <span class="n">bind</span>
<span class="n">bind</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">bind</span><span class="p">,</span> <span class="n">_bind_to</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">clear</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Clear all Table objects from this MetaData."""</span>
<span class="nb">dict</span><span class="o">.</span><span class="n">clear</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_schemas</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_fk_memos</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">remove</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span>
<span class="sd">"""Remove the given Table object from this MetaData."""</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_remove_table</span><span class="p">(</span><span class="n">table</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">table</span><span class="o">.</span><span class="n">schema</span><span class="p">)</span>
<span class="nd">@property</span>
<span class="k">def</span> <span class="nf">sorted_tables</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Returns a list of :class:`.Table` objects sorted in order of</span>
<span class="sd"> foreign key dependency.</span>
<span class="sd"> The sorting will place :class:`.Table` objects that have dependencies</span>
<span class="sd"> first, before the dependencies themselves, representing the</span>
<span class="sd"> order in which they can be created. To get the order in which</span>
<span class="sd"> the tables would be dropped, use the ``reversed()`` Python built-in.</span>
<span class="sd"> .. warning::</span>
<span class="sd"> The :attr:`.sorted_tables` accessor cannot by itself accommodate</span>
<span class="sd"> automatic resolution of dependency cycles between tables, which</span>
<span class="sd"> are usually caused by mutually dependent foreign key constraints.</span>
<span class="sd"> To resolve these cycles, either the</span>
<span class="sd"> :paramref:`.ForeignKeyConstraint.use_alter` parameter may be appled</span>
<span class="sd"> to those constraints, or use the</span>
<span class="sd"> :func:`.schema.sort_tables_and_constraints` function which will break</span>
<span class="sd"> out foreign key constraints involved in cycles separately.</span>
<span class="sd"> .. seealso::</span>
<span class="sd"> :func:`.schema.sort_tables`</span>
<span class="sd"> :func:`.schema.sort_tables_and_constraints`</span>
<span class="sd"> :attr:`.MetaData.tables`</span>
<span class="sd"> :meth:`.Inspector.get_table_names`</span>
<span class="sd"> :meth:`.Inspector.get_sorted_table_and_fkc_names`</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">ddl</span><span class="o">.</span><span class="n">sort_tables</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="o">.</span><span class="n">values</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">key</span><span class="p">))</span>
<span class="k">def</span> <span class="nf">reflect</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">schema</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">views</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">only</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">extend_existing</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
<span class="n">autoload_replace</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="o">**</span><span class="n">dialect_kwargs</span><span class="p">):</span>
<span class="sa">r</span><span class="sd">"""Load all available table definitions from the database.</span>
<span class="sd"> Automatically creates ``Table`` entries in this ``MetaData`` for any</span>
<span class="sd"> table available in the database but not yet present in the</span>
<span class="sd"> ``MetaData``. May be called multiple times to pick up tables recently</span>
<span class="sd"> added to the database, however no special action is taken if a table</span>
<span class="sd"> in this ``MetaData`` no longer exists in the database.</span>
<span class="sd"> :param bind:</span>
<span class="sd"> A :class:`.Connectable` used to access the database; if None, uses</span>
<span class="sd"> the existing bind on this ``MetaData``, if any.</span>
<span class="sd"> :param schema:</span>
<span class="sd"> Optional, query and reflect tables from an alterate schema.</span>
<span class="sd"> If None, the schema associated with this :class:`.MetaData`</span>
<span class="sd"> is used, if any.</span>
<span class="sd"> :param views:</span>
<span class="sd"> If True, also reflect views.</span>
<span class="sd"> :param only:</span>
<span class="sd"> Optional. Load only a sub-set of available named tables. May be</span>
<span class="sd"> specified as a sequence of names or a callable.</span>
<span class="sd"> If a sequence of names is provided, only those tables will be</span>
<span class="sd"> reflected. An error is raised if a table is requested but not</span>
<span class="sd"> available. Named tables already present in this ``MetaData`` are</span>
<span class="sd"> ignored.</span>
<span class="sd"> If a callable is provided, it will be used as a boolean predicate to</span>
<span class="sd"> filter the list of potential table names. The callable is called</span>
<span class="sd"> with a table name and this ``MetaData`` instance as positional</span>
<span class="sd"> arguments and should return a true value for any table to reflect.</span>
<span class="sd"> :param extend_existing: Passed along to each :class:`.Table` as</span>
<span class="sd"> :paramref:`.Table.extend_existing`.</span>
<span class="sd"> .. versionadded:: 0.9.1</span>
<span class="sd"> :param autoload_replace: Passed along to each :class:`.Table` as</span>
<span class="sd"> :paramref:`.Table.autoload_replace`.</span>
<span class="sd"> .. versionadded:: 0.9.1</span>
<span class="sd"> :param \**dialect_kwargs: Additional keyword arguments not mentioned</span>
<span class="sd"> above are dialect specific, and passed in the form</span>
<span class="sd"> ``<dialectname>_<argname>``. See the documentation regarding an</span>
<span class="sd"> individual dialect at :ref:`dialect_toplevel` for detail on</span>
<span class="sd"> documented arguments.</span>
<span class="sd"> .. versionadded:: 0.9.2 - Added</span>
<span class="sd"> :paramref:`.MetaData.reflect.**dialect_kwargs` to support</span>
<span class="sd"> dialect-level reflection options for all :class:`.Table`</span>
<span class="sd"> objects reflected.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="k">with</span> <span class="n">bind</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span> <span class="k">as</span> <span class="n">conn</span><span class="p">:</span>
<span class="n">reflect_opts</span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'autoload'</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
<span class="s1">'autoload_with'</span><span class="p">:</span> <span class="n">conn</span><span class="p">,</span>
<span class="s1">'extend_existing'</span><span class="p">:</span> <span class="n">extend_existing</span><span class="p">,</span>
<span class="s1">'autoload_replace'</span><span class="p">:</span> <span class="n">autoload_replace</span><span class="p">,</span>
<span class="s1">'_extend_on'</span><span class="p">:</span> <span class="nb">set</span><span class="p">()</span>
<span class="p">}</span>
<span class="n">reflect_opts</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">dialect_kwargs</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">schema</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">schema</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">reflect_opts</span><span class="p">[</span><span class="s1">'schema'</span><span class="p">]</span> <span class="o">=</span> <span class="n">schema</span>
<span class="n">available</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">OrderedSet</span><span class="p">(</span>
<span class="n">bind</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">table_names</span><span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">connection</span><span class="o">=</span><span class="n">conn</span><span class="p">))</span>
<span class="k">if</span> <span class="n">views</span><span class="p">:</span>
<span class="n">available</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
<span class="n">bind</span><span class="o">.</span><span class="n">dialect</span><span class="o">.</span><span class="n">get_view_names</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> <span class="n">schema</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">if</span> <span class="n">schema</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">available_w_schema</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">OrderedSet</span><span class="p">([</span><span class="s2">"</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">schema</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">available</span><span class="p">])</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">available_w_schema</span> <span class="o">=</span> <span class="n">available</span>
<span class="n">current</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tables</span><span class="p">)</span>
<span class="k">if</span> <span class="n">only</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">load</span> <span class="o">=</span> <span class="p">[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">schname</span> <span class="ow">in</span>
<span class="nb">zip</span><span class="p">(</span><span class="n">available</span><span class="p">,</span> <span class="n">available_w_schema</span><span class="p">)</span>
<span class="k">if</span> <span class="n">extend_existing</span> <span class="ow">or</span> <span class="n">schname</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">current</span><span class="p">]</span>
<span class="k">elif</span> <span class="n">util</span><span class="o">.</span><span class="n">callable</span><span class="p">(</span><span class="n">only</span><span class="p">):</span>
<span class="n">load</span> <span class="o">=</span> <span class="p">[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">schname</span> <span class="ow">in</span>
<span class="nb">zip</span><span class="p">(</span><span class="n">available</span><span class="p">,</span> <span class="n">available_w_schema</span><span class="p">)</span>
<span class="k">if</span> <span class="p">(</span><span class="n">extend_existing</span> <span class="ow">or</span> <span class="n">schname</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">current</span><span class="p">)</span>
<span class="ow">and</span> <span class="n">only</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">)]</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">missing</span> <span class="o">=</span> <span class="p">[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">only</span> <span class="k">if</span> <span class="n">name</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">available</span><span class="p">]</span>
<span class="k">if</span> <span class="n">missing</span><span class="p">:</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">schema</span> <span class="ow">and</span> <span class="p">(</span><span class="s2">" schema '</span><span class="si">%s</span><span class="s2">'"</span> <span class="o">%</span> <span class="n">schema</span><span class="p">)</span> <span class="ow">or</span> <span class="s1">''</span>
<span class="k">raise</span> <span class="n">exc</span><span class="o">.</span><span class="n">InvalidRequestError</span><span class="p">(</span>
<span class="s1">'Could not reflect: requested table(s) not available '</span>
<span class="s1">'in </span><span class="si">%r%s</span><span class="s1">: (</span><span class="si">%s</span><span class="s1">)'</span> <span class="o">%</span>
<span class="p">(</span><span class="n">bind</span><span class="o">.</span><span class="n">engine</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="s1">', '</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">missing</span><span class="p">)))</span>
<span class="n">load</span> <span class="o">=</span> <span class="p">[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">only</span> <span class="k">if</span> <span class="n">extend_existing</span> <span class="ow">or</span>
<span class="n">name</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">current</span><span class="p">]</span>
<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">load</span><span class="p">:</span>
<span class="n">Table</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">reflect_opts</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">append_ddl_listener</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">event_name</span><span class="p">,</span> <span class="n">listener</span><span class="p">):</span>
<span class="sd">"""Append a DDL event listener to this ``MetaData``.</span>
<span class="sd"> .. deprecated:: 0.7</span>
<span class="sd"> See :class:`.DDLEvents`.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">adapt_listener</span><span class="p">(</span><span class="n">target</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="n">tables</span> <span class="o">=</span> <span class="n">kw</span><span class="p">[</span><span class="s1">'tables'</span><span class="p">]</span>
<span class="n">listener</span><span class="p">(</span><span class="n">event</span><span class="p">,</span> <span class="n">target</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">tables</span><span class="o">=</span><span class="n">tables</span><span class="p">)</span>
<span class="n">event</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s2">""</span> <span class="o">+</span> <span class="n">event_name</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">'-'</span><span class="p">,</span> <span class="s1">'_'</span><span class="p">),</span> <span class="n">adapt_listener</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">create_all</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">tables</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="sd">"""Create all tables stored in this metadata.</span>
<span class="sd"> Conditional by default, will not attempt to recreate tables already</span>
<span class="sd"> present in the target database.</span>
<span class="sd"> :param bind:</span>
<span class="sd"> A :class:`.Connectable` used to access the</span>
<span class="sd"> database; if None, uses the existing bind on this ``MetaData``, if</span>
<span class="sd"> any.</span>
<span class="sd"> :param tables:</span>
<span class="sd"> Optional list of ``Table`` objects, which is a subset of the total</span>
<span class="sd"> tables in the ``MetaData`` (others are ignored).</span>
<span class="sd"> :param checkfirst:</span>
<span class="sd"> Defaults to True, don't issue CREATEs for tables already present</span>
<span class="sd"> in the target database.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaGenerator</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">,</span>
<span class="n">tables</span><span class="o">=</span><span class="n">tables</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">drop_all</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bind</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">tables</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">checkfirst</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="sd">"""Drop all tables stored in this metadata.</span>
<span class="sd"> Conditional by default, will not attempt to drop tables not present in</span>
<span class="sd"> the target database.</span>
<span class="sd"> :param bind:</span>
<span class="sd"> A :class:`.Connectable` used to access the</span>
<span class="sd"> database; if None, uses the existing bind on this ``MetaData``, if</span>
<span class="sd"> any.</span>
<span class="sd"> :param tables:</span>
<span class="sd"> Optional list of ``Table`` objects, which is a subset of the</span>
<span class="sd"> total tables in the ``MetaData`` (others are ignored).</span>
<span class="sd"> :param checkfirst:</span>
<span class="sd"> Defaults to True, only issue DROPs for tables confirmed to be</span>
<span class="sd"> present in the target database.</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">bind</span> <span class="o">=</span> <span class="n">_bind_or_error</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="n">bind</span><span class="o">.</span><span class="n">_run_visitor</span><span class="p">(</span><span class="n">ddl</span><span class="o">.</span><span class="n">SchemaDropper</span><span class="p">,</span>
<span class="bp">self</span><span class="p">,</span>
<span class="n">checkfirst</span><span class="o">=</span><span class="n">checkfirst</span><span class="p">,</span>
<span class="n">tables</span><span class="o">=</span><span class="n">tables</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ThreadLocalMetaData</span><span class="p">(</span><span class="n">MetaData</span><span class="p">):</span>
<span class="sd">"""A MetaData variant that presents a different ``bind`` in every thread.</span>
<span class="sd"> Makes the ``bind`` property of the MetaData a thread-local value, allowing</span>
<span class="sd"> this collection of tables to be bound to different ``Engine``</span>
<span class="sd"> implementations or connections in each thread.</span>
<span class="sd"> The ThreadLocalMetaData starts off bound to None in each thread. Binds</span>
<span class="sd"> must be made explicitly by assigning to the ``bind`` property or using</span>
<span class="sd"> ``connect()``. You can also re-bind dynamically multiple times per</span>
<span class="sd"> thread, just like a regular ``MetaData``.</span>
<span class="sd"> """</span>
<span class="n">__visit_name__</span> <span class="o">=</span> <span class="s1">'metadata'</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Construct a ThreadLocalMetaData."""</span>
<span class="bp">self</span><span class="o">.</span><span class="n">context</span> <span class="o">=</span> <span class="n">util</span><span class="o">.</span><span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">__engines</span> <span class="o">=</span> <span class="p">{}</span>
<span class="nb">super</span><span class="p">(</span><span class="n">ThreadLocalMetaData</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""The bound Engine or Connection for this thread.</span>
<span class="sd"> This property may be assigned an Engine or Connection, or assigned a</span>
<span class="sd"> string or URL to automatically create a basic Engine for this bind</span>
<span class="sd"> with ``create_engine()``."""</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="p">,</span> <span class="s1">'_engine'</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="nd">@util</span><span class="o">.</span><span class="n">dependencies</span><span class="p">(</span><span class="s2">"sqlalchemy.engine.url"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">_bind_to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">bind</span><span class="p">):</span>
<span class="sd">"""Bind to a Connectable in the caller's thread."""</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">bind</span><span class="p">,</span> <span class="n">util</span><span class="o">.</span><span class="n">string_types</span> <span class="o">+</span> <span class="p">(</span><span class="n">url</span><span class="o">.</span><span class="n">URL</span><span class="p">,</span> <span class="p">)):</span>
<span class="k">try</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="o">.</span><span class="n">_engine</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__engines</span><span class="p">[</span><span class="n">bind</span><span class="p">]</span>
<span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">sqlalchemy</span><span class="o">.</span><span class="n">create_engine</span><span class="p">(</span><span class="n">bind</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">__engines</span><span class="p">[</span><span class="n">bind</span><span class="p">]</span> <span class="o">=</span> <span class="n">e</span>
<span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="o">.</span><span class="n">_engine</span> <span class="o">=</span> <span class="n">e</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># TODO: this is squirrely. we shouldn't have to hold onto engines</span>
<span class="c1"># in a case like this</span>
<span class="k">if</span> <span class="n">bind</span> <span class="ow">not</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">__engines</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">__engines</span><span class="p">[</span><span class="n">bind</span><span class="p">]</span> <span class="o">=</span> <span class="n">bind</span>
<span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="o">.</span><span class="n">_engine</span> <span class="o">=</span> <span class="n">bind</span>
<span class="n">bind</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">bind</span><span class="p">,</span> <span class="n">_bind_to</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">is_bound</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""True if there is a bind for this thread."""</span>
<span class="k">return</span> <span class="p">(</span><span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="p">,</span> <span class="s1">'_engine'</span><span class="p">)</span> <span class="ow">and</span>
<span class="bp">self</span><span class="o">.</span><span class="n">context</span><span class="o">.</span><span class="n">_engine</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">dispose</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="sd">"""Dispose all bound engines, in all thread contexts."""</span>
<span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">__engines</span><span class="o">.</span><span class="n">values</span><span class="p">():</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="s1">'dispose'</span><span class="p">):</span>
<span class="n">e</span><span class="o">.</span><span class="n">dispose</span><span class="p">()</span>
<span class="k">class</span> <span class="nc">_SchemaTranslateMap</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="sd">"""Provide translation of schema names based on a mapping.</span>
<span class="sd"> Also provides helpers for producing cache keys and optimized</span>
<span class="sd"> access when no mapping is present.</span>
<span class="sd"> Used by the :paramref:`.Connection.execution_options.schema_translate_map`</span>
<span class="sd"> feature.</span>
<span class="sd"> .. versionadded:: 1.1</span>
<span class="sd"> """</span>
<span class="vm">__slots__</span> <span class="o">=</span> <span class="s1">'map_'</span><span class="p">,</span> <span class="s1">'__call__'</span><span class="p">,</span> <span class="s1">'hash_key'</span><span class="p">,</span> <span class="s1">'is_default'</span>
<span class="n">_default_schema_getter</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">attrgetter</span><span class="p">(</span><span class="s2">"schema"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">map_</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">map_</span> <span class="o">=</span> <span class="n">map_</span>
<span class="k">if</span> <span class="n">map_</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">schema_for_object</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
<span class="n">effective_schema</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_default_schema_getter</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
<span class="n">effective_schema</span> <span class="o">=</span> <span class="n">obj</span><span class="o">.</span><span class="n">_translate_schema</span><span class="p">(</span>
<span class="n">effective_schema</span><span class="p">,</span> <span class="n">map_</span><span class="p">)</span>
<span class="k">return</span> <span class="n">effective_schema</span>
<span class="bp">self</span><span class="o">.</span><span class="fm">__call__</span> <span class="o">=</span> <span class="n">schema_for_object</span>
<span class="bp">self</span><span class="o">.</span><span class="n">hash_key</span> <span class="o">=</span> <span class="s2">";"</span><span class="o">.</span><span class="n">join</span><span class="p">(</span>
<span class="s2">"</span><span class="si">%s</span><span class="s2">=</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">map_</span><span class="p">[</span><span class="n">k</span><span class="p">])</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">map_</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="p">)</span>
<span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">is_default</span> <span class="o">=</span> <span class="kc">False</span>
<span class="k">else</span><span class="p">:</span>
<span class="bp">self</span><span class="o">.</span><span class="n">hash_key</span> <span class="o">=</span> <span class="mi">0</span>
<span class="bp">self</span><span class="o">.</span><span class="fm">__call__</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_default_schema_getter</span>
<span class="bp">self</span><span class="o">.</span><span class="n">is_default</span> <span class="o">=</span> <span class="kc">True</span>
<span class="nd">@classmethod</span>
<span class="k">def</span> <span class="nf">_schema_getter</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">map_</span><span class="p">):</span>
<span class="k">if</span> <span class="n">map_</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="n">_default_schema_map</span>
<span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">map_</span><span class="p">,</span> <span class="n">_SchemaTranslateMap</span><span class="p">):</span>
<span class="k">return</span> <span class="n">map_</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">_SchemaTranslateMap</span><span class="p">(</span><span class="n">map_</span><span class="p">)</span>
<span class="n">_default_schema_map</span> <span class="o">=</span> <span class="n">_SchemaTranslateMap</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
<span class="n">_schema_getter</span> <span class="o">=</span> <span class="n">_SchemaTranslateMap</span><span class="o">.</span><span class="n">_schema_getter</span>
</pre></div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, A. Dorsk.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../../../',
VERSION:'0.0.1',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../../../_static/jquery.js"></script>
<script type="text/javascript" src="../../../_static/underscore.js"></script>
<script type="text/javascript" src="../../../_static/doctools.js"></script>
<script type="text/javascript" src="../../../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | 105.378675 | 652 | 0.612304 |
dd93512509961a31263a6be09651623db8db1dd5 | 364 | php | PHP | perfex_crm/application/views/themes/perfex/views/terms_and_conditions.php | gerekper/perfect | 280172ccfe0894b0bdfbe866529668d4c12e93f1 | [
"Unlicense"
] | null | null | null | perfex_crm/application/views/themes/perfex/views/terms_and_conditions.php | gerekper/perfect | 280172ccfe0894b0bdfbe866529668d4c12e93f1 | [
"Unlicense"
] | null | null | null | perfex_crm/application/views/themes/perfex/views/terms_and_conditions.php | gerekper/perfect | 280172ccfe0894b0bdfbe866529668d4c12e93f1 | [
"Unlicense"
] | null | null | null | <?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<div class="panel_s">
<div class="panel-body">
<h4 class="terms-and-conditions-heading"><?php echo _l('terms_and_conditions'); ?></h4>
<hr />
<div class="tc-content terms-and-conditions-content">
<?php echo $terms; ?>
</div>
</div>
</div>
| 33.090909 | 95 | 0.57967 |