blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8f5ab9c2968ebebea5d7bee44efc0cd8b2654b26
|
41a20700b5bb351d20562ac23ec4db06bc96f0d7
|
/src/plum/types/property/submodule.py
|
c7fde187b7be2313d64acbade9f0a3bc5e711ba6
|
[] |
no_license
|
kedz/noiseylg
|
ee0c54634767e8d3789b4ffb93727988c29c6979
|
17266e1a41e33aecb95dc1c3aca68f6bccee86d5
|
refs/heads/master
| 2020-07-30T11:22:08.351759
| 2019-10-30T21:33:11
| 2019-10-30T21:33:11
| 210,212,253
| 4
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,702
|
py
|
from .plum_property import PlumProperty
import torch.nn as nn
class Submodule(PlumProperty):
def __init__(self, default=None, required=True, type=None, tags=None):
self._default = default
self._required = required
if type is None:
def any_type(x):
return True
self._type = any_type
elif hasattr(type, "__call__"):
self._type = type
else:
raise ValueError("type must be None or implement __call__")
if isinstance(tags, str):
self._tags = tuple([tags])
elif isinstance(tags, (list, tuple)):
self._tags = tuple(tags)
elif tags is None:
self._tags = tuple()
else:
raise ValueError(
"tags must be None, a str, or a list/tuple of str")
@property
def default(self):
return self._default
@property
def required(self):
return self._required
@property
def type(self):
return self._type
@property
def tags(self):
return self._tags
def new(self, owner_module, submodule):
if submodule is None:
submodule = self.default
if submodule is None:
if not self.required:
return None
else:
raise Exception("Missing submodule for {}".format(
str(owner_module.__class__)))
elif isinstance(submodule, (list, tuple)):
for subsubmod in submodule:
if not self.type(subsubmod) or \
not issubclass(subsubmod.__class__, nn.Module):
raise ValueError("Bad type: {}".format(type(subsubmod)))
return nn.ModuleList(submodule)
elif isinstance(submodule, dict):
for subsubmod in submodule.values():
if not self.type(subsubmod) or \
not issubclass(subsubmod.__class__, nn.Module):
raise ValueError("Bad type: {}".format(type(subsubmod)))
return nn.ModuleDict(submodule)
else:
if not issubclass(submodule.__class__, nn.Module):
raise ValueError("Bad type: {}".format(type(submodule)))
return submodule
def __get__(self, owner_module, owner_type=None):
return owner_module._modules[owner_module._submodule_names[self]]
@classmethod
def iter_named_submodules(cls, plum_module):
return cls.iter_named_plum_property(plum_module, prop_type=cls)
@classmethod
def iter_submodules(cls, plum_module):
return cls.iter_plum_property(plum_module, prop_type=cls)
|
[
"kedzie@cs.columbia.edu"
] |
kedzie@cs.columbia.edu
|
9197ed24cac4246e593e240d233fa8bef16cedc0
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_fatherlands.py
|
8ba1a35575d89333db2a00481b5443ff629ef5a3
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 238
|
py
|
#calss header
class _FATHERLANDS():
def __init__(self,):
self.name = "FATHERLANDS"
self.definitions = fatherland
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['fatherland']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
db9fe5e9cb4bda725fe01b0c4fe09c6fa1902e6a
|
1e2b69476b2b174ac210ba525b197c621280a390
|
/Configuration/Geometry/python/GeometryExtended2017Plan1_cff.py
|
6ed28868e6981ebbfff879df8fd786e61a845e77
|
[
"Apache-2.0"
] |
permissive
|
skinnari/cmssw
|
640e5fe2f23a423ccb7afe82d43ea1b80a2603f0
|
62b49319e475fbcf14484d77814d47a552c61f63
|
refs/heads/L1TK_CMSSW_11-1-0-pre4
| 2022-10-27T03:55:33.402157
| 2020-03-24T14:18:04
| 2020-03-24T14:18:04
| 11,660,178
| 2
| 3
|
Apache-2.0
| 2020-03-24T14:16:54
| 2013-07-25T12:44:13
|
C++
|
UTF-8
|
Python
| false
| false
| 397
|
py
|
import FWCore.ParameterSet.Config as cms
#
# Geometry master configuration
#
# Ideal geometry, needed for simulation
from Geometry.CMSCommonData.cmsExtendedGeometry2017Plan1XML_cfi import *
from Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi import *
from Geometry.EcalCommonData.ecalSimulationParameters_cff import *
from Geometry.HcalCommonData.hcalDDDSimConstants_cff import *
|
[
"sunanda.banerjee@cern.ch"
] |
sunanda.banerjee@cern.ch
|
392a88d06ae3d8ebc39cc6872208fe79a63c7d0d
|
0ed9a8eef1d12587d596ec53842540063b58a7ec
|
/cloudrail/knowledge/context/aws/resources_builders/scanner/resources_tagging_list_builder.py
|
5cb9815c2ef85ff46f3f0573716faf4abef4a865
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
cbc506/cloudrail-knowledge
|
8611faa10a3bf195f277b81622e2590dbcc60da4
|
7b5c9030575f512b9c230eed1a93f568d8663708
|
refs/heads/main
| 2023-08-02T08:36:22.051695
| 2021-09-13T15:23:33
| 2021-09-13T15:24:26
| 390,127,361
| 0
| 0
|
MIT
| 2021-07-27T21:08:06
| 2021-07-27T21:08:06
| null |
UTF-8
|
Python
| false
| false
| 588
|
py
|
from cloudrail.knowledge.context.aws.resources_builders.scanner.base_aws_scanner_builder import BaseAwsScannerBuilder
from cloudrail.knowledge.context.aws.resources_builders.scanner.cloud_mapper_component_builder import build_resources_tagging_list
class ResourceTagMappingListBuilder(BaseAwsScannerBuilder):
def get_file_name(self) -> str:
return 'resourcegroupstaggingapi-get-resources.json'
def get_section_name(self) -> str:
return 'ResourceTagMappingList'
def do_build(self, attributes: dict):
return build_resources_tagging_list(attributes)
|
[
"ori.bar.emet@gmail.com"
] |
ori.bar.emet@gmail.com
|
9695f7ae9065259aa8878bac3d67707a89736479
|
5da5473ff3026165a47f98744bac82903cf008e0
|
/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/types/job_state.py
|
9980364dd9433a2eb7720c4ca26313554eb86dfa
|
[
"Apache-2.0"
] |
permissive
|
googleapis/google-cloud-python
|
ed61a5f03a476ab6053870f4da7bc5534e25558b
|
93c4e63408c65129422f65217325f4e7d41f7edf
|
refs/heads/main
| 2023-09-04T09:09:07.852632
| 2023-08-31T22:49:26
| 2023-08-31T22:49:26
| 16,316,451
| 2,792
| 917
|
Apache-2.0
| 2023-09-14T21:45:18
| 2014-01-28T15:51:47
|
Python
|
UTF-8
|
Python
| false
| false
| 2,203
|
py
|
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# 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.
#
from __future__ import annotations
from typing import MutableMapping, MutableSequence
import proto # type: ignore
__protobuf__ = proto.module(
package="google.cloud.enterpriseknowledgegraph.v1",
manifest={
"JobState",
},
)
class JobState(proto.Enum):
r"""Describes the state of a job.
Values:
JOB_STATE_UNSPECIFIED (0):
The job state is unspecified.
JOB_STATE_PENDING (9):
The service is preparing to run the job.
JOB_STATE_RUNNING (1):
The job is in progress.
JOB_STATE_SUCCEEDED (2):
The job completed successfully.
JOB_STATE_FAILED (3):
The job failed.
JOB_STATE_CANCELLED (4):
The job has been cancelled.
JOB_STATE_KNOWLEDGE_EXTRACTION (5):
Entity Recon API: The knowledge extraction
job is running.
JOB_STATE_RECON_PREPROCESSING (6):
Entity Recon API: The preprocessing job is
running.
JOB_STATE_CLUSTERING (7):
Entity Recon API: The clustering job is
running.
JOB_STATE_EXPORTING_CLUSTERS (8):
Entity Recon API: The exporting clusters job
is running.
"""
JOB_STATE_UNSPECIFIED = 0
JOB_STATE_PENDING = 9
JOB_STATE_RUNNING = 1
JOB_STATE_SUCCEEDED = 2
JOB_STATE_FAILED = 3
JOB_STATE_CANCELLED = 4
JOB_STATE_KNOWLEDGE_EXTRACTION = 5
JOB_STATE_RECON_PREPROCESSING = 6
JOB_STATE_CLUSTERING = 7
JOB_STATE_EXPORTING_CLUSTERS = 8
__all__ = tuple(sorted(__protobuf__.manifest))
|
[
"noreply@github.com"
] |
googleapis.noreply@github.com
|
9ec0e0a5d45e3039214a48188142d86b1534571a
|
f2658c4bd7f833ace25ac2b63e88317b05f4602d
|
/2017 July/2017-July-11/st_rdf_test/model/WaysNavigableLinkTimezone.py
|
ec567c431d1b3d80de464f2214bce132f5730431
|
[] |
no_license
|
xiaochao00/telanav_diary
|
e4c34ac0a14b65e4930e32012cc2202ff4ed91e2
|
3c583695e2880322483f526c98217c04286af9b2
|
refs/heads/master
| 2022-01-06T19:42:55.504845
| 2019-05-17T03:11:46
| 2019-05-17T03:11:46
| 108,958,763
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,753
|
py
|
#-------------------------------------------------------------------------------
# Name: WaysNavigableLinkTimezone model
# Purpose: this model is used to mapping the rdf_nav_link, rdf_link and rdf_access
# columns: [ ]
#
# Author: rex
#
# Created: 2016-01-29
# Copyright: (c) rex 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
from record import Record
from constants import *
import os
import sys
import datetime
import json
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),"..")
GLOBAL_KEY_PREFIX = "ways_navlink_"
CSV_SEP = '`'
LF = '\n'
#(key, category, function)
STATISTIC_KEYS = (
("timezone:left",False,"timezone_left"),
("timezone:right", False, "timezone_right")
)
class WaysNavigableLinkTimezone(Record):
def __init__(self, region):
Record.__init__(self)
self.dump_file = os.path.join(ROOT_DIR, "temporary", self.__class__.__name__)
self.stat = {}
self.region = region
def dump2file(self):
cmd = "SELECT \
rnl.link_id, \
rl.left_admin_place_id, \
rl.right_admin_place_id \
FROM \
public.rdf_nav_link as rnl left join public.rdf_link as rl on rnl.link_id=rl.link_id \
WHERE rnl.iso_country_code in (%s)"%(REGION_COUNTRY_CODES(self.region, GLOBAL_KEY_PREFIX))
print cmd
self.cursor.copy_expert("COPY (%s) TO STDOUT DELIMITER '`'"%(cmd),open(self.dump_file,"w"))
def get_statistic(self):
try:
self.dump2file()
self.__build_admins()
except:
print "Some table or schema don't exist! Please check the upper sql"
print "Unexpected error:[ %s.py->%s] %s"%(self.__class__.__name__, 'get_statistic', str(sys.exc_info()))
return {}
processcount = 0
with open(self.dump_file, "r",1024*1024*1024) as csv_f:
for line in csv_f:
line = line.rstrip()
line_p = line.split(CSV_SEP)
if len(line_p) < 1:
continue
self.__statistic(line_p)
processcount += 1
if processcount%5000 == 0:
print "\rProcess index [ "+str(processcount)+" ]",
print "\rProcess index [ "+str(processcount)+" ]",
# write to file
with open(os.path.join(ROOT_DIR, "output", "stat", self.__class__.__name__), 'w') as stf:
stf.write(json.dumps(self.stat))
return self.stat
def __build_admins(self):
processcount = 0
admins = {}
with open(self.__dump_adminplaceid(), "r",1024*1024*1024) as csv_f:
for line in csv_f:
line = line.rstrip()
line_p = line.split(CSV_SEP)
if len(line_p) < 1:
continue
if line_p[0] in admins:
continue
admins[line_p[0]] = line_p[1:]
processcount += 1
if processcount%5000 == 0:
print "\rProcess index [ "+str(processcount)+" ]",
print "\rProcess index [ "+str(processcount)+" ]",
print "build admin time zone hierarchy"
for api in admins:
#check order8
admins[api][1] = (admins.get(api)[1] in admins and '\N' != admins.get(admins.get(api)[1])[0]) and 1 or 0
#check order2
admins[api][2] = (admins.get(api)[2] in admins and '\N' != admins.get(admins.get(api)[2])[0]) and 1 or 0
#check order1
admins[api][3] = (admins.get(api)[3] in admins and '\N' != admins.get(admins.get(api)[3])[0]) and 1 or 0
#check country
admins[api][4] = (admins.get(api)[4] in admins and '\N' != admins.get(admins.get(api)[4])[0]) and 1 or 0
self.admins = admins
def __dump_adminplaceid(self):
cmd = "SELECT \
rap.admin_place_id, \
rap.time_zone, \
rah.order8_id, \
rah.order2_id, \
rah.order1_id, \
rah.country_id \
FROM \
public.rdf_admin_place AS rap, public.rdf_admin_hierarchy AS rah \
WHERE rap.admin_place_id=rah.admin_place_id and rah.iso_country_code IN (%s)"%(REGION_COUNTRY_CODES(self.region, GLOBAL_KEY_PREFIX))
print cmd
f = "%s_admins"%(self.dump_file)
self.cursor.copy_expert("COPY (%s) TO STDOUT DELIMITER '`'"%(cmd),open(f,"w"))
return f
def __statistic(self,line):
for keys in STATISTIC_KEYS:
try:
getattr(self,'_%s__get_%s'%(self.__class__.__name__,keys[2]))(keys,line)
except:
print "The statistic [ %s ] didn't exist"%(keys[2])
print "Unexpected error:[ %s.py->%s] %s"%(self.__class__.__name__, '__statistic', str(sys.exc_info()))
def __count(self,key):
if self.stat.has_key(key):
self.stat[key] += 1
else:
self.stat[key] = 1
# all statistic method
def __get_timezone_left(self,keys,line):
if '\N' != line[1] and reduce(lambda px,py:px+py,self.admins.get(line[1])[1:]) > 0:
self.__count("%s%s"%(GLOBAL_KEY_PREFIX,keys[0]))
def __get_timezone_right(self,keys,line):
if '\N' != line[2] and reduce(lambda px,py:px+py,self.admins.get(line[2])[1:]) > 0:
self.__count("%s%s"%(GLOBAL_KEY_PREFIX,keys[0]))
if __name__ == "__main__":
# use to test this model
bg = datetime.datetime.now()
navlink_stat = WaysNavigableLinkTimezone('na').get_statistic()
keys = navlink_stat.keys()
print "==>"
print "{%s}"%(",".join(map(lambda px: "\"%s\":%s"%(px,navlink_stat[px]) ,keys)))
print "<=="
ed = datetime.datetime.now()
print "Cost time:"+str(ed - bg)
|
[
"1363180272@qq.com"
] |
1363180272@qq.com
|
1876baded258b0f238e61b62902741d2f5805194
|
8b59108f621e94935b3b72aae3c441e10cb64a1c
|
/toggle_lods.py
|
a076d80ac06be061fdc6e2b1799d90097d95d484
|
[] |
no_license
|
CyberSys/CE_Python
|
97a373b1fe2d214ae854d454dc5e7d79bc150d8e
|
721ac005e215f1225fb3c99491b55dc48b19ab30
|
refs/heads/master
| 2022-01-13T08:04:08.558594
| 2019-07-22T17:05:46
| 2019-07-22T17:05:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 153
|
py
|
cvar = general.get_cvar('e_DebugDraw')
if cvar != 22:
general.set_cvar('e_DebugDraw', 22)
if cvar == '22':
general.set_cvar('e_DebugDraw', 0)
|
[
"chrissprance@gmail.com"
] |
chrissprance@gmail.com
|
93f1260fdf0cb8d633f4967c78c99ea23c315318
|
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
|
/good_point_and_great_person/place.py
|
b3c68823b8fc17e94d73df2acd0901fd60e6be4e
|
[] |
no_license
|
JingkaiTang/github-play
|
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
|
51b550425a91a97480714fe9bc63cb5112f6f729
|
refs/heads/master
| 2021-01-20T20:18:21.249162
| 2016-08-19T07:20:12
| 2016-08-19T07:20:12
| 60,834,519
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 213
|
py
|
#! /usr/bin/env python
def person(str_arg):
get_great_case(str_arg)
print('young_hand_or_first_life')
def get_great_case(str_arg):
print(str_arg)
if __name__ == '__main__':
person('good_week')
|
[
"jingkaitang@gmail.com"
] |
jingkaitang@gmail.com
|
587cd786cb7e5627440b322af69c2291af3c666d
|
eb54a89743222bc7d72cf7530e745b8986cad441
|
/leetcode/canFormArray.py
|
39cc9feeb2c341db226cbd358f4dd9e799cad443
|
[] |
no_license
|
ugaemi/algorithm
|
db341809e2497b36e82fc09939ae8e3f1ca7d880
|
e4f57f01d21f822eb8da5ba5bfc04c29b9ddce78
|
refs/heads/master
| 2023-01-10T05:16:55.167675
| 2023-01-04T13:12:20
| 2023-01-04T13:12:20
| 200,671,606
| 3
| 10
| null | 2022-02-27T12:52:31
| 2019-08-05T14:28:56
|
Python
|
UTF-8
|
Python
| false
| false
| 954
|
py
|
import unittest
class Solution:
def canFormArray(self, arr, pieces):
for piece in pieces:
if len(piece) > 1:
result = any(piece == arr[i:i+len(piece)] for i in range(len(arr) - 1))
if not result:
return result
else:
if piece[0] not in arr:
return False
return True
class Test(unittest.TestCase):
def test_canFormArray(self):
solution = Solution()
self.assertEqual(solution.canFormArray([85], [[85]]), True)
self.assertEqual(solution.canFormArray([15, 88], [[88], [15]]), True)
self.assertEqual(solution.canFormArray([49, 18, 16], [[16, 18, 49]]), False)
self.assertEqual(solution.canFormArray([91, 4, 64, 78], [[78], [4, 64], [91]]), True)
self.assertEqual(solution.canFormArray([1, 3, 5, 7], [[2, 4, 6, 8]]), False)
if __name__ == '__main__':
unittest.main()
|
[
"u.gaemi@gmail.com"
] |
u.gaemi@gmail.com
|
bb9ebaaa51633a24e64e44e7dfb51ff0f21d2fdc
|
5f29a9f8b218f7b02a76af02b49f8cf5aaa8ec97
|
/ecommerce/ecommerce/settings.py
|
1f96bed14501297d0c6f25199abbbb08ba9df6f9
|
[] |
no_license
|
yemiemy/Footwear-Stores
|
58c026b38ffe828cef17c58365b77169ad21ce80
|
92f719824c019044aef78b2b481597b9f94405e0
|
refs/heads/master
| 2022-12-18T13:34:05.283709
| 2019-09-01T22:32:31
| 2019-09-01T22:32:31
| 205,739,701
| 2
| 0
| null | 2022-12-08T06:06:26
| 2019-09-01T22:31:27
|
HTML
|
UTF-8
|
Python
| false
| false
| 4,190
|
py
|
"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0#-622+)iekpf$4w_vn19e0_itwsgdt9v)g63(22h0ygjzvs2y'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
DEFAULT_FROM_EMAIL = 'FOOTWEAR <rasholayemi@gmail.com>'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'rasholayemi@gmail.com'
EMAIL_HOST_PASSWORD = 'oladimeji'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
if DEBUG:
SITE_URL = 'http://127.0.0.1:8000'
if not DEBUG:
SITE_URL = 'http://footwear.com'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products',
'carts',
'orders',
'accounts',
'crispy_forms',
'django_countries',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ecommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Lagos'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static_file')
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'media')
#MEDIA_ROOT = '/Users/Yemi/Desktop/works/static/media'
STRIPE_SECRET_KEY = 'sk_test_zYI5XTc4XMwwHKiJ5HhNUbEW008WFLfwDb'
STRIPE_PUBLISHABLE_KEY = 'pk_test_N3wRcVV5GmnPBaSJiwbwqVHb00omMk74e1'
#send_mail('hello there', 'this is a test message', 'rasholayemi@gmail.com', ['rasholayemi@gmail.com'], fail_silently = True)
|
[
"rasholayemi@gmail.com"
] |
rasholayemi@gmail.com
|
d9da6299c37925b684c7e641e6e4b21e82cdd5c1
|
7a02c39b1bd97576991581379fed7e4209c199f2
|
/Learning/day20/s12bbs-code/s12bbs-code/aa.py
|
a44becfde85a3b36497596a8daf7ff50434c0b70
|
[] |
no_license
|
chenjinpeng1/python
|
0dc9e980ea98aac7145dd6ef966dd3903d488810
|
342d3d5079d158764a5f27838dcaf877e7c430ab
|
refs/heads/master
| 2020-04-06T13:28:11.158318
| 2016-10-16T16:11:09
| 2016-10-16T16:11:09
| 48,805,853
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 446
|
py
|
#python 3.5环境,解释器在linux需要改变
# -*- encoding:utf-8 -*-
#Auth ChenJinPeng
if __name__ == '__main__':
s = set()
s.add("aaaaa")
s.add("bbbbbb")
# print(s)
with open("tzc.txt", 'w', encoding="utf-8") as f:
for i in s:
print(i)
write_value = "%scccccc\n" % i
print(write_value)
f.write(write_value)
f.write("eeee")
f.write("dddd")
|
[
"1585742649@qq.com"
] |
1585742649@qq.com
|
ddf0d322979e965f66a2702d1b4fd867fa63cc0e
|
8c016302f173a8a2c4cdbc8c3398e1be61808cc9
|
/itkwidgets/widget_line_profiler.py
|
b8db546a3b430a5f5617574ff54595bdbf2e5b2f
|
[
"Apache-2.0"
] |
permissive
|
jpambrun/itk-jupyter-widgets
|
cba7b760912446f6ec801bbf4e3d83dafa70b8b5
|
3e00592e2f7285deea1b4eed0257c96179e5dc96
|
refs/heads/master
| 2020-04-09T20:10:21.686169
| 2018-11-26T19:25:32
| 2018-11-26T19:25:32
| 160,565,931
| 0
| 1
|
Apache-2.0
| 2018-12-05T19:10:03
| 2018-12-05T19:10:03
| null |
UTF-8
|
Python
| false
| false
| 8,145
|
py
|
"""LineProfiler class
Image visualization with a line profile.
"""
from traitlets import Unicode
import numpy as np
import scipy.ndimage
import ipywidgets as widgets
from .widget_viewer import Viewer
from ipydatawidgets import NDArray, array_serialization, shape_constraints
from traitlets import CBool
import matplotlib.pyplot as plt
import matplotlib
import IPython
import itk
from ._to_itk import to_itk_image
@widgets.register
class LineProfiler(Viewer):
"""LineProfiler widget class."""
_view_name = Unicode('LineProfilerView').tag(sync=True)
_model_name = Unicode('LineProfilerModel').tag(sync=True)
_view_module = Unicode('itk-jupyter-widgets').tag(sync=True)
_model_module = Unicode('itk-jupyter-widgets').tag(sync=True)
_view_module_version = Unicode('^0.12.2').tag(sync=True)
_model_module_version = Unicode('^0.12.2').tag(sync=True)
point1 = NDArray(dtype=np.float64, default_value=np.zeros((3,), dtype=np.float64),
help="First point in physical space that defines the line profile")\
.tag(sync=True, **array_serialization)\
.valid(shape_constraints(3,))
point2 = NDArray(dtype=np.float64, default_value=np.ones((3,), dtype=np.float64),
help="First point in physical space that defines the line profile")\
.tag(sync=True, **array_serialization)\
.valid(shape_constraints(3,))
_select_initial_points = CBool(default_value=False, help="We will select the initial points for the line profile.").tag(sync=True)
def __init__(self, **kwargs):
if 'point1' not in kwargs or 'point2' not in kwargs:
self._select_initial_points = True
# Default to z-plane mode instead of the 3D volume if we need to
# select points
if 'mode' not in kwargs:
kwargs['mode'] = 'z'
super(LineProfiler, self).__init__(**kwargs)
def line_profile(image, order=2, plotter=None, comparisons=None, **viewer_kwargs):
"""View the image with a line profile.
Creates and returns an ipywidget to visualize the image along with a line
profile.
The image can be 2D or 3D.
Parameters
----------
image : array_like, itk.Image, or vtk.vtkImageData
The 2D or 3D image to visualize.
order : int, optional
Spline order for line profile interpolation. The order has to be in the
range 0-5.
plotter : 'plotly', 'bqplot', or 'ipympl', optional
Plotting library to use. If not defined, use plotly if available,
otherwise bqplot if available, otherwise ipympl.
comparisons: dict, optional
A dictionary whose keys are legend labels and whose values are other
images whose intensities to plot over the same line.
viewer_kwargs : optional
Keyword arguments for the viewer. See help(itkwidgets.view).
"""
profiler = LineProfiler(image=image, **viewer_kwargs)
if not plotter:
try:
import plotly.graph_objs as go
plotter = 'plotly'
except ImportError:
pass
if not plotter:
try:
import bqplot
plotter = 'bqplot'
except ImportError:
pass
if not plotter:
plotter = 'ipympl'
def get_profile(image_or_array):
image_from_array = to_itk_image(image_or_array)
if image_from_array:
image_ = image_from_array
else:
image_ = image_or_array
image_array = itk.GetArrayViewFromImage(image_)
dimension = image_.GetImageDimension()
distance = np.sqrt(sum([(profiler.point1[ii] - profiler.point2[ii])**2 for ii in range(dimension)]))
index1 = tuple(image_.TransformPhysicalPointToIndex(tuple(profiler.point1[:dimension])))
index2 = tuple(image_.TransformPhysicalPointToIndex(tuple(profiler.point2[:dimension])))
num_points = int(np.round(np.sqrt(sum([(index1[ii] - index2[ii])**2 for ii in range(dimension)])) * 2.1))
coords = [np.linspace(index1[ii], index2[ii], num_points) for ii in range(dimension)]
mapped = scipy.ndimage.map_coordinates(image_array, np.vstack(coords[::-1]),
order=order, mode='nearest')
return np.linspace(0.0, distance, num_points), mapped
if plotter == 'plotly':
import plotly.graph_objs as go
layout = go.Layout(
xaxis=dict(title='Distance'),
yaxis=dict(title='Intensity')
)
fig = go.FigureWidget(layout=layout)
elif plotter == 'bqplot':
import bqplot
x_scale = bqplot.LinearScale()
y_scale = bqplot.LinearScale()
x_axis = bqplot.Axis(scale=x_scale, grid_lines='solid', label='Distance')
y_axis = bqplot.Axis(scale=y_scale, orientation='vertical', grid_lines='solid', label='Intensity')
labels = ['Reference']
display_legend = False
if comparisons:
display_legend=True
labels += [label for label in comparisons.keys()]
lines = [bqplot.Lines(scales={'x': x_scale, 'y': y_scale},
labels=labels, display_legend=display_legend, enable_hover=True)]
fig = bqplot.Figure(marks=lines, axes=[x_axis, y_axis])
elif plotter == 'ipympl':
ipython = IPython.get_ipython()
ipython.enable_matplotlib('widget')
is_interactive = matplotlib.is_interactive()
matplotlib.interactive(False)
fig, ax = plt.subplots()
else:
raise ValueError('Invalid plotter: ' + plotter)
def update_plot():
if plotter == 'plotly':
distance, intensity = get_profile(image)
fig.data[0]['x'] = distance
fig.data[0]['y'] = intensity
if comparisons:
for ii, image_ in enumerate(comparisons.values()):
distance, intensity = get_profile(image_)
fig.data[ii+1]['x'] = distance
fig.data[ii+1]['y'] = intensity
elif plotter == 'bqplot':
distance, intensity = get_profile(image)
if comparisons:
for image_ in comparisons.values():
distance_, intensity_ = get_profile(image_)
distance = np.vstack((distance, distance_))
intensity = np.vstack((intensity, intensity_))
fig.marks[0].x = distance
fig.marks[0].y = intensity
elif plotter == 'ipympl':
ax.plot(*get_profile(image))
if comparisons:
ax.plot(*get_profile(image), label='Reference')
for label, image_ in comparisons.items():
ax.plot(*get_profile(image_), label=label)
ax.legend()
else:
ax.plot(*get_profile(image))
ax.set_xlabel('Distance')
ax.set_ylabel('Intensity')
fig.canvas.draw()
fig.canvas.flush_events()
def update_profile(change):
if plotter == 'plotly':
update_plot()
elif plotter == 'bqplot':
update_plot()
elif plotter == 'ipympl':
is_interactive = matplotlib.is_interactive()
matplotlib.interactive(False)
ax.clear()
update_plot()
matplotlib.interactive(is_interactive)
if plotter == 'plotly':
distance, intensity = get_profile(image)
trace = go.Scattergl(x=distance, y=intensity, name='Reference')
fig.add_trace(trace)
if comparisons:
for label, image_ in comparisons.items():
distance, intensity = get_profile(image_)
trace = go.Scattergl(x=distance, y=intensity, name=label)
fig.add_trace(trace)
widget = widgets.VBox([profiler, fig])
elif plotter == 'bqplot':
update_plot()
widget = widgets.VBox([profiler, fig])
elif plotter == 'ipympl':
update_plot()
widget = widgets.VBox([profiler, fig.canvas])
profiler.observe(update_profile, names=['point1', 'point2'])
return widget
|
[
"matt.mccormick@kitware.com"
] |
matt.mccormick@kitware.com
|
f84ba0dc45e75e82e0edb109d4c3ce7da79af4d9
|
4eea6c0940439d4e78cd125c311d0e1a12a826ed
|
/messiah_ast_optimizer/common/classutils.py
|
be8047fdbe9e8e3284be1bd1b0aac878653c08a4
|
[] |
no_license
|
chenyfsysu/PythonNote
|
5c77578423f95399b1eda7651dc73f1642ee3cb7
|
9b49eced10bab794ddf5452f18bba55d8ba24c18
|
refs/heads/master
| 2021-05-07T06:14:56.825737
| 2018-10-18T06:49:41
| 2018-10-18T06:49:41
| 111,645,501
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,985
|
py
|
# -*- coding:utf-8 -*-
import ast
def ismethod(node):
return isinstance(node, ast.FunctionDef)
def getmembers(mro, predicate=None):
result = {}
finder = AttributeFinder(findall=True, predicate=predicate)
for cls in mro:
for (key, value) in finder.find(cls).iteritems():
if (key not in result):
result[key] = value.node
return result
def getclassbodies(mro, predicate=None):
return [node for cls in mro for node in cls.body if ((not predicate) or predicate(node))]
def predicate_entity_property(node):
return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Call) and (node.value.func.id == 'Property'))
def predicate_class_attr(node):
return isinstance(node, ast.Assign)
def _fold_property(props):
return ('coco', 0, 0, 0)
for prop in props:
(name, all, flag, delay) = _fold_property(prop)
property_all[name] = all
property_flag[name] = flag
property_delay[name] = delay
return (property_all, property_flag, property_delay)
def split_cls_body(cls):
prop = getclassbodies(cls, predicate_entity_property)
attr = getclassbodies(cls, predicate_class_attr)
method = getmembers(cls, ismethod)
return (prop, attr, method)
def merge_component(host, component):
(attrs, methods, properties, decorator_list) = ([], {}, [], [])
component.insert(0, host)
print component
for comp in component:
(prop, attr, method) = split_cls_body(comp)
properties.append(prop)
attrs.append(attr)
methods.update(method)
decorator_list.extend([deco for cls in comp for deco in cls.decorator_list])
body = ((properties + attrs) + methods.values())
host[0].body = body
host[0].decorator_list = decorator_list
return host
if (__name__ == '__main__'):
src = '\nif True:\n\tA = 100\nelse:\n\tA = 10\n'
import astunparse
node = ast.parse(src)
for body in node.body:
print body
|
[
"chenyfsysu@gmail.com"
] |
chenyfsysu@gmail.com
|
6695b4cc772773778236433871367a45cddbb7d3
|
521efcd158f4c69a686ed1c63dd8e4b0b68cc011
|
/airflow/providers/alibaba/cloud/example_dags/example_oss_bucket.py
|
83d0255349f6eb143226b6fdc12c5eab8c85d2d5
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
coutureai/RaWorkflowOrchestrator
|
33fd8e253bfea2f9a82bb122ca79e8cf9dffb003
|
cd3ea2579dff7bbab0d6235fcdeba2bb9edfc01f
|
refs/heads/main
| 2022-10-01T06:24:18.560652
| 2021-12-29T04:52:56
| 2021-12-29T04:52:56
| 184,547,783
| 5
| 12
|
Apache-2.0
| 2022-11-04T00:02:55
| 2019-05-02T08:38:38
|
Python
|
UTF-8
|
Python
| false
| false
| 1,413
|
py
|
# 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.
from datetime import datetime
from airflow.models.dag import DAG
from airflow.providers.alibaba.cloud.operators.oss import OSSCreateBucketOperator, OSSDeleteBucketOperator
# [START howto_operator_oss_bucket]
with DAG(
dag_id='oss_bucket_dag',
start_date=datetime(2021, 1, 1),
default_args={'bucket_name': 'your bucket', 'region': 'your region'},
max_active_runs=1,
tags=['example'],
catchup=False,
) as dag:
create_bucket = OSSCreateBucketOperator(task_id='task1')
delete_bucket = OSSDeleteBucketOperator(task_id='task2')
create_bucket >> delete_bucket
# [END howto_operator_oss_bucket]
|
[
"noreply@github.com"
] |
coutureai.noreply@github.com
|
017d97be74d253ad06c54ee180f0c4270f0ebb4a
|
23d1d8e2f2cb54ce1227765f949af3324063357f
|
/shopify/webhook/tests/factories.py
|
fc7cbd2900f88739c76bf00a9f4daccbb7f83e4b
|
[
"BSD-3-Clause"
] |
permissive
|
CorbanU/corban-shopify
|
4586b6625511c594b9f37b72d0adf57b71c7677c
|
5af1d9e5b4828c375fe8c3329e13f7dcad5e5cfc
|
refs/heads/master
| 2021-01-17T13:50:39.845955
| 2017-05-17T18:36:24
| 2017-05-17T18:36:24
| 29,499,681
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,528
|
py
|
import factory
from factory import fuzzy
from mock import patch
from django.utils.timezone import now
from shopify.product.models import Product
from shopify.product.models import Transaction
from shopify.webhook.models import Webhook
class ProductFactory(factory.django.DjangoModelFactory):
class Meta:
model = Product
product_id = fuzzy.FuzzyInteger(100000, 999999)
product_type = fuzzy.FuzzyChoice(['Deposit', 'Fee', 'Purchase'])
description = fuzzy.FuzzyText(length=64)
account_number = fuzzy.FuzzyInteger(1000000, 9999999)
class TransactionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Transaction
product = factory.SubFactory(ProductFactory)
amount = fuzzy.FuzzyFloat(1.00, 100.00)
is_credit = True
order_id = fuzzy.FuzzyInteger(1000000, 9999999)
order_name = fuzzy.FuzzyText(length=8)
item_id = fuzzy.FuzzyInteger(100000, 999999)
created_at = now()
class WebhookFactory(factory.django.DjangoModelFactory):
class Meta:
model = Webhook
@classmethod
def _create(cls, target_class, *args, **kwargs):
with patch('requests.post') as mock:
mock.return_value.status_code = 200
mock.return_value.raise_for_status.return_value = None
mock.return_value.raise_for_status()
mock.return_value.json.return_value = {'webhook': {'id': 12345}}
mock.return_value.json()
return super(WebhookFactory, cls)._create(target_class, *args, **kwargs)
|
[
"jason.bittel@gmail.com"
] |
jason.bittel@gmail.com
|
87762da3e9e92ee74337ce102ce0e7fa74365ffc
|
2d311d74071ea2d5e0c756186e41cfc567f56b6c
|
/app/core/tests/test_models.py
|
4c43911407bd1cbce4dc7cd67ba5ffdf7ca942c2
|
[
"MIT"
] |
permissive
|
frankRose1/recipe-app-api
|
ab128d4b97f76f55f61a5a6eb17e4acdf8348981
|
0fff174ecb59bb06e6b631a33e34984e2f12f68a
|
refs/heads/master
| 2022-02-05T03:55:00.043139
| 2019-08-01T03:43:14
| 2019-08-01T03:43:14
| 197,990,263
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,909
|
py
|
from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='testUser@local.host', password='testPass'):
"""
Create and return a sample user
:param email: Email address
:type email: str
:param password: Password
:type password: str
:return: User model instance
"""
return get_user_model().objects.create(email=email, password=password)
class ModelTests(TestCase):
def test_create_user_with_email_successfull(self):
"""Test creating a new user with an email successfully"""
params = {
'email': 'test@local.host',
'password': 'testPass123'
}
user = get_user_model().objects.create_user(**params)
self.assertEqual(user.email, params['email'])
self.assertTrue(user.check_password(params['password']))
def test_new_user_email_normalized(self):
"""Test creating a new user will normalize the email"""
email = 'test@LOCAL.HOST'
user = get_user_model().objects.create_user(email, 'test123')
self.assertEqual(user.email, email.lower())
def test_new_user_invalid_email(self):
"""Test creating a user with no email raises an error"""
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, 'test123')
def test_create_new_super_user(self):
"""Test cresting a new super user"""
user = get_user_model().objects.create_superuser(
'superUser@local.host',
'test123')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
def test_tag_str(self):
"""Test the tag string representation"""
tag = models.Tag.objects.create(
user=sample_user(),
name='Vegan'
)
self.assertEqual(str(tag), tag.name)
def test_ingredient_str(self):
"""Test the ingredient string representation"""
ingredient = models.Ingredient.objects.create(
user=sample_user(),
name='Cucumber'
)
self.assertEqual(str(ingredient), ingredient.name)
def test_recipe_str(self):
"""Test the ingredient string representation"""
recipe = models.Recipe.objects.create(
user=sample_user(),
title='Steak and Mushroom Sauce',
time_minutes=5,
price=5.00
)
self.assertEqual(str(recipe), recipe.title)
@patch('uuid.uuid4')
def test_recipe_filename_uuid(self, mock_uuid):
"""Test that image is saved in the correct location"""
uuid = 'test-uuid'
mock_uuid.return_value = uuid
file_path = models.recipe_image_file_path(None, 'myimage.jpg')
expected_path = f'uploads/recipe/{uuid}.jpg'
self.assertEqual(file_path, expected_path)
|
[
"frank.rosendorf1@gmail.com"
] |
frank.rosendorf1@gmail.com
|
1fa0fb7eeeffdef62a38f01de113f43e004559c7
|
76e9b6cd86803cfd619c32bea338fbf64bf29221
|
/gui.py
|
c53e9809dad7296d77a12ed04aa958293c411b36
|
[] |
no_license
|
remton/Python_Chess
|
3f004d3d6be4321f75e4176a36f7d728a4c2fc8e
|
977ee7d6d154037f9588f826c03a3943a2122d94
|
refs/heads/master
| 2022-12-03T11:14:15.552912
| 2020-08-13T05:17:32
| 2020-08-13T05:17:32
| 285,480,016
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,936
|
py
|
# gui.py
# Handles all the gui
from tkinter import *
from util import col_to_board, row_to_board
import util
# First thing when working with tkinter
root = Tk()
root.title("Remi's Chess Game")
def on_close():
raise SystemExit
root.protocol("WM_DELETE_WINDOW", on_close)
# PhotoImage must keep the original variable so this dict allows access to images whenever we want
piece_images = {
'Empty': PhotoImage(file='Images/Empty.png'),
'Pawn_w': PhotoImage(file='Images/Pawn_w.png'),
'Pawn_b': PhotoImage(file='Images/Pawn_b.png'),
'Knight_w': PhotoImage(file='Images/Knight_w.png'),
'Knight_b': PhotoImage(file='Images/Knight_b.png'),
'Bishop_w': PhotoImage(file='Images/Bishop_w.png'),
'Bishop_b': PhotoImage(file='Images/Bishop_b.png'),
'Rook_w': PhotoImage(file='Images/Rook_w.png'),
'Rook_b': PhotoImage(file='Images/Rook_b.png'),
'Queen_w': PhotoImage(file='Images/Queen_w.png'),
'Queen_b': PhotoImage(file='Images/Queen_b.png'),
'King_w': PhotoImage(file='Images/King_w.png'),
'King_b': PhotoImage(file='Images/King_b.png'),
}
last_move = ''
is_first_button = True
first_space = ''
def on_button_press(space_str):
global last_move
global first_space
global is_first_button
if is_first_button:
# This is a weird way to check if the space is empty but it works
# board is updated in update_grid
global board
x = util.board_to_space[space_str[0]]
y = util.board_to_space[space_str[1]]
if board[y][x].piece.name == 'Empty':
return
first_space = space_str
is_first_button = False
else:
last_move = f'{first_space},{space_str}'
is_first_button = True
first_space = ''
root.quit()
# Unlike with the ChessBoard grid is indexed [x][y]
grid = [[]]
def create_grid():
back_color = 'gray'
front_color = 'white'
grid.clear()
row = []
for x in range(8):
row.clear()
for y in range(8):
space = row_to_board[x] + col_to_board[y]
new_button = Button(root, padx=20, pady=20, bg=back_color, fg=front_color, image=piece_images['Empty'],
text=space, command=util.create_lambda(on_button_press, space))
row.append(new_button)
temp = back_color
back_color = front_color
front_color = temp
grid.append(row.copy())
temp = back_color
back_color = front_color
front_color = temp
for x in range(0, 8):
for y in range(0, 8):
grid[x][7 - y].grid(column=x+1, row=y)
# Create the labels for space names
for x in range(8):
new_label = Label(root, height=2, width=8, text=row_to_board[x])
new_label.grid(column=x+1, row=8)
for y in range(8):
new_label = Label(root, height=4, width=4, text=col_to_board[y])
new_label.grid(column=0, row=7-y)
board = None
def update_grid(chess_board):
global grid
global board
board = chess_board.board
for x in range(8):
for y in range(8):
piece = board[y][x].piece
grid[x][y]['image'] = piece_images[piece.img_name]
def open_window(chess_board, run_loop=True):
create_grid()
update_grid(chess_board)
if run_loop:
root.mainloop()
def endgame_window_close(end_root):
end_root.quit()
def open_endgame_window(is_checkmate=False, is_draw=False):
end_root = Tk()
if is_checkmate:
message = "Checkmate!"
elif is_draw:
message = "Draw."
else:
message = "Error: open_endgame_window needs checkmate or is_draw to be true"
message_label = Label(end_root, height=5, width=10, text=message)
message_label.pack()
continue_button = Button(end_root, padx=20, pady=20, text='continue', command=lambda: endgame_window_close(end_root))
continue_button.pack()
end_root.mainloop()
|
[
"unconfigured@null.spigotmc.org"
] |
unconfigured@null.spigotmc.org
|
e8ab10ad4da9ab0533ae01589b7ed1aee5b30997
|
32166eebe7767379259192d322939d3cf83fd403
|
/Token_Management/windows_token_demo.py
|
ff475a3862172025ec0b690048044e4004b7bf58
|
[] |
no_license
|
wifinigel/semfio-mist
|
1294e52d42f0c373eb24724beaf754f9332d742e
|
f501b6488de621b30c5f3a99b3e53bb129970915
|
refs/heads/master
| 2022-09-30T04:53:55.968239
| 2020-05-22T11:22:47
| 2020-05-22T11:22:47
| 266,056,873
| 0
| 0
| null | 2020-05-22T08:18:51
| 2020-05-22T08:18:51
| null |
UTF-8
|
Python
| false
| false
| 2,002
|
py
|
"""
This script that demonsrates how to use token_class.py on Windows
Before running the script, you must define a user-level environmental
variable that contains your Mist API token. This will be used to access
the Mist cloud and create the required temporary key(s) to perfom
scripted actions.
The token_class module relies on the presence of an environmental
variable called MIST_TOKEN to authorize access to the Mist API. This
env var must contain the value of a valid token that has been
previousy created via the Mist API, e.g. using POSTMAN or some other
API access tool - see the following URL for an example:
https://www.mist.com/documentation/using-postman/).
To create the user env var, use the following command from a
command window on a Windows 10 machine:
setx MIST_TOKEN "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
To verify the env var has been correctly created, open a new command
windows and type the following command to verify that the env var
is now gloablly available to the user account being used:
echo %MIST_TOKEN%
Note that the env var is only available in a NEW command window. The env
var is now permanently avaialble to all processes running under the current
user account. The env var will not be available to other users on the same
machine.
To remove the env var value, set the env var with a blank value in a command
window (the env var will still exist, but will have no value):
setx MIST_TOKEN ""
Or, alternatively it may be deleted via the Windows 10 GUI environmental
variable editing tool: Start > Control Panel > System & Security >
System > Advanced System Settings > Environmental Variables (User section)
"""
from token_class import Token
# create Token obj
master_token_obj = Token()
# get a temporary token so that we can do some stuff
temp_mist_token = master_token_obj.get_tmp_token()
# do some stuff here (e.g. list WLANs)
# TBA
# clean up by removing our temporary token
master_token_obj.delete_tmp_token()
|
[
"wifinigel@gmail.com"
] |
wifinigel@gmail.com
|
131f171e663006b3246eeba41b11a128b8d050df
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03626/s622123482.py
|
66a5287c093edaa7fe69b4f24155002213a9e8f0
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 483
|
py
|
MOD = 10**9 + 7
N = int(input())
S = input()
S2 = input()
check = []
flg = False
for i in range(N-1):
if flg:
check.append(2)
flg = False
continue
if S[i] == S[i+1]:
flg = True
else:
check.append(1)
if flg:
check.append(2)
else:
check.append(1)
ans = 3 if check[0] == 1 else 6
for i in range(1,len(check)):
if check[i-1] == 1:
ans *= 2
elif check[i] == 2 and check[i-1] == 2:
ans *= 3
print(ans%MOD)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
5e4e68907abd04d355a44780c5bfe0fa5ebfdc8d
|
d86c52f4098fd9c1a102c2d3f5630556e0610fa2
|
/fitle/myenv/Lib/site-packages/django/db/models/fields/related_descriptors.py
|
ebcd53f1822ef4847790158e594127aaabf8fc0d
|
[] |
no_license
|
makadama/bitbucket
|
24f05c4946168ed15d4f56bfdc45fd6c0774e0f2
|
cabfd551b92fe1af6d9d14ab9eb3d9974b64aa79
|
refs/heads/master
| 2023-06-19T19:04:03.894599
| 2021-07-15T12:10:39
| 2021-07-15T12:10:39
| 385,203,791
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 130
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:c80ba94b54aa0987fdd1aca4451b1c1266148d2b48d83ceb5c33ec8048d478d7
size 54061
|
[
"adamamakhtarsow@gmail.com"
] |
adamamakhtarsow@gmail.com
|
5000e704ec583c0179a3f2695f926eb0e8621667
|
caa05194b8f11f29a19767c94fdc93628be694d5
|
/examples/asr/quantization/speech_to_text_calibrate.py
|
165623f283c29b64d870e226782f5cc7f6844a2a
|
[
"Apache-2.0"
] |
permissive
|
Jimmy-INL/NeMo
|
a589ab0ab97b9ccb8921579670e80c470ce7077b
|
6a3753b3013dc92a3587853d60c5086e2e64d98f
|
refs/heads/main
| 2023-04-02T22:28:29.891050
| 2021-04-13T18:22:24
| 2021-04-13T18:22:24
| 357,681,603
| 1
| 0
|
Apache-2.0
| 2021-04-13T20:34:12
| 2021-04-13T20:34:12
| null |
UTF-8
|
Python
| false
| false
| 6,150
|
py
|
# Copyright (c) 2020, NVIDIA CORPORATION. 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.
"""
Script for calibrating a pretrained ASR model for quantization
"""
from argparse import ArgumentParser
import torch
from omegaconf import open_dict
from nemo.collections.asr.models import EncDecCTCModel
from nemo.utils import logging
try:
from pytorch_quantization import calib
from pytorch_quantization import nn as quant_nn
from pytorch_quantization import quant_modules
from pytorch_quantization.tensor_quant import QuantDescriptor
except ImportError:
raise ImportError(
"pytorch-quantization is not installed. Install from "
"https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization."
)
try:
from torch.cuda.amp import autocast
except ImportError:
from contextlib import contextmanager
@contextmanager
def autocast(enabled=None):
yield
can_gpu = torch.cuda.is_available()
def main():
parser = ArgumentParser()
parser.add_argument(
"--asr_model", type=str, default="QuartzNet15x5Base-En", required=True, help="Pass: 'QuartzNet15x5Base-En'",
)
parser.add_argument("--dataset", type=str, required=True, help="path to evaluation data")
parser.add_argument("--batch_size", type=int, default=256)
parser.add_argument(
"--normalize_text", default=True, type=bool, help="Normalize transcripts or not. Set to False for non-English."
)
parser.add_argument('--num_calib_batch', default=1, type=int, help="Number of batches for calibration.")
parser.add_argument('--calibrator', type=str, choices=["max", "histogram"], default="max")
parser.add_argument('--percentile', nargs='+', type=float, default=[99.9, 99.99, 99.999, 99.9999])
parser.add_argument("--amp", action="store_true", help="Use AMP in calibration.")
parser.set_defaults(amp=False)
args = parser.parse_args()
torch.set_grad_enabled(False)
# Initialize quantization
quant_desc_input = QuantDescriptor(calib_method=args.calibrator)
quant_nn.QuantConv2d.set_default_quant_desc_input(quant_desc_input)
quant_nn.QuantConvTranspose2d.set_default_quant_desc_input(quant_desc_input)
quant_nn.QuantLinear.set_default_quant_desc_input(quant_desc_input)
if args.asr_model.endswith('.nemo'):
logging.info(f"Using local ASR model from {args.asr_model}")
asr_model_cfg = EncDecCTCModel.restore_from(restore_path=args.asr_model, return_config=True)
with open_dict(asr_model_cfg):
asr_model_cfg.encoder.quantize = True
asr_model = EncDecCTCModel.restore_from(restore_path=args.asr_model, override_config_path=asr_model_cfg)
else:
logging.info(f"Using NGC cloud ASR model {args.asr_model}")
asr_model_cfg = EncDecCTCModel.from_pretrained(model_name=args.asr_model, return_config=True)
with open_dict(asr_model_cfg):
asr_model_cfg.encoder.quantize = True
asr_model = EncDecCTCModel.from_pretrained(model_name=args.asr_model, override_config_path=asr_model_cfg)
asr_model.setup_test_data(
test_data_config={
'sample_rate': 16000,
'manifest_filepath': args.dataset,
'labels': asr_model.decoder.vocabulary,
'batch_size': args.batch_size,
'normalize_transcripts': args.normalize_text,
'shuffle': True,
}
)
if can_gpu:
asr_model = asr_model.cuda()
asr_model.eval()
# Enable calibrators
for name, module in asr_model.named_modules():
if isinstance(module, quant_nn.TensorQuantizer):
if module._calibrator is not None:
module.disable_quant()
module.enable_calib()
else:
module.disable()
for i, test_batch in enumerate(asr_model.test_dataloader()):
if can_gpu:
test_batch = [x.cuda() for x in test_batch]
if args.amp:
with autocast():
_ = asr_model(input_signal=test_batch[0], input_signal_length=test_batch[1])
else:
_ = asr_model(input_signal=test_batch[0], input_signal_length=test_batch[1])
if i >= args.num_calib_batch:
break
# Save calibrated model(s)
model_name = args.asr_model.replace(".nemo", "") if args.asr_model.endswith(".nemo") else args.asr_model
if not args.calibrator == "histogram":
compute_amax(asr_model, method="max")
asr_model.save_to(F"{model_name}-max-{args.num_calib_batch*args.batch_size}.nemo")
else:
for percentile in args.percentile:
print(F"{percentile} percentile calibration")
compute_amax(asr_model, method="percentile")
asr_model.save_to(F"{model_name}-percentile-{percentile}-{args.num_calib_batch*args.batch_size}.nemo")
for method in ["mse", "entropy"]:
print(F"{method} calibration")
compute_amax(asr_model, method=method)
asr_model.save_to(F"{model_name}-{method}-{args.num_calib_batch*args.batch_size}.nemo")
def compute_amax(model, **kwargs):
for name, module in model.named_modules():
if isinstance(module, quant_nn.TensorQuantizer):
if module._calibrator is not None:
if isinstance(module._calibrator, calib.MaxCalibrator):
module.load_calib_amax()
else:
module.load_calib_amax(**kwargs)
print(F"{name:40}: {module}")
if can_gpu:
model.cuda()
if __name__ == '__main__':
main() # noqa pylint: disable=no-value-for-parameter
|
[
"noreply@github.com"
] |
Jimmy-INL.noreply@github.com
|
5e3fae95e1de68e3ee68cb9335bfce8908637b86
|
d5796258828bf3e12abc8def1ad1828aa14b4cfc
|
/apps/courses/migrations/0005_video_url.py
|
b491a64be7002102502b318d5ee3e0948700ff8e
|
[] |
no_license
|
ghjan/imooc2
|
fbd3b1478df12a2961c77ee05f15cffc9cc26097
|
4652ba68db80577466f72ef1cda087c820144879
|
refs/heads/master
| 2020-03-18T16:12:28.828646
| 2018-11-28T07:52:14
| 2018-11-28T07:52:14
| 134,952,788
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 483
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-26 11:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0004_course_tag'),
]
operations = [
migrations.AddField(
model_name='video',
name='url',
field=models.URLField(default='', verbose_name='访问地址'),
),
]
|
[
"cajan2@163.com"
] |
cajan2@163.com
|
471d50f0791bed7f3468efcec297cac090555298
|
567c54ba9176581a5d5e1ae65212a6e87a604f0b
|
/wsgi/pico/pico/urls.py
|
10f56e5d61f05915d1344f8a55c10f6a8cc5c632
|
[] |
no_license
|
andrewidya/pico
|
e0641433e1e63ab865fe65924c32c687c75b8d83
|
4a0e8ff885601004aa92ba05d204e3fe6bd90731
|
refs/heads/master
| 2021-01-10T13:46:20.543152
| 2015-12-08T13:14:40
| 2015-12-08T13:14:40
| 45,040,768
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,305
|
py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import * # NOQA
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
handler404 = 'pico.views.page_not_found'
#handler500 = 'pico.views.server_error'
admin.autodiscover()
#urlpatterns = patterns('',
# url(r'^i18n/', include('django.conf.urls.i18n')),
#)
urlpatterns = i18n_patterns('',
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}, name='sitemap-xml'),
url(r'^select2/', include('django_select2.urls')),
url(r'^', include('cms.urls')),
url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')),
url(r'^pico_blog/', include('pico_blog.urls', namespace='pico_blog')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + staticfiles_urlpatterns() + urlpatterns # NOQA
|
[
"andrywidyaputra@gmail.com"
] |
andrywidyaputra@gmail.com
|
41ca6333a252f2922ade21e51fce832cc16380cd
|
d1ddb9e9e75d42986eba239550364cff3d8f5203
|
/google-cloud-sdk/lib/surface/compute/backend_buckets/update.py
|
e0ebec42cade87a67f1e4d9830e24530ac96f7af
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
bopopescu/searchparty
|
8ecd702af0d610a7ad3a8df9c4d448f76f46c450
|
afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6
|
refs/heads/master
| 2022-11-19T14:44:55.421926
| 2017-07-28T14:55:43
| 2017-07-28T14:55:43
| 282,495,798
| 0
| 0
|
Apache-2.0
| 2020-07-25T17:48:53
| 2020-07-25T17:48:52
| null |
UTF-8
|
Python
| false
| false
| 3,509
|
py
|
# Copyright 2015 Google 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.
"""Commands for updating backend buckets."""
from apitools.base.py import encoding
from googlecloudsdk.api_lib.compute import backend_buckets_utils
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute.backend_buckets import flags as backend_buckets_flags
from googlecloudsdk.core import log
class Update(base.UpdateCommand):
"""Update a backend bucket.
*{command}* is used to update backend buckets.
"""
BACKEND_BUCKET_ARG = None
@staticmethod
def Args(parser):
backend_buckets_utils.AddUpdatableArgs(Update, parser, 'update')
backend_buckets_flags.GCS_BUCKET_ARG.AddArgument(parser)
def GetGetRequest(self, client, backend_bucket_ref):
return (
client.apitools_client.backendBuckets,
'Get',
client.messages.ComputeBackendBucketsGetRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name()))
def GetSetRequest(self, client, backend_bucket_ref, replacement):
return (
client.apitools_client.backendBuckets,
'Update',
client.messages.ComputeBackendBucketsUpdateRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name(),
backendBucketResource=replacement))
def Modify(self, args, existing):
replacement = encoding.CopyProtoMessage(existing)
if args.description:
replacement.description = args.description
elif args.description == '': # pylint: disable=g-explicit-bool-comparison
replacement.description = None
if args.gcs_bucket_name:
replacement.bucketName = args.gcs_bucket_name
if args.enable_cdn is not None:
replacement.enableCdn = args.enable_cdn
return replacement
def Run(self, args):
if not any([
args.description is not None,
args.gcs_bucket_name is not None,
args.enable_cdn is not None,
]):
raise exceptions.ToolException('At least one property must be modified.')
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket_ref = Update.BACKEND_BUCKET_ARG.ResolveAsResource(
args, holder.resources)
get_request = self.GetGetRequest(client, backend_bucket_ref)
objects = client.MakeRequests([get_request])
new_object = self.Modify(args, objects[0])
# If existing object is equal to the proposed object or if
# Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print(
'No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
return client.MakeRequests(
[self.GetSetRequest(client, backend_bucket_ref, new_object)])
|
[
"vinvivo@users.noreply.github.com"
] |
vinvivo@users.noreply.github.com
|
6f42842cd6d4e2a15cbf9d8d790618bcd0159ee0
|
86e904c75d0140eea3e4169d216955e1c34801b3
|
/python06/otherlist/tuple.py
|
08901db550a2d42cbcae9e73445464e794c265e3
|
[] |
no_license
|
reharmony/cloudpython
|
d62f61749e5b5862d3b81e449d5154e188a14d21
|
98e033e537d763ba86d162f58d0fe8f64249a291
|
refs/heads/master
| 2020-04-29T16:58:55.281917
| 2019-05-15T12:11:43
| 2019-05-15T12:11:43
| 176,281,740
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 283
|
py
|
# 튜플 연습
data1 = (1,2,3)
print(data1)
print(data1[0])
print(data1[0:2])
print(data1[1:])
print(data1[:2])
print()
data2 = "나는 파이썬 프로그래머입니다."
print(data2[0])
print(data2[0:3])
print()
print(len(data2))
data2[0] = "너"
print(data2)
|
[
"noreply@github.com"
] |
reharmony.noreply@github.com
|
f0471cb047e073636ed9b5e06738bc66e893f364
|
a4a01e251b194f6d3c6654a2947a33fec2c03e80
|
/PythonWeb/Django/1809/djangoproject/djangodemo03/index/migrations/0005_book_isactive.py
|
f1824439227422bb93b902a60723b849ee4ecca1
|
[] |
no_license
|
demo112/1809
|
033019043e2e95ebc637b40eaf11c76bfd089626
|
e22972229e5e7831dce2aae0b53ce19a6e3bb106
|
refs/heads/master
| 2020-04-09T07:10:49.906231
| 2019-02-27T13:08:45
| 2019-02-27T13:08:45
| 160,143,869
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 442
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-01-15 06:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('index', '0004_author_book'),
]
operations = [
migrations.AddField(
model_name='book',
name='isActive',
field=models.BooleanField(default=True),
),
]
|
[
"huafengdongji@hotmail.com"
] |
huafengdongji@hotmail.com
|
ef1e1182e010d8e86a23b996d3675af834a646b9
|
77a37559730c9228c6ae9c530dc80b8488080c23
|
/src/my_plagin/scripts/getoff.py
|
776c307efdf299d807b2958f889c159a44ee4cc4
|
[] |
no_license
|
tdtce/quadrotor
|
f01e889ef1252ef5e28fc146521a057ead6fa62e
|
64677c9c0c461f5bc7ef73b922d5cd912c2e6783
|
refs/heads/master
| 2020-03-10T17:06:53.133096
| 2018-05-19T16:42:21
| 2018-05-19T16:42:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 686
|
py
|
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import math
from geometry_msgs.msg import Twist # message for topic /cmd_vel
from geometry_msgs.msg import Vector3
import sys
def cmd_command():
msg = Vector3(-5.0, 2.0, 1.0)
#rospy.loginfo(cmd)
return msg
def open_loop():
rospy.init_node("getoff", anonymous=True, disable_signals=True)
quad_vel = rospy.Publisher("/intermediate_state", Vector3, queue_size=1)
rate = rospy.Rate(10)
while not rospy.is_shutdown():
quad_vel.publish(cmd_command())
rate.sleep()
if __name__ == "__main__":
try:
open_loop()
except rospy.ROSInterruptException:
pass
|
[
"fantaa499@gmail.com"
] |
fantaa499@gmail.com
|
e57e48ae6f83a97426f4e9b7b4dac4ea7bc018d9
|
51da71a26628a3c6d1814e6da38f5c48f3101d9b
|
/uri/1174.py
|
e4d914cf072f646eca444af1f90e1b8b071a2f5b
|
[] |
no_license
|
da-ferreira/uri-online-judge
|
279156249a1b0be49a7b29e6dbce85a293a47df1
|
6ec97122df3cb453ea26e0c9f9206a2e470ba37d
|
refs/heads/main
| 2023-03-30T11:47:05.120388
| 2021-04-02T19:45:25
| 2021-04-02T19:45:25
| 309,744,456
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 180
|
py
|
vetor = []
for i in range(100):
vetor.append(float(input()))
for i in range(len(vetor)):
if vetor[i] <= 10:
print('A[{}] = {:.1f}'.format(i, vetor[i]))
|
[
"noreply@github.com"
] |
da-ferreira.noreply@github.com
|
bfc11d3a1f557d7017409f177799342afc40ecc8
|
826a8aeb87cb074938b2056ada22c89b9bd9276c
|
/serve.py
|
004adc1f26237b22a69263d9b3e9026761ba3a59
|
[] |
no_license
|
priyom/priyomdb2
|
ce441d755d021c838684aba705b3fb905461ca9f
|
47deecab60febd427af692149788d37cd9f770ba
|
refs/heads/master
| 2020-07-04T01:59:29.506148
| 2014-03-03T11:51:14
| 2014-03-03T11:51:14
| 25,634,647
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,268
|
py
|
#!/usr/bin/python3
if __name__ == "__main__":
import argparse
import logging
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
parser = argparse.ArgumentParser()
parser.add_argument(
"-f", "--app-file",
default="app.wsgi")
parser.add_argument(
"-p", "--port",
type=int,
default=8080)
parser.add_argument(
"-v", "--verbose",
action="count",
dest="verbosity",
default=0)
args = parser.parse_args()
logging.basicConfig(level=logging.ERROR, format='%(levelname)-8s %(message)s')
if args.verbosity >= 3:
logging.getLogger().setLevel(logging.DEBUG)
elif args.verbosity >= 2:
logging.getLogger().setLevel(logging.INFO)
elif args.verbosity >= 1:
logging.getLogger().setLevel(logging.WARNING)
with open(args.app_file, "r") as f:
code = compile(f.read(), args.app_file, 'exec')
locals_dict = {}
exec(code, globals(), locals_dict)
container = tornado.wsgi.WSGIContainer(locals_dict["application"])
server = tornado.httpserver.HTTPServer(container)
server.listen(args.port)
print("serving on port {}".format(args.port))
tornado.ioloop.IOLoop.instance().start()
|
[
"j.wielicki@sotecware.net"
] |
j.wielicki@sotecware.net
|
f7e19b16b6647eb623e4fae8467f79c39b656c7b
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_191/ch78_2020_04_12_20_17_38_556773.py
|
ba021a809518ee7a4dbb3ecf4bc6fe0b3537e17a
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 273
|
py
|
import math
v=True
j={}
while v:
n=input('nome')
if n=='sair':
v=False
else:
a=float(input('acele'))
j[n]=a
l={}
for i,u in j.items():
t=math.sqrt(200/u)
l[i]=t
v=list(l.values())
k=list(l.keys())
print(k[v.index(min(v))],min(v))
|
[
"you@example.com"
] |
you@example.com
|
193ff6392df5dd4435f1d59cf1f51002b58aace6
|
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
|
/python/python_22359.py
|
9f9e50568fed7f7401e8c7ecdc5d72c124a37a6f
|
[] |
no_license
|
AK-1121/code_extraction
|
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
|
5297a4a3aab3bb37efa24a89636935da04a1f8b6
|
refs/heads/master
| 2020-05-23T08:04:11.789141
| 2015-10-22T19:19:40
| 2015-10-22T19:19:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 147
|
py
|
# Python AttributeError: 'module' object has no attribute 'DIST_LT2'
(dist_transform, labels) = cv2.distanceTransform(opening,cv2.cv.CV_DIST_L2,5)
|
[
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] |
ubuntu@ip-172-31-7-228.us-west-2.compute.internal
|
482a8858558f606aab6c71a41ac79a62af32faa4
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03337/s150510433.py
|
fda17f4d3d34cc307fe022e909e277f692423ff1
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 472
|
py
|
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
a,b = I()
print(max(a+b,a-b,a*b))
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
8270b057878ea47f1b8c898a9f6f688170c9102c
|
56d56b40dd7202e07b475b03cebd3d6fb2f58441
|
/safi/app/wsgi/endpoints/subjectchallenges.py
|
eb5290580896381d40f8df878002573a1d23895a
|
[] |
no_license
|
wizardsofindustry/quantum-safi
|
7284db981d14777a46d5372fa0080b1d72d8cd80
|
6c97ae544444e90753e375ecc68f25534d97764a
|
refs/heads/master
| 2020-03-23T03:10:50.171082
| 2018-11-23T21:59:34
| 2018-11-23T21:59:34
| 141,014,467
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,100
|
py
|
import ioc
import sq.interfaces.http
class SubjectChallengesEndpoint(sq.interfaces.http.Endpoint):
"""Deserializes, serializes and validates the structure of the input and output
(requests and response) to its configured URL endpoint, which exposes the
following functionality:
Retrieve the Factors that may be used for interim authentication challenges.
A :class:`SubjectChallengesEndpoint` validates the structure of the request headers,
URL parameters, query parameters and entity prior to forwarding the
request to its handler (controller).
The handler function (e.g., :meth:`~SubjectChallengeCtrl.get()`) may,
instead of a :class:`~sq.interfaces.http.Response` object, return a tuple
or a dictionary. The :class:`SubjectChallengesEndpoint` instance will interpret
these return values as follows:
- If the return value is a :class:`dict`, then the endpoint assumes that
the response code is ``200`` and the object should be included as the
response body, serialized using the default content type. It is
considered an error condition if no serializer is specified for
this content type.
- If the return value is a :class:`tuple` with a length of 2, and the
first element is an :class:`int`, it is considered to hold
``(status_code, body)``.
- Otherwise, for more granular control over the response, a
:class:`~sq.interfaces.http.Response` object may be returned.
If the response body is not a string, it will be serialized using the
best-matching content type in the client ``Accept`` header. If no
match is found, the client receives a ``406`` response.
During serialization, A schema may be selected by :class:`SubjectChallengesEndpoint`
based on the response status code and content type, if one was defined in
the OpenAPI definition for this API endpoint.
"""
pattern = "/factors/<gsid>/challenges"
ctrl = ioc.class_property("SubjectChallengeCtrl")
# pylint: skip-file
# !!! SG MANAGED FILE -- DO NOT EDIT -- VERSION: !!!
|
[
"cochise.ruhulessin@wizardsofindustry.net"
] |
cochise.ruhulessin@wizardsofindustry.net
|
6752105ec117800345237119406cf6949287fc2a
|
c2008671b9902adfd5444607ead35ebe9f33ebda
|
/pico/yay.py
|
6db68296f63d178b98d45e8d08bd67190a30e769
|
[] |
no_license
|
joelburton/secret-pico
|
08fb73e8354dc810656bdfe1fb2c943abfba1fc5
|
0705489798c6ded9d54f785e7c86b3421f6ba87a
|
refs/heads/main
| 2023-03-16T06:50:49.366872
| 2021-03-05T17:08:17
| 2021-03-05T17:08:17
| 343,303,331
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 504
|
py
|
"""Yay!"""
from common import rainbow, oled_page, joel_msg, mark, url
def start():
mark("yay")
oled_page("Yay!")
rainbow()
print("""
You did it! It was fun for me to lead you through this.
And here's a personal message from Joel for you:
--
{joel_msg}
--
You can learn more, as well as get the table of contents for everything, along
with permission to dig into that mysterious envelope, at:
{url}
<3 Pico, Joel, and Fluffy
""".format(joel_msg=joel_msg, url=url("yay")))
|
[
"joel@joelburton.com"
] |
joel@joelburton.com
|
8f8ac91f2bc59a3ba97c42c10fc4c389efdacaca
|
bec623f2fab5bafc95eb5bd95e7527e06f6eeafe
|
/django-shared/private_messages/utils.py
|
bc292ce9750e2ee0c41d087232e5725d000f47c4
|
[] |
no_license
|
riyanhax/a-demo
|
d714735a8b59eceeb9cd59f788a008bfb4861790
|
302324dccc135f55d92fb705c58314c55fed22aa
|
refs/heads/master
| 2022-01-21T07:24:56.468973
| 2017-10-12T13:48:55
| 2017-10-12T13:48:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,069
|
py
|
from django.utils.text import wrap
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
from django.template import Context, loader
from django.template.loader import render_to_string
from django.conf import settings
# favour django-mailer but fall back to django.core.mail
from notification.models import get_from_email
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail
def format_quote(text):
"""
Wraps text at 55 chars and prepends each
line with `> `.
Used for quoting messages in replies.
"""
lines = wrap(text, 55).split('\n')
for i, line in enumerate(lines):
lines[i] = "> %s" % line
return '\n'.join(lines)
def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
template_name="messages/new_message.html",
default_protocol=None,
*args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
``default_protocol``: default protocol in site URL passed to template
"""
if default_protocol is None:
default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, get_from_email(instance.recipient.profile.registered_from),
[instance.recipient.email,])
except Exception, e:
#print e
pass #fail silently
|
[
"ibalyko@ubuntu-server-16-04"
] |
ibalyko@ubuntu-server-16-04
|
17ae827cd8a089e7fe6471407c7d6f3424ac2078
|
41586d36dd07c06860b9808c760e2b0212ed846b
|
/hardware/library/aufs-headers/actions.py
|
98601510ff4ca8e2ec68a21d6b5148f725093a73
|
[] |
no_license
|
SulinOS/SulinRepository
|
4d5551861f57bc1f4bec6879dfe28ce68c7c125d
|
9686811a1e06080f63199233561a922fe1f78d67
|
refs/heads/master
| 2021-06-15T21:34:25.039979
| 2021-06-05T13:43:34
| 2021-06-05T13:43:34
| 207,672,864
| 6
| 3
| null | 2019-12-06T08:11:22
| 2019-09-10T22:16:17
|
Python
|
UTF-8
|
Python
| false
| false
| 450
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Suleyman POYRAZ (Zaryob)
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt.
from inary.actionsapi import autotools
from inary.actionsapi import inarytools
from inary.actionsapi import shelltools
from inary.actionsapi import get
def install():
inarytools.insinto("/usr/include/linux", "include/linux/aufs_type.h")
|
[
"zaryob.dev@gmail.com"
] |
zaryob.dev@gmail.com
|
8002be677ca26279c21afda1f4891664c842fd7f
|
8c7a187ebfe858ff3f840602585d166b29fce576
|
/appstore/translation.py
|
b8994cca4910d34679e424ebbe4ce5c70da3c2d9
|
[] |
no_license
|
ohannes/pythonScripts
|
b756faa2e6d5314cb04c7afc0ca07f69027f59b2
|
5249b2735d8b2a9a2c6ad8a1ae625cb47f50d0b5
|
refs/heads/master
| 2020-04-06T04:20:29.565042
| 2015-07-19T17:40:39
| 2015-07-19T17:40:39
| 34,119,366
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,552
|
py
|
import os
language_yml_path = "/home/arcelik/projects/appstore2.0/server/config/locales"
EOL = "\n"
CR = "\r"
TAB = "\t"
SPACE = " "
skip_characters = [SPACE, TAB, CR, EOL]
file_extension_splitter = "."
yml_extension = "yml"
extension = "translation"
language_code_length = 2
reference_language_code = "en"
reference_language_code2 = "tr"
comment_start_indicator = "#"
label_splitter = ":"
read_mode = "r"
write_mode = "w"
END = "END"
def isNotEmpty(line):
for char in line:
if not char in skip_characters:
return True
return False
def commentStartIndex(line):
try:
index = line.index(comment_start_indicator)
return index
except:
return len(line)
def extractComment(line):
return line[0:commentStartIndex(line)]
def getLabel(line):
label = ""
for char in line:
if char == label_splitter:
break
if not char in skip_characters:
label += char
return label
def extractLabel(line):
return line[line.index(label_splitter)+1:len(line)]
def hasValue(line):
return isNotEmpty(extractLabel(line))
def getDepth(line):
depth = 0
for char in line:
if char != SPACE:
break
depth += 1
return depth/2
def isRealValue(value):
previous_char = "a"
for char in value:
if (char.islower() or char.isupper()) and (previous_char.islower() or previous_char.isupper()):
return True
previous_char = char
return False
def getValue(line):
value = extractLabel(line)
start_index = 0
end_index = len(value) - 1
while value[start_index] in skip_characters:
start_index += 1
while value[end_index] in skip_characters:
end_index -= 1
return value[start_index:end_index+1]
def searchFile(file_name):
ftr = open(file_name, read_mode)
previous_depth = -1
previous_label = ""
ftw = open(file_name + file_extension_splitter + extension, write_mode)
while True:
line = ftr.readline()
if not line:
break
if isNotEmpty(line):
line = extractComment(line)
if isNotEmpty(line):
depth = getDepth(line)
label = getLabel(line)
if hasValue(line):
value = getValue(line)
if isRealValue(value):
#print depth, label, value
ftw.write(str(depth) + TAB + label + TAB + value + EOL)
ftr.close()
ftw.close()
os.chdir(language_yml_path)
yml_files = os.listdir(os.getcwd())
language_codes = []
for yml_file in yml_files:
language_code = yml_file.split(file_extension_splitter)[0]
if len(language_code) == language_code_length:
language_codes.append(language_code)
for language_code in language_codes:
searchFile(language_code + file_extension_splitter + yml_extension)
|
[
"yasinyildiza@gmail.com"
] |
yasinyildiza@gmail.com
|
2d08fab219857c1c78989b15f11f4bad4e48c065
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_expedited.py
|
7d2b6ebd4dc9da31f59bc5114301568600ec3d23
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 230
|
py
|
#calss header
class _EXPEDITED():
def __init__(self,):
self.name = "EXPEDITED"
self.definitions = expedite
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['expedite']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
195342a7a8d19ad4d68a02c17a005b456d2aeceb
|
0a42fed6746cd9093fc3c3d4fbd7ac5d2cff310f
|
/python高级编程io/study07/code01_ORM_test.py
|
918a9b4bd5423b334ab34b3fbb20d8b68d656220
|
[] |
no_license
|
luoshanya/Vue_Study
|
4767fc46f2186c75a4b2f7baeeb2fcc9044bd9a4
|
d3a07364a63f0552b166a5697a7245f56e38e78d
|
refs/heads/master
| 2020-06-19T02:15:20.253362
| 2019-07-17T08:49:48
| 2019-07-17T08:49:48
| 196,529,016
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,630
|
py
|
import numbers
import pymysql
class Filed:
pass
class IntField(Filed):
def __init__(self, db_column, min_value=None, max_value=None):
self._value = None
self.min_value = min_value
self.max_value = max_value
self.db_column = db_column
if min_value is not None:
if not isinstance(min_value, numbers.Integral):
raise ValueError('this value attr must to int')
elif min_value < 0:
raise ValueError('this value must bigger than zero')
elif max_value is not None:
if not isinstance(min_value, numbers.Integral):
raise ValueError('this value attr must to int')
elif min_value < 0:
raise ValueError('this value must bigger than zero')
elif min_value and max_value is not None:
if min_value > max_value:
raise ValueError('min_value must be smaller than max_value')
# 数据描述符
def __get__(self, instance, owner):
# 这里的self.value是set的
return self._value
def __set__(self, instance, value):
if not isinstance(value, numbers.Integral):
raise ValueError('this value attr must be int')
elif value < self.min_value or value > self.max_value:
raise ValueError('value must between min_value and max_length')
self._value = value
class CharField(Filed):
def __init__(self, db_column, max_length=None):
self.value = None
self.max_length = max_length
self.db_column = db_column
if self.max_length is None:
raise ValueError('max_length not must be None')
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
if not isinstance(value, str):
raise ValueError('this value attr must be str')
elif len(value) > self.max_length:
raise ValueError('value is length must be smaller than max_length ')
self._value = value
# 创建元类
class ModelMateClass(type):
def __new__(cls, name, bases, attrs, **kwargs):
if name == 'BasesModel':
super().__new__(cls, name, bases, attrs, **kwargs)
field = {}
for key, value in attrs.items():
#首先创建一个类来判断字段
if isinstance(value, Filed):
field[key] = value
attr_meta = attrs.get('Meta', None)
_meta = {}
db_table = name.lower()
if db_table is not None:
table = getattr(attr_meta, "db_table", None)
if table is not None:
db_table = table
_meta['db_table'] = db_table
attrs['_meta'] = _meta
attrs['field'] = field
# del attrs['Meta']
return super().__new__(cls, name, bases, attrs, **kwargs)
# return super().__new__()
class BasesModel(metaclass=ModelMateClass):
# 在传参不确定的情况下 使用*args **kwargs
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
# 实例化
return super().__init__()
def save(self):
fields = []
values = []
for key, value in self.field.items():
db_column = value.db_column
if db_column is None:
db_column = key.lower()
fields.append(db_column)
value = getattr(self, key)
# 这里必须将value转str
values.append(str(value))
sql = 'insert into {table_name}({fields}) value("{name}",{age})'.format(table_name=self._meta['db_table'], fields=','.join(fields), name=",".join(values).split(',')[0], age=",".join(values).split(',')[1])
dbparams = {
'host': "127.0.0.1",
'port': 3306,
'db': "test",
'user': "root",
'password': "10130503",
'charset': "utf8"
}
conn = pymysql.Connect(**dbparams)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
class User(BasesModel):#调用的话,继承的关系= 会直接找到父类
# 本来这里是需要实例化来对应用户的操作 那就需要重新创建一个类来继承
# def __init__(self):
name = CharField(db_column='name', max_length=10)
age = IntField(db_column='age', min_value=1, max_value=200)
class Meta:
db_table = 'user'
if __name__ == '__main__':
user = User(name='猪', age=100)
# user.name = 1
# user.age = 300
user.save()
|
[
"310927880@qq.com"
] |
310927880@qq.com
|
c5bc92e292c60a7a58f74a7e71291cac3968bfc8
|
1aeb828e57be9b046ee25433fff05956f01db53b
|
/python_bms/ALGORITHMS/SWEA/SWEA_d2/1986.지그재그숫자.py
|
00ecd7e2ed3f2062c756fb5f7c20c59c9c54153c
|
[] |
no_license
|
LynnYeonjuLee/TIL_BMS2
|
11f2753e2e82c4898a782d6907a21e973c34cf69
|
f363723391598caf5ec6b33925fcb8a13a252d9f
|
refs/heads/master
| 2023-01-22T00:45:25.091512
| 2020-12-04T00:22:44
| 2020-12-04T00:22:44
| 290,238,836
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 234
|
py
|
T = int(input())
for test_case in range(1, T+1):
N = int(input())
result = 0
for i in range(1, N+1):
if i % 2 == 1:
result += i
else:
result -= i
print(f'#{test_case} {result}')
|
[
"lynnlyj9@gmail.com"
] |
lynnlyj9@gmail.com
|
75d4d2d5cd7f43565d0f937dec45d592a73eaed0
|
2442d073434d463cede4a79ae8f9fd31c62174f8
|
/procedural-programming/exceptions/name-error.py
|
832f2844420c2a3aed590e3ddd8ab52153adc4d3
|
[] |
no_license
|
grbalmeida/hello-python
|
3630d75cfdde15223dc1c3a714fd562f6cda0505
|
4d9ddf2f7d104fdbc3aed2c88e50af19a39c1b63
|
refs/heads/master
| 2020-07-10T10:04:38.982256
| 2020-02-26T00:37:36
| 2020-02-26T00:37:36
| 204,237,527
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 199
|
py
|
try:
print(nonexistent_variable)
except NameError as error:
print(error.args)
print(f'The variable was not set: {error}')
else:
print('The code was executed without throwing any exceptions')
|
[
"g.r.almeida@live.com"
] |
g.r.almeida@live.com
|
afb8519068bdf6411c8ce24d687543a19994b39f
|
e38f7b5d46fd8a65c15e49488fc075e5c62943c9
|
/pychron/canvas/tasks/designer.py
|
43aed5471b6e5e63fc8030de8446c425a50ab10d
|
[] |
no_license
|
INGPAN/pychron
|
3e13f9d15667e62c347f5b40af366096ee41c051
|
8592f9fc722f037a61b0b783d587633e22f11f2f
|
refs/heads/master
| 2021-08-15T00:50:21.392117
| 2015-01-19T20:07:41
| 2015-01-19T20:07:41
| 111,054,121
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,887
|
py
|
#===============================================================================
# Copyright 2013 Jake Ross
#
# 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.
#===============================================================================
#============= enthought library imports =======================
import os
from traits.api import HasTraits, Instance
#============= standard library imports ========================
#============= local library imports ==========================
from pychron.canvas.canvas2D.designer_extraction_line_canvas2D import DesignerExtractionLineCanvas2D
from pychron.canvas.canvas2D.extraction_line_canvas2D import ExtractionLineCanvas2D
from pychron.canvas.canvas2D.scene.canvas_parser import CanvasParser
from pychron.canvas.canvas2D.scene.extraction_line_scene import ExtractionLineScene
from pychron.canvas.canvas2D.scene.primitives.valves import Valve
class Designer(HasTraits):
scene = Instance(ExtractionLineScene, ())
canvas = Instance(ExtractionLineCanvas2D)
def _canvas_default(self):
canvas = DesignerExtractionLineCanvas2D()
return canvas
def save_xml(self, p):
if self.scene:
# sync the canvas_parser with the
# current scene and save
if os.path.isfile(p):
self._save_xml(p)
else:
self._construct_xml()
def _save_xml(self, p):
cp = CanvasParser(p)
for tag in ('laser', 'stage', 'spectrometer'):
for ei in cp.get_elements(tag):
self._set_element_color(ei)
self._set_element_translation(ei)
for ei in cp.get_elements('valve'):
self._set_element_translation(ei)
for ei in cp.get_elements('connection'):
name = ei.text.strip()
obj = self.scene.get_item(name)
if obj.clear_orientation:
ei.set('orientation', '')
p = os.path.join(os.path.dirname(p, ), 'test.xml')
cp.save()
def _set_element_translation(self, elem):
def func(obj, trans):
trans.text = '{},{}'.format(obj.x, obj.y)
self._set_element_attr(func, elem, 'translation')
def _set_element_color(self, elem):
def func(obj, color):
if color is not None:
c = ','.join(map(lambda x: str(x),
obj.default_color.toTuple()
))
color.text = c
self._set_element_attr(func, elem, 'color')
def _set_element_attr(self, func, elem, tag):
name = elem.text.strip()
obj = self.scene.get_item(name)
if obj is not None:
func(obj, elem.find(tag))
def _construct_xml(self):
tags = {Valve: 'valve'}
cp = CanvasParser()
for elem in self.scene.iteritems():
if type(elem) in tags:
tag = tags[type(elem)]
print tag, elem
elif hasattr(elem, 'type_tag'):
print elem.type_tag, elem
def open_xml(self, p):
#cp=CanvasParser(p)
#print cp
scene = ExtractionLineScene(canvas=self.canvas)
self.canvas.scene = scene
cp = os.path.join(os.path.dirname(p), 'canvas_config.xml')
scene.load(p, cp)
self.scene = scene
#============= EOF =============================================
|
[
"jirhiker@gmail.com"
] |
jirhiker@gmail.com
|
ad5d8cd83f719b59a3793b8bfcbfda33cd7f65b0
|
095521582f598b65b76f222d8c1acbcaca0c24bf
|
/output_raw/output_input_Lx1Ly3.py
|
db4de0907eb008061450f4a61a6d47971d67167b
|
[
"MIT"
] |
permissive
|
ryuikaneko/itps_contraction
|
cf07e41d32e93c10db6ebeb1c4f5246b238e737b
|
10816fb6c90d77f5a3b2f804ab22573d1d676eb4
|
refs/heads/master
| 2020-08-28T23:05:00.262183
| 2020-08-03T01:04:22
| 2020-08-03T01:04:22
| 217,847,703
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,511
|
py
|
def Contract_scalar_1x3(\
t0_4,t1_4,t2_4,\
t0_3,t1_3,t2_3,\
t0_2,t1_2,t2_2,\
t0_1,t1_1,t2_1,\
t0_0,t1_0,t2_0,\
o1_3,\
o1_2,\
o1_1\
):
##############################
# ./input/input_Lx1Ly3.dat
##############################
# (o1_2*(t1_2*((t2_2*(t2_1*(t1_1*((o1_1*t1_1.conj())*(t0_1*(t0_0*(t2_0*t1_0)))))))*(t1_2.conj()*(t0_2*(t0_3*(t1_3*((o1_3*t1_3.conj())*(t2_3*(t0_4*(t2_4*t1_4)))))))))))
# cpu_cost= 1.804e+11 memory= 5.0206e+08
# final_bond_order ()
##############################
return np.tensordot(
o1_2, np.tensordot(
t1_2, np.tensordot(
np.tensordot(
t2_2, np.tensordot(
t2_1, np.tensordot(
t1_1, np.tensordot(
np.tensordot(
o1_1, t1_1.conj(), ([1], [4])
), np.tensordot(
t0_1, np.tensordot(
t0_0, np.tensordot(
t2_0, t1_0, ([1], [0])
), ([0], [1])
), ([0], [0])
), ([1, 4], [2, 5])
), ([0, 3, 4], [4, 6, 0])
), ([1, 2, 3], [5, 1, 3])
), ([1], [0])
), np.tensordot(
t1_2.conj(), np.tensordot(
t0_2, np.tensordot(
t0_3, np.tensordot(
t1_3, np.tensordot(
np.tensordot(
o1_3, t1_3.conj(), ([1], [4])
), np.tensordot(
t2_3, np.tensordot(
t0_4, np.tensordot(
t2_4, t1_4, ([0], [1])
), ([1], [1])
), ([0], [1])
), ([2, 3], [5, 2])
), ([1, 2, 4], [6, 4, 0])
), ([1, 2, 3], [5, 0, 2])
), ([1], [0])
), ([0, 1], [2, 4])
), ([0, 2, 4, 5], [6, 0, 1, 3])
), ([0, 1, 2, 3], [3, 4, 0, 1])
), ([0, 1], [0, 1])
)
|
[
"27846552+ryuikaneko@users.noreply.github.com"
] |
27846552+ryuikaneko@users.noreply.github.com
|
6f587046be7066cad70382b794003f17a416b0aa
|
6515dee87efbc5edfbf4c117e262449999fcbb50
|
/eet/Pacific_Atlantic_Water_Flow.py
|
b5b510ce650e4d832898d5e4641d865557b67c63
|
[] |
no_license
|
wangyunge/algorithmpractice
|
24edca77e180854b509954dd0c5d4074e0e9ef31
|
085b8dfa8e12f7c39107bab60110cd3b182f0c13
|
refs/heads/master
| 2021-12-29T12:55:38.096584
| 2021-12-12T02:53:43
| 2021-12-12T02:53:43
| 62,696,785
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,101
|
py
|
"""
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
"""
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
|
[
"wangyunge1@yahoo.com"
] |
wangyunge1@yahoo.com
|
262a0db07ed6e9da60628477540a51c51d4cdb30
|
7365f2410c139c5f4bf5ba0777ed0321322c92d9
|
/python/数组中只出现一次的数字.py
|
bf189f784d5f0e385008e6c963df8d84172acffe
|
[] |
no_license
|
EvanJamesMG/Point-to-the-offer
|
956a17a3c2a0d99a11428765f6af9f4ebbbe5fc3
|
cc9b6b7572cf819f0e53a800899e1ebd9fd6cf9d
|
refs/heads/master
| 2021-01-10T17:11:06.125860
| 2016-04-21T03:47:15
| 2016-04-21T03:47:15
| 52,489,364
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,098
|
py
|
# coding=utf-8
__author__ = 'EvanJames'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
'''
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
利用haspmap
'''
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
if array == None or len(array) <= 1:
return [0, 0]
map = {}
res = []
for i in range(len(array)):
if array[i] in map:
map.pop(array[i])
else:
map[array[i]] = 1
for i in map:
res.append(i)
return res
if __name__ == '__main__':
res = Solution().FindNumsAppearOnce([1, 2, 3, 3, 2, 4])
print(res)
|
[
"Evan123mg@gmail.com"
] |
Evan123mg@gmail.com
|
a5d12bb6d61ae83e3e28dc74139590146591a395
|
09f8a3825c5109a6cec94ae34ea17d9ace66f381
|
/cohesity_management_sdk/models/filter_ip_config.py
|
599025d68f0a892418ff10e71716b77276675c3d
|
[
"Apache-2.0"
] |
permissive
|
cohesity/management-sdk-python
|
103ee07b2f047da69d7b1edfae39d218295d1747
|
e4973dfeb836266904d0369ea845513c7acf261e
|
refs/heads/master
| 2023-08-04T06:30:37.551358
| 2023-07-19T12:02:12
| 2023-07-19T12:02:12
| 134,367,879
| 24
| 20
|
Apache-2.0
| 2023-08-31T04:37:28
| 2018-05-22T06:04:19
|
Python
|
UTF-8
|
Python
| false
| false
| 2,058
|
py
|
# -*- coding: utf-8 -*-
# Copyright 2023 Cohesity Inc.
class FilterIpConfig(object):
"""Implementation of the 'FilterIpConfig' model.
Specifies the list of IP addresses that are allowed or denied at the job
level. Allowed IPs and Denied IPs cannot be used together.
Attributes:
allowed_ip_addresses (list of string): Specifies the IP addresses that
should be used exclusively at the job level. Cannot be set if
deniedIpAddresses is set.
denied_ip_addresses (list of string): Specifies the IP addresses that
should not be used at the job level. Cannot be set if
allowedIpAddresses is set.
"""
# Create a mapping from Model property names to API property names
_names = {
"allowed_ip_addresses":'allowedIpAddresses',
"denied_ip_addresses":'deniedIpAddresses',
}
def __init__(self,
allowed_ip_addresses=None,
denied_ip_addresses=None,
):
"""Constructor for the FilterIpConfig class"""
# Initialize members of the class
self.allowed_ip_addresses = allowed_ip_addresses
self.denied_ip_addresses = denied_ip_addresses
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
allowed_ip_addresses = dictionary.get("allowedIpAddresses")
denied_ip_addresses = dictionary.get("deniedIpAddresses")
# Return an object of this model
return cls(
allowed_ip_addresses,
denied_ip_addresses
)
|
[
"naveena.maplelabs@cohesity.com"
] |
naveena.maplelabs@cohesity.com
|
6a9a4b92daa1da9160d1d1440fa87b2c6ff94510
|
4cf652ee4168f6f728d4ad86a9df13fd3431fd98
|
/DynamicProgramming/perfect-squares.py
|
66193dfcb8ff4d53f8769187374993dfe945a26b
|
[] |
no_license
|
jadenpadua/Foundation
|
73940b73720a3e84f46502797a02fa19117b653c
|
042a83177e8cce7291c9b31b54b3d71e4d4c9696
|
refs/heads/master
| 2023-03-07T03:20:21.546843
| 2021-02-16T23:16:43
| 2021-02-16T23:16:43
| 286,326,064
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 364
|
py
|
class Solution:
def numSquares(self, n: int) -> int:
dp = [0] *(n+1)
for i in range(1, n+1):
min_val = i
j, sq = 1,1
while sq <= i:
min_val = min(min_val, 1 + dp[i-sq])
j += 1
sq = j*j
dp[i] = min_val
return dp[n]
|
[
"noreply@github.com"
] |
jadenpadua.noreply@github.com
|
d26cece290c619bc7a5ac2689dfeb990b05579af
|
10aefc154e740941a9b340f471b785739280fc93
|
/May2020/1st_week/reverse_int.py
|
e8da53f0c7436c79be3d129f843d5e3032f765cd
|
[] |
no_license
|
saurabh-kumar88/leetcode
|
465b9eaa7d844eba21c3bc4e9cc1e3348c75c037
|
282b270c1a97bc726b835f8288fdb898a8d0c81c
|
refs/heads/master
| 2022-12-04T13:13:32.144792
| 2020-08-21T14:54:24
| 2020-08-21T14:54:24
| 280,216,966
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 602
|
py
|
class Solution:
def reverse(self, x: int) -> int:
# check if number is greater then 32 bit
if x < -(2**31) or x > (2**31) -1:
return 0
string = str(x)
if x < 0:
result = int("-" + str(-x)[::-1])
else:
result = int(string[::-1])
# Again check 32 bit limit for reversed number
if result < -(2**31) or result > (2**31) -1:
return 0
else:
return result
string = "-123"
if __name__ == "__main__":
obj = Solution()
z = obj.reverse(1534236469)
print(z)
|
[
"ykings.saurabh@gmail.com"
] |
ykings.saurabh@gmail.com
|
9b5c50da6072d37a8bab42e3f2baa02890590e25
|
77741ac3384cf80ba9f5684f896e4b6500064582
|
/PycharmProjects/模块、包、异常/04-捕获异常信息.py
|
67d9c93ccddcea9b796f7cc827d2ccf9e5016259
|
[
"MIT"
] |
permissive
|
jiankangliu/baseOfPython
|
9c02763b6571596844ee3e690c4d505c8b95038d
|
a10e81c79bc6fc3807ca8715fb1be56df527742c
|
refs/heads/master
| 2020-05-09T12:11:02.314281
| 2019-04-13T01:17:24
| 2019-04-13T01:17:24
| 181,104,243
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 376
|
py
|
# print(num) # NameError
# 捕获异常类型
# try:
# print(num)
# # print(1/0)
# # except ZeroDivisionError:
# except NameError as e:
# print(e)
# try:
# # print(num)
# print(1/0)
# except ZeroDivisionError as e:
# # except NameError as e:
# print(e)
try:
print(1 / 0)
print(num)
except Exception as e:
print(e)
|
[
"xwp_fullstack@163.com"
] |
xwp_fullstack@163.com
|
3713d0ee0e3afed4e3607b6ad33354ee81071a6e
|
4331b28f22a2efb12d462ae2a8270a9f666b0df1
|
/.history/dvdstore/webapp/views_20190914133048.py
|
615e3723c4902560ba9ac1776831448b19fbf81a
|
[] |
no_license
|
ZiyaadLakay/csc312.group.project
|
ba772a905e0841b17478eae7e14e43d8b078a95d
|
9cdd9068b5e24980c59a53595a5d513c2e738a5e
|
refs/heads/master
| 2020-07-26T23:30:22.542450
| 2019-09-16T11:46:41
| 2019-09-16T11:46:41
| 200,703,160
| 0
| 0
| null | 2019-08-05T17:52:37
| 2019-08-05T17:52:37
| null |
UTF-8
|
Python
| false
| false
| 6,307
|
py
|
from django.shortcuts import render
from .models import DVD, Transaction, Customer
from django.core.paginator import EmptyPage,PageNotAnInteger, Paginator
from django.db.models import Q
from django.contrib.auth.models import User, auth
from django.shortcuts import render, redirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.contrib.auth.decorators import login_required, permission_required
from .form import DocumentForm
import datetime
#This is the homepage for the User
def home(request):
dvds = DVD.objects.all() #imports dvds from database
query = request.GET.get("query")
gen = request.GET.get("gen")
if query:
dvds = DVD.objects.filter(Q(Title__icontains=query))#Search Function according to name
if not DVD.objects.filter(Q(Title__icontains=query)).exists():
messages.info(request,'No search results for : '+query)
elif gen:
dvds = DVD.objects.filter(Q(genre__icontains=gen))#Search Function according to name
paginator = Paginator(dvds, 6) # Show 3 dvds per page
page = request.GET.get('page')
dvds = paginator.get_page(page)
genre = {'Action', 'Comedy', 'Drama', 'Family', 'Romance'}
return render(request, 'home.html', {'dvds':dvds}, {'genre':genre}) #renders the page
#This is the page for clerks
@login_required
def clerk(request):
dvds = DVD.objects.all() #imports dvds from database
trans = Transaction.objects.all() #imports dvds from database
users = User.objects.all() #imports dvds from database
customer = Customer.objects.all() #imports dvds from database
query = request.GET.get("query")
if query:
dvds = DVD.objects.filter(Q(Title__icontains=query)) #Search Function according to name
paginator = Paginator(dvds, 6) # Show 3 dvds per page
page = request.GET.get('page')
dvds = paginator.get_page(page)
form=DocumentForm()
context_dict = { 'dvds':dvds ,'form': form, 'trans':trans, 'users':users, 'customer':customer}
return render(request, 'clerk.html',context_dict)
@login_required
def userstbl(request):
dvds = DVD.objects.all() #imports dvds from database
trans = Transaction.objects.all() #imports dvds from database
users = User.objects.all() #imports dvds from database
customer = Customer.objects.all() #imports dvds from database
query = request.GET.get("query")
if query:
users = User.objects.filter(Q(username__icontains=query)) #Search Function according to name
paginator = Paginator(dvds, 6) # Show 3 dvds per page
page = request.GET.get('page')
dvds = paginator.get_page(page)
form=DocumentForm()
context_dict = { 'dvds':dvds ,'form': form, 'trans':trans, 'users':users, 'customer':customer}
return render(request, 'userstbl.html',context_dict)
@login_required
def transactions(request):
dvds = DVD.objects.all() #imports dvds from database
trans = Transaction.objects.all() #imports dvds from database
users = User.objects.all() #imports dvds from database
customer = Customer.objects.all() #imports dvds from database
query = request.GET.get("query")
if query:
trans = Transaction.objects.filter(Q(TransactionNumber__icontains=query)) #Search Function according to name
paginator = Paginator(dvds, 6) # Show 3 dvds per page
page = request.GET.get('page')
dvds = paginator.get_page(page)
form=DocumentForm()
context_dict = { 'dvds':dvds ,'form': form, 'trans':trans, 'users':users, 'customer':customer}
return render(request, 'transactions.html',context_dict)
def register2(request):
if request.method == 'POST':
first_name= request.POST['first_name']
last_name= request.POST['last_name']
username= request.POST['username']
email= request.POST['email']
password1= first_name[0]+last_name
if User.objects.filter(username=username).exists():
messages.info(request, 'Username Taken')
return redirect('clerk')
elif User.objects.filter(email=email).exists():
messages.info(request, 'Email Taken')
user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
user.save()
messages.info(request, 'User Created')
return redirect('/clerk')
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/clerk')
def booking(request):
username= request.POST['username']
dvdID= request.POST['dvdID']
DVD.objects.filter(id=dvdID).update(BookingPickup=username)
return redirect('home')
def checkout(request):
dvdID= request.POST['dvdID']
numOfDays=request.POST['numDaysBooked']
dvdPrice=request.POST['dvdPrice']
users_ID=request.POST['user_ID']
MovieTitle=request.POST['MovieTitle']
payment=request.POST['payment']
bill=int(numOfDays)*int(dvdPrice)
DVD.objects.filter(id=dvdID).update(NumDaysBooked=numOfDays,InStock=False)
RentDate= datetime.date.today()
DueDate=RentDate+datetime.timedelta(days=int(numOfDays))
t = datetime.datetime.now().strftime("%H%M%S")
TransactionNumber=payment+str(RentDate)[0:4]+str(RentDate)[8:10]+t
#Amount
trans = Transaction(users_ID=users_ID, TransactionNumber=TransactionNumber, RentDate=RentDate, DueDate=DueDate, MovieTitle=MovieTitle, Payment_Method=payment,Amount="R"+str(bill),dvdID=dvdID)
trans.save()
return redirect('/clerk')
def checkin(request):
dvdID= request.POST['dvdID']
DVD.objects.filter(id=dvdID).update(BookingPickup='None',InStock=True,NumDaysBooked=0)
return redirect('/clerk')
def deleteMovie(request):
dvdID= request.POST['dvdID']
DVD.objects.filter(id=dvdID).delete()
return redirect('/clerk')
def deleteTransaction(request):
transID= request.POST['transID']
Transaction.objects.filter(id=transID).delete()
return redirect('/transactions')
def deleteUser(request):
userID= request.POST['userID']
User.objects.filter(id=userID).delete()
return redirect('/userstbl')
|
[
"uzairjoneswolf@gmail.com"
] |
uzairjoneswolf@gmail.com
|
055318a7275ecbf68596296f9cb1e45c5239ea9f
|
c0ce40b948129cd1d293bb024649d103348b30a4
|
/tkinter_demo2.py
|
3775dd3054875a5bb3f456f9ead8512748209608
|
[] |
no_license
|
BrettMcGregor/udemy-python-tim
|
ee6dc2882b57cd05f9df433459917e2ae6f05cd1
|
fd4e3368987740491a802cab7ce469db5b528505
|
refs/heads/master
| 2020-03-11T17:05:38.268836
| 2018-07-11T23:11:04
| 2018-07-11T23:11:04
| 130,137,368
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,328
|
py
|
# this uses the grid configuration
import tkinter
# print(tkinter.TkVersion)
# print(tkinter.TclVersion)
#
# tkinter._test()
main_window = tkinter.Tk()
main_window.title("Country Destroyer")
main_window.geometry("640x480+8+200")
label = tkinter.Label(main_window, text="Choose a country to destroy.\n(Important: Cannot be undone)")
label.grid(row=0, column=0)
left_frame = tkinter.Frame(main_window)
left_frame.grid(row=1, column=1)
canvas = tkinter.Canvas(left_frame, relief="raised", borderwidth=1)
canvas.grid(row=1, column=0)
right_frame = tkinter.Frame(main_window)
right_frame.grid(row=1, column=2, sticky="n")
button1 = tkinter.Button(right_frame, text="Iran")
button2 = tkinter.Button(right_frame, text="Russia")
button3 = tkinter.Button(right_frame, text="Syria")
button1.grid(row=0, column=0)
button2.grid(row=1, column=0)
button3.grid(row=2, column=0)
# configure columns
main_window.columnconfigure(0, weight=1)
main_window.columnconfigure(1, weight=1)
main_window.grid_columnconfigure(2, weight=1)
left_frame.config(relief="sunken", borderwidth=1)
right_frame.config(relief="sunken", borderwidth=1)
left_frame.grid(sticky="ns")
right_frame.grid(sticky="new")
right_frame.columnconfigure(0, weight=1)
button1.grid(sticky="ew")
button2.grid(sticky="ew")
button3.grid(sticky="ew")
main_window.mainloop()
|
[
"brett.w.mcgregor@gmail.com"
] |
brett.w.mcgregor@gmail.com
|
682e8bc78b5df1311583a636f8d185ddbcf42c35
|
a33a1490b1b344f603e347e7f2db2daab5a23d32
|
/components/app_outputs/chain_flow_assembler/system_definition.py
|
3ea53efff4ee2d2136f036878e91f878fba07eb4
|
[
"MIT"
] |
permissive
|
glenn-edgar/esp32_gateway
|
16fabe8c4e937d9d98ca825ad28275b1c3ede6a7
|
5dc4a65eeb2226b6a6529c91a5491df7080b853f
|
refs/heads/master
| 2020-03-26T12:10:03.555424
| 2019-02-21T22:54:39
| 2019-02-21T22:54:39
| 144,878,278
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 982
|
py
|
from helper_functions import Helper_Functions
from assembler import CF_Assembler
cf = CF_Assembler()
hf = Helper_Functions( cf )
cf.define_chain("initialization",True)
hf.one_step("analog_output_store_cf_handle_ref")
hf.one_step("analog_output_subscribe_configuration")
hf.one_step("analog_output_subscribe_output")
hf.one_step("analog_output_subscribe_pulse_output")
hf.one_step("add_watch_dog")
hf.wait( "wait_for_mqtt_connect" )
hf.enable_chain( "pulse_task")
hf.terminate() #initialization is done now disable the chain
cf.end_chain()
#These chains are for actions every second
cf.define_chain("feed_watch_dog", True )
hf.wait_event("CF_SECOND_TICK")
hf.one_step("pat_watch_dog")
hf.reset()
cf.end_chain()
cf.define_chain("pulse_task",False)
hf.wait_event("CF_PULSE_EVENT")
hf.one_step("analog_output_set_initial_value")
hf.wait("analog_output_step_timer")
hf.one_step("analog_output_set_final_value")
hf.reset()
cf.end_chain()
cf.generate_c_header()
|
[
"glenn-edgar@onyxengr.com"
] |
glenn-edgar@onyxengr.com
|
8d73df9c54e5b8fc70e96d319792bc44f407983d
|
7d117771094a24bc411ec8d5a7b8525a5b85b018
|
/ninfo_plugins/google_safebrowsing/google_safebrowsing_plugin.py
|
fdf9a34ee3d85a5cecf0a8b3fc774763ca184c82
|
[] |
no_license
|
kraigu/ninfo_plugins
|
18ca1be940101a5d5f863320c53a0cd7cc80efce
|
746cc48567036337763e888f913f3a4321f166d3
|
refs/heads/master
| 2021-01-18T06:36:08.108586
| 2013-09-19T16:06:25
| 2013-09-19T16:06:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,107
|
py
|
import urllib
import requests
from ninfo import PluginBase
class SafeBrowsing(PluginBase):
"""This plugin looks up the address using the google safe browsing API"""
name = 'google_safebrowsing'
title = 'Google Safe Browsing'
description = 'Google Safe Browsing check'
cache_timeout = 60*60
types = ['ip','ip6','hostname']
local = False
def setup(self):
api_key = self.plugin_config['api_key']
self.base_url = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=ninfo&apikey=%s&appver=1.5.2&pver=3.0" % api_key
def get_info(self, arg):
url = self.base_url + "&url=" + urllib.quote(arg)
resp = requests.get(url)
if resp.status_code == 204:
return {}
status = resp.text
return { 'status': status}
def render_template(self, output_type, arg, result):
if not result:
return ''
if output_type == 'text':
return result['status']
else:
return '<pre>%s</pre>' % result['status']
plugin_class = SafeBrowsing
|
[
"justin@bouncybouncy.net"
] |
justin@bouncybouncy.net
|
7625a230d83e667833e77845ff3774f296eff5a9
|
08607218396a0269a90e8b4e6d099a5e99e39a8b
|
/database/schemes/520/script/testCase/U商城项目/U商城管理端/商城设置/邮件配置/邮件配置.py
|
ab4610a6db1d39606a04c5f3d9dbf57d04b89f88
|
[
"MIT"
] |
permissive
|
TonnaMajesty/test
|
4a07297557669f98eeb9f94b177a02a4af6f1af0
|
68b24d1f3e8b4d6154c9d896a7fa3e2f99b49a6f
|
refs/heads/master
| 2021-01-19T22:52:18.309061
| 2017-03-06T10:51:05
| 2017-03-06T10:51:05
| 83,779,681
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,084
|
py
|
# coding=utf-8
from time import sleep
from SRC.common import utils_user
from SRC.common.decorator import codeException_dec
from SRC.common.utils_user import randomStr
from SRC.unittest.case import TestCase
from script.common import utils
class EasyCase(TestCase):
def __init__(self, webDriver, paramsList):
# 请不要修改该方法
super(EasyCase, self).__init__(webDriver, paramsList)
@codeException_dec('3')
def runTest(self):
driver = self.getDriver()
param = self.param
tool = utils_user
driver.get('http://upmalldemo.yonyouup.com/corp/')
driver.find_element_by_css_selector('body > div.container.corp-page.ng-scope > div > div.col-xs-2.corp-mune.noprint > ul:nth-child(8) > li.title.pointer').click() # 点击商城设置
driver.find_element_by_css_selector('body > div.container.corp-page.ng-scope > div > div.col-xs-2.corp-mune.noprint > ul:nth-child(8) > li:nth-child(5) > a').click() # 点击邮件配置
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[1]/div/input').clear()
AA='.'.join([randomStr(2) for _ in range(4)])
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[1]/div/input').send_keys(AA) # 输入服务器地址
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[2]/div/input').clear()
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[2]/div/input').send_keys(u'25') # 输入服务器端口
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[3]/div/input').clear()
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[3]/div/input').send_keys(u'876317070@qq.com') # 输入发件人邮箱
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[4]/div/input').clear()
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[4]/div/input').send_keys(u'123456')
driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/form/div[6]/div/button[2]').click() # 点击保存
sleep(3)
|
[
"1367441805@qq.com"
] |
1367441805@qq.com
|
79bbfeded34d7846b0dbd38c449856cccf9fbf93
|
5ec7d0bad8a77c79843a2813f5effcb3a2b7e288
|
/tests/test_main.py
|
ffea5974434e9311dd3cf5d9a101028cc1cd9e96
|
[
"Apache-2.0"
] |
permissive
|
xdpknx/lean-cli
|
aca9b9c9c4e156c9faefcfa8ccdfc20423b510a0
|
c1051bd3e8851ae96f6e84f608a7116b1689c9e9
|
refs/heads/master
| 2023-08-08T02:30:09.827647
| 2021-09-21T21:36:24
| 2021-09-21T21:36:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,387
|
py
|
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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.
from click.testing import CliRunner
from lean.commands import lean
def test_lean_shows_help_when_called_without_arguments() -> None:
result = CliRunner().invoke(lean, [])
assert result.exit_code == 0
assert "Usage: lean [OPTIONS] COMMAND [ARGS]..." in result.output
def test_lean_shows_help_when_called_with_help_option() -> None:
result = CliRunner().invoke(lean, ["--help"])
assert result.exit_code == 0
assert "Usage: lean [OPTIONS] COMMAND [ARGS]..." in result.output
def test_lean_shows_error_when_running_unknown_command() -> None:
result = CliRunner().invoke(lean, ["this-command-does-not-exist"])
assert result.exit_code != 0
assert "No such command" in result.output
|
[
"jaspervmerle@gmail.com"
] |
jaspervmerle@gmail.com
|
50dff405b181b454abda8be27a8b50fe2ebcce82
|
c67831f476cb530fc0c26e0bf4258ce18e986749
|
/module_index/tests.py
|
d40565133c9787f282d39d67ff2417b2a4fb2303
|
[
"MIT"
] |
permissive
|
cz-qq/bk-chatbot
|
a3ce4b86452b3de0ff35430c1c85b91d6b23a3e6
|
da37fb2197142eae32158cdb5c2b658100133fff
|
refs/heads/master
| 2023-06-05T05:48:22.083008
| 2021-06-15T10:21:30
| 2021-06-15T10:21:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 757
|
py
|
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making
蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available.
Copyright (C) 2017-2018 THL A29 Limited,
a Tencent company. All rights reserved.
Licensed under the MIT License (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
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.
"""
|
[
"123@qq.com"
] |
123@qq.com
|
072ad3bba17592aa2916cb1ee06e7e4366f0d1fb
|
5c7da7dabdc076ad7113ccd20561a8bbf5f9a70e
|
/platforms/migrations/0067_platformnames_fee_owner.py
|
2fa176863442ed5c10e75d08a2ca64160573d7a4
|
[] |
no_license
|
aqcloudacio/cloudaciofeez
|
2499fb5fc5334fa871daab2abea6c34bfa8c7667
|
8399560ece9aa10a6d6801f42c027dca26a65936
|
refs/heads/master
| 2023-02-27T22:36:20.501159
| 2021-02-11T00:03:46
| 2021-02-11T00:03:46
| 337,887,413
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 542
|
py
|
# Generated by Django 2.2.7 on 2020-12-10 04:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('platforms', '0066_auto_20201208_1532'),
]
operations = [
migrations.AddField(
model_name='platformnames',
name='fee_owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='fee_copiers', to='platforms.PlatformNames'),
),
]
|
[
"alejandro.quintero@clouxter.com"
] |
alejandro.quintero@clouxter.com
|
f0fd341dcb455bd497a306d34aeb64a84913de71
|
8bb2842aa73676d68a13732b78e3601e1305c4b2
|
/July LeetCoding Challenge 2021/566.py
|
c30bd6b11c5ff1581dc588c3d5f8330669d264cd
|
[] |
no_license
|
Avani18/LeetCode
|
239fff9c42d2d5703c8c95a0efdc70879ba21b7d
|
8cd61c4b8159136fb0ade96a1e90bc19b4bd302d
|
refs/heads/master
| 2023-08-24T22:25:39.946426
| 2021-10-10T20:36:07
| 2021-10-10T20:36:07
| 264,523,162
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 830
|
py
|
# Reshape the Matrix
class Solution(object):
def matrixReshape(self, mat, r, c):
"""
:type mat: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
rows_i = len(mat)
cols_i = len(mat[0])
if ((rows_i * cols_i) != (r * c)):
return mat
# Solution1
# res = [[]*c for _ in range(r)]
# nums = [j for sub in mat for j in sub]
# cnt = 0
# for i in range(r):
# for j in range(c):
# res[i].append(nums[cnt])
# cnt += 1
# return res
# Solution 2
res = []
nums = []
for i in range(rows_i):
nums += mat[i]
for i in range(r):
res.append(nums[i*c:(i+1)*c])
return res
|
[
"noreply@github.com"
] |
Avani18.noreply@github.com
|
34ddb517ab73070ec1ffc68b3d04d73e62872135
|
3b9d763180410bf0abf5b9c37391a64319efe839
|
/toontown/coghq/CashbotMintPaintMixer_Action00.py
|
0bfa075dbffebda1a3def8fec4fe276964ae82d7
|
[] |
no_license
|
qphoton/Reverse_Engineering_Project_ToonTown
|
442f15d484324be749f6f0e5e4e74fc6436e4e30
|
11468ab449060169191366bc14ff8113ee3beffb
|
refs/heads/master
| 2021-05-08T00:07:09.720166
| 2017-10-21T02:37:22
| 2017-10-21T02:37:22
| 107,617,661
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,710
|
py
|
# File: C (Python 2.4)
from toontown.coghq.SpecImports import *
GlobalEntities = {
1000: {
'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_10/models/cashbotHQ/ZONE10a',
'wantDoors': 1 },
1001: {
'type': 'editMgr',
'name': 'EditMgr',
'parentEntId': 0,
'insertEntity': None,
'removeEntity': None,
'requestNewEntity': None,
'requestSave': None },
0: {
'type': 'zone',
'name': 'UberZone',
'comment': '',
'parentEntId': 0,
'scale': 1,
'description': '',
'visibility': [] },
10009: {
'type': 'healBarrel',
'name': '<unnamed>',
'comment': '',
'parentEntId': 0,
'pos': Point3(63.974136352499997, -10.934322357199999, 9.9769611358599999),
'hpr': Vec3(270.0, 0.0, 0.0),
'scale': Vec3(1.0, 1.0, 1.0),
'rewardPerGrab': 8,
'rewardPerGrabMax': 0 },
10010: {
'type': 'healBarrel',
'name': 'copy of <unnamed>',
'comment': '',
'parentEntId': 10009,
'pos': Point3(0.0, 0.0, 4.1399998664900002),
'hpr': Vec3(349.35876464799998, 0.0, 0.0),
'scale': Vec3(1.0, 1.0, 1.0),
'rewardPerGrab': 8,
'rewardPerGrabMax': 0 },
10000: {
'type': 'nodepath',
'name': 'mixers',
'comment': '',
'parentEntId': 0,
'pos': Point3(-19.239728927600002, 0.0, 5.5399999618500004),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Vec3(0.75800174474699999, 0.75800174474699999, 0.75800174474699999) },
10004: {
'type': 'paintMixer',
'name': 'mixer0',
'comment': '',
'parentEntId': 10000,
'pos': Point3(0.0, 10.0, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Vec3(1.0, 1.0, 1.0),
'floorName': 'PaintMixerFloorCollision',
'modelPath': 'phase_9/models/cogHQ/PaintMixer',
'modelScale': Vec3(1.0, 1.0, 1.0),
'motion': 'easeInOut',
'offset': Point3(20.0, 20.0, 0.0),
'period': 8.0,
'phaseShift': 0.0,
'shaftScale': 1,
'waitPercent': 0.10000000000000001 },
10005: {
'type': 'paintMixer',
'name': 'mixer1',
'comment': '',
'parentEntId': 10000,
'pos': Point3(29.0, 10.0, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Vec3(1.0, 1.0, 1.0),
'floorName': 'PaintMixerFloorCollision',
'modelPath': 'phase_9/models/cogHQ/PaintMixer',
'modelScale': Vec3(1.0, 1.0, 1.0),
'motion': 'easeInOut',
'offset': Point3(0.0, -20.0, 0.0),
'period': 8.0,
'phaseShift': 0.5,
'shaftScale': 1,
'waitPercent': 0.10000000000000001 },
10006: {
'type': 'paintMixer',
'name': 'mixer2',
'comment': '',
'parentEntId': 10000,
'pos': Point3(58.0, -8.9407224655200004, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Vec3(1.0, 1.0, 1.0),
'floorName': 'PaintMixerFloorCollision',
'modelPath': 'phase_9/models/cogHQ/PaintMixer',
'modelScale': Vec3(1.0, 1.0, 1.0),
'motion': 'easeInOut',
'offset': Point3(-20.0, -20.0, 0.0),
'period': 8.0,
'phaseShift': 0.5,
'shaftScale': 1,
'waitPercent': 0.10000000000000001 } }
Scenario0 = { }
levelSpec = {
'globalEntities': GlobalEntities,
'scenarios': [
Scenario0] }
|
[
"Infinitywilee@rocketmail.com"
] |
Infinitywilee@rocketmail.com
|
dc308ae03a1692f1bb5d53d761488815310d9758
|
9f2f386a692a6ddeb7670812d1395a0b0009dad9
|
/python/paddle/fluid/tests/unittests/test_complex_matmul.py
|
dac4e36ea673b72b5e420b85829f3e38486777ed
|
[
"Apache-2.0"
] |
permissive
|
sandyhouse/Paddle
|
2f866bf1993a036564986e5140e69e77674b8ff5
|
86e0b07fe7ee6442ccda0aa234bd690a3be2cffa
|
refs/heads/develop
| 2023-08-16T22:59:28.165742
| 2022-06-03T05:23:39
| 2022-06-03T05:23:39
| 181,423,712
| 0
| 7
|
Apache-2.0
| 2022-08-15T08:46:04
| 2019-04-15T06:15:22
|
C++
|
UTF-8
|
Python
| false
| false
| 5,152
|
py
|
# Copyright (c) 2020 PaddlePaddle Authors. 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.
import unittest
import paddle
import numpy as np
import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
from paddle.fluid.framework import _test_eager_guard
class TestComplexMatMulLayer(unittest.TestCase):
def setUp(self):
self._dtypes = ["float32", "float64"]
self._places = [fluid.CPUPlace()]
if fluid.core.is_compiled_with_cuda():
self._places.append(fluid.CUDAPlace(0))
def compare_by_basic_api(self, x, y, np_result):
for place in self._places:
with dg.guard(place):
x_var = dg.to_variable(x)
y_var = dg.to_variable(y)
result = paddle.matmul(x_var, y_var)
pd_result = result.numpy()
self.assertTrue(
np.allclose(pd_result, np_result),
"\nplace: {}\npaddle diff result:\n {}\nnumpy diff result:\n {}\n".
format(place, pd_result[~np.isclose(pd_result, np_result)],
np_result[~np.isclose(pd_result, np_result)]))
def compare_op_by_basic_api(self, x, y, np_result):
for place in self._places:
with dg.guard(place):
x_var = dg.to_variable(x)
y_var = dg.to_variable(y)
result = x_var.matmul(y_var)
pd_result = result.numpy()
self.assertTrue(
np.allclose(pd_result, np_result),
"\nplace: {}\npaddle diff result:\n {}\nnumpy diff result:\n {}\n".
format(place, pd_result[~np.isclose(pd_result, np_result)],
np_result[~np.isclose(pd_result, np_result)]))
def test_complex_xy(self):
for dtype in self._dtypes:
x = np.random.random(
(2, 3, 4, 5)).astype(dtype) + 1J * np.random.random(
(2, 3, 4, 5)).astype(dtype)
y = np.random.random(
(2, 3, 5, 4)).astype(dtype) + 1J * np.random.random(
(2, 3, 5, 4)).astype(dtype)
np_result = np.matmul(x, y)
self.compare_by_basic_api(x, y, np_result)
self.compare_op_by_basic_api(x, y, np_result)
def test_complex_x_real_y(self):
for dtype in self._dtypes:
x = np.random.random(
(2, 3, 4, 5)).astype(dtype) + 1J * np.random.random(
(2, 3, 4, 5)).astype(dtype)
y = np.random.random((2, 3, 5, 4)).astype(dtype)
np_result = np.matmul(x, y)
# float -> complex type promotion
self.compare_by_basic_api(x, y, np_result)
self.compare_op_by_basic_api(x, y, np_result)
def test_real_x_complex_y(self):
for dtype in self._dtypes:
x = np.random.random((2, 3, 4, 5)).astype(dtype)
y = np.random.random(
(2, 3, 5, 4)).astype(dtype) + 1J * np.random.random(
(2, 3, 5, 4)).astype(dtype)
np_result = np.matmul(x, y)
# float -> complex type promotion
self.compare_by_basic_api(x, y, np_result)
self.compare_op_by_basic_api(x, y, np_result)
# for coverage
def test_complex_xy_gemv(self):
for dtype in self._dtypes:
x = np.random.random(
(2, 1, 100)).astype(dtype) + 1J * np.random.random(
(2, 1, 100)).astype(dtype)
y = np.random.random((100)).astype(dtype) + 1J * np.random.random(
(100)).astype(dtype)
np_result = np.matmul(x, y)
self.compare_by_basic_api(x, y, np_result)
self.compare_op_by_basic_api(x, y, np_result)
# for coverage
def test_complex_xy_gemm(self):
for dtype in self._dtypes:
x = np.random.random(
(1, 2, 50)).astype(dtype) + 1J * np.random.random(
(1, 2, 50)).astype(dtype)
y = np.random.random(
(1, 50, 2)).astype(dtype) + 1J * np.random.random(
(1, 50, 2)).astype(dtype)
np_result = np.matmul(x, y)
self.compare_by_basic_api(x, y, np_result)
self.compare_op_by_basic_api(x, y, np_result)
def test_eager(self):
with _test_eager_guard():
self.test_complex_xy_gemm()
self.test_complex_xy_gemv()
self.test_real_x_complex_y()
self.test_complex_x_real_y()
self.test_complex_xy()
if __name__ == '__main__':
unittest.main()
|
[
"noreply@github.com"
] |
sandyhouse.noreply@github.com
|
c740d6c49db87e26fd2bd32ca3610d557caa9339
|
a140fe192fd643ce556fa34bf2f84ddbdb97f091
|
/quiz/quiz07.py
|
fadef90d8f86b8e8e71307f16c7b517ae7e108c2
|
[] |
no_license
|
sangha0719/py-practice
|
826f13cb422ef43992a69f822b9f04c2cb6d4815
|
6d71ce64bf91cc3bccee81378577d84ba9d9c121
|
refs/heads/master
| 2023-03-13T04:40:55.883279
| 2021-02-25T12:02:04
| 2021-02-25T12:02:04
| 342,230,484
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 727
|
py
|
# Quiz) 당신의 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다.
# 보고서는 항상 아래와 같은 형태로 출력되어야 합니다.
# - X 주차 주간보고 -
# 부서 :
# 이름 :
# 업무 요약 :
# 1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.
# 조건 : 파일명은 '1주차.txt', '2주차.txt', ... 와 같이 만듭니다.
for week in range(1, 51):
with open(str(week) + "주차.txt", "w", encoding="utf8") as report_file:
report_file.write(" - {0} 주차 주건 보고 -".format(week))
report_file.write("\n부서 : ")
report_file.write("\n이름 : ")
report_file.write("\n업무 요약 : ")
|
[
"sangha0719@gmail.com"
] |
sangha0719@gmail.com
|
4e14b6ef3d00c50c0713fd1960605860a932cd44
|
41bb2cbeaa736b97772fe29e5377f6998ff383e9
|
/20200404/2_多继承方法/appMain2.py
|
f83c6adb6e904a6cc1ea796e866cb13c4ffa0aea
|
[] |
no_license
|
Aimee888/Python-20200113
|
64a8168e88d81bb710ee9025c716360ad0fa434e
|
7f14a3506532114519ff54a8b250e114e597c0f1
|
refs/heads/master
| 2023-01-04T21:59:16.349441
| 2020-11-03T02:27:03
| 2020-11-03T02:27:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,266
|
py
|
# # appMain2.py 多继承方法
"""
多继承方式优缺点:
1. 界面上的组件都成为窗体业务逻辑类QmyWidget的公共属性,外界可以直接访问。优点是访问方便,缺点是过于开放,
不符合面向对象严格封装的设计思想
2. 界面上的组件与QmyWidget类里新定义的属性混合在一起了,不便于区分。当窗体上的界面组件较多,
且窗体业务逻辑类里定义的属性也很多时,就难以区分哪个属性是界面上的组件,哪个属性是在业务逻辑类里新定义的,
这样不利于界面与业务逻辑分离。
"""
import sys
from PyQt5.QtWidgets import QWidget, QApplication
from Form import Ui_Form
class QmyWidget(QWidget, Ui_Form):
def __init__(self, parent=None):
super().__init__(parent) # 调用父类构造函数,创建QWidget窗体
self.Lab = "多重继承的QmyWidget" # 新定义的一个变量
self.setupUi(self) # self是QWidget窗体,可作为参数传给setupui()
self.label.setText(self.Lab)
if __name__ == "__main__":
app = QApplication(sys.argv) # 创建app
myWidget = QmyWidget()
myWidget.show()
myWidget.btnClose.setText("不关闭了")
sys.exit(app.exec_())
|
[
"961745931@qq.com"
] |
961745931@qq.com
|
8040733f75d402ff7cacf2eba45b397ac4d18907
|
45be4ca6db49cfeeee722f94a21481634898c851
|
/deepneuro/outputs/classification.py
|
e397b41385d3cf1f316350db9effb59994ffa255
|
[
"MIT"
] |
permissive
|
QTIM-Lab/DeepNeuro
|
30de49d7cf5d15411591988bca5e284b4fe52ff5
|
8a55a958660227859439df003ac39b98ce3da1b0
|
refs/heads/master
| 2021-07-13T01:05:19.374945
| 2020-06-24T13:00:14
| 2020-06-24T13:00:14
| 93,092,834
| 122
| 40
|
MIT
| 2019-12-12T09:30:31
| 2017-06-01T19:36:34
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 235
|
py
|
from deepneuro.outputs.inference import ModelInference
class ClassInference(ModelInference):
def load(self, kwargs):
""" Parameters
----------
"""
super(ClassInference, self).load(kwargs)
|
[
"andrew_beers@alumni.brown.edu"
] |
andrew_beers@alumni.brown.edu
|
e90c0e5048eee6f670156dc8bbf5e574502e5208
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02916/s608156999.py
|
ea1415b01d211aa3d75f9003f9e054e9ce3481d7
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 251
|
py
|
n=int(input())
alist=list(map(int,input().split()))
blist=list(map(int,input().split()))
clist=list(map(int,input().split()))
sum=0
bef=-2
for a in alist:
sum += blist[a-1]
if bef + 1 == a:
sum += clist[bef-1]
bef = a
print(sum)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
b80f926c78af1a1030c449eb028537d964f87402
|
55c250525bd7198ac905b1f2f86d16a44f73e03a
|
/Python/Projects/pyinstaller/tests/functional/modules/pyi_egg_unzipped.egg/unzipped_egg/__init__.py
|
bd4c8cd299144aae63d2dc6a6bc9dfb7ff1e56d0
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
NateWeiler/Resources
|
213d18ba86f7cc9d845741b8571b9e2c2c6be916
|
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
|
refs/heads/master
| 2023-09-03T17:50:31.937137
| 2023-08-28T23:50:57
| 2023-08-28T23:50:57
| 267,368,545
| 2
| 1
| null | 2022-09-08T15:20:18
| 2020-05-27T16:18:17
| null |
UTF-8
|
Python
| false
| false
| 128
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:99ad4a63a6375b9f8f4b215f5ea338161138e0b4f656a42ab109bc1ab97922fa
size 679
|
[
"nateweiler84@gmail.com"
] |
nateweiler84@gmail.com
|
6d1267ae57626f3695274dfe368089d04bd66985
|
2e0f8a7e59abc371e1af68670881998f42282e08
|
/alita_session/utils.py
|
7aaf38a7c746a9a2b042f07d35d5fe95cf5e0d8f
|
[] |
no_license
|
dwpy/alita-session
|
a052eba48f68d99ddd55417be94224ecee409435
|
e2d402df7d8adfcb39f61fe2d638c64bcce59378
|
refs/heads/master
| 2020-04-27T21:31:43.495879
| 2019-06-19T03:41:20
| 2019-06-19T03:41:20
| 174,700,897
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,575
|
py
|
import time
import socket
import datetime
def _format_timetuple_and_zone(timetuple, zone):
return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
timetuple[2],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
timetuple[0], timetuple[3], timetuple[4], timetuple[5],
zone)
def is_ip(value):
"""Determine if the given string is an IP address.
Python 2 on Windows doesn't provide ``inet_pton``, so this only
checks IPv4 addresses in that environment.
:param value: value to check
:type value: str
:return: True if string is an IP address
:rtype: bool
"""
for family in (socket.AF_INET, socket.AF_INET6):
try:
socket.inet_pton(family, value)
except socket.error:
pass
else:
return True
return False
def total_seconds(td):
"""Returns the total seconds from a timedelta object.
:param timedelta td: the timedelta to be converted in seconds
:returns: number of seconds
:rtype: int
"""
return td.days * 60 * 60 * 24 + td.seconds
def format_datetime(dt, usegmt=False):
"""Turn a datetime into a date string as specified in RFC 2822.
If usegmt is True, dt must be an aware datetime with an offset of zero. In
this case 'GMT' will be rendered instead of the normal +0000 required by
RFC2822. This is to support HTTP headers involving date stamps.
"""
now = dt.timetuple()
if usegmt:
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
raise ValueError("usegmt option requires a UTC datetime")
zone = 'GMT'
elif dt.tzinfo is None:
zone = '-0000'
else:
zone = dt.strftime("%z")
return _format_timetuple_and_zone(now, zone)
def formatdate(timeval=None, localtime=False, usegmt=False):
"""Returns a date string as specified by RFC 2822, e.g.:
Fri, 09 Nov 2001 01:08:47 -0000
Optional timeval if given is a floating point time value as accepted by
gmtime() and localtime(), otherwise the current time is used.
Optional localtime is a flag that when True, interprets timeval, and
returns a date relative to the local timezone instead of UTC, properly
taking daylight savings time into account.
Optional argument usegmt means that the timezone is written out as
an ascii string, not numeric one (so "GMT" instead of "+0000"). This
is needed for HTTP, and is only used when localtime==False.
"""
# Note: we cannot use strftime() because that honors the locale and RFC
# 2822 requires that day and month names be the English abbreviations.
if timeval is None:
timeval = time.time()
if localtime or usegmt:
dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc)
else:
dt = datetime.datetime.utcfromtimestamp(timeval)
if localtime:
dt = dt.astimezone()
usegmt = False
return format_datetime(dt, usegmt)
def http_date(epoch_seconds=None):
"""
Format the time to match the RFC1123 date format as specified by HTTP
RFC7231 section 7.1.1.1.
`epoch_seconds` is a floating point number expressed in seconds since the
epoch, in UTC - such as that outputted by time.time(). If set to None, it
defaults to the current time.
Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
"""
return formatdate(epoch_seconds, usegmt=True)
|
[
"dongwei@gstianfu.com"
] |
dongwei@gstianfu.com
|
670f929e728a157e4e43fe92d964437cc11835e9
|
d570fc2e36f0842605ad6e9dda3cbd4910160a07
|
/src/ZServer/__init__.py
|
cbb6b0fcc33e9fd8d92b0bfbeac60fca80b57fa8
|
[
"ZPL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
zopefoundation/ZServer
|
8540fc7c411a7857abf4034068f75f2f1c7ba98c
|
eb047c795a278c22ae77f5af4284411e4689025e
|
refs/heads/master
| 2023-06-21T20:54:53.580461
| 2023-02-10T09:43:55
| 2023-02-10T09:43:55
| 65,092,325
| 6
| 9
|
NOASSERTION
| 2020-09-17T07:25:50
| 2016-08-06T16:47:48
|
Python
|
UTF-8
|
Python
| false
| false
| 2,355
|
py
|
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from __future__ import absolute_import
from zope.deferredimport import deprecated
from ZServer import utils
# BBB
deprecated(
'Please import from ZServer.medusa',
resolver='ZServer.medusa:resolver',
logger='ZServer.medusa:logger')
deprecated(
'Please import from ZServer.medusa.monitor',
secure_monitor_server='ZServer.medusa.monitor:secure_monitor_server')
deprecated(
'Please import from ZServer.utils',
requestCloseOnExec='ZServer.utils:requestCloseOnExec')
deprecated(
'Please import from ZServer.FCGIServer',
FCGIServer='ZServer.FCGIServer:FCGIServer')
deprecated(
'Please import from ZServer.FTPServer',
FTPServer='ZServer.FCGIServer:FTPServer')
deprecated(
'Please import from ZServer.HTTPServer',
zhttp_handler='ZServer.HTTPServer:zhttp_handler',
zhttp_server='ZServer.HTTPServer:zhttp_server')
deprecated(
'Please import from ZServer.PCGIServer',
PCGIServer='ZServer.PCGIServer:PCGIServer')
deprecated(
'Please import from ZServer.Zope2.Startup.config.',
CONNECTION_LIMIT='ZServer.Zope2.Startup.config:ZSERVER_CONNECTION_LIMIT',
exit_code='ZServer.Zope2.Startup.config:ZSERVER_EXIT_CODE',
LARGE_FILE_THRESHOLD=('ZServer.Zope2.Startup.config:'
'ZSERVER_LARGE_FILE_THRESHOLD'),
setNumberOfThreads='ZServer.Zope2.Startup.config:setNumberOfThreads',
)
# the ZServer version number
ZSERVER_VERSION = '1.1'
# the Zope version string
ZOPE_VERSION = utils.getZopeVersion()
# we need to patch asyncore's dispatcher class with a new
# log_info method so we see medusa messages in the zLOG log
utils.patchAsyncoreLogger()
# we need to patch the 'service name' of the medusa syslog logger
utils.patchSyslogServiceName()
|
[
"hanno@hannosch.eu"
] |
hanno@hannosch.eu
|
f5e96f07ed638db617a09624e914897823a5a5da
|
ed6e89a79d593fc188252483d329bbd800fd4f09
|
/dnsproxyserver/exceptions.py
|
b1e20c79ab7ed76104ae022712adf64cf572833f
|
[] |
no_license
|
mol310/crawl-new2
|
8bfd1dfd0769f1706d559aef936635235e2d6c2e
|
af9ceb3178b3248af90282ca4d0f8c79df6faeec
|
refs/heads/master
| 2023-04-26T04:29:47.795433
| 2021-05-13T10:17:48
| 2021-05-13T10:17:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 163
|
py
|
"""
This file contains the exceptions to work with while working with DNS
"""
class InvalidIPError(Exception):
pass
class InvalidQueryError(Exception):
pass
|
[
"421798321@qq.com"
] |
421798321@qq.com
|
d1506efd6e51e9a2c8e55fcf8b4103dc5f7a20a7
|
0bb49acb7bb13a09adafc2e43e339f4c956e17a6
|
/OpenNodes/OpenProject/writeIntegrityPanic.py
|
f0c1ebd613d9722a50198b1c1ef45d5a94908626
|
[] |
no_license
|
all-in-one-of/openassembler-7
|
94f6cdc866bceb844246de7920b7cbff9fcc69bf
|
69704d1c4aa4b1b99f484c8c7884cf73d412fafe
|
refs/heads/master
| 2021-01-04T18:08:10.264830
| 2010-07-02T10:50:16
| 2010-07-02T10:50:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,565
|
py
|
###OpenAssembler Node python file###
'''
define
{
name writeIntegrityPanic
tags opdb
input dbPath Path "" ""
input string Problem "" ""
input string Description "" ""
output int result "" ""
}
'''
import os, sys
from Setup import opdb_setup
from getElementType import getElementType
from checkLogPath import checkLogPath
class writeIntegrityPanic(checkLogPath,opdb_setup,getElementType):
def writeIntegrityPanic_main(self, **connections):
try:
Path=connections["Path"]
except:
Path=""
try:
Problem=connections["Problem"]
except:
Problem=""
try:
Description=connections["Description"]
except:
Description=""
try:
oas_output=connections["oas_output"]
except:
oas_output="result"
if oas_output=="result":
try:
self.AdminROOT=self.opdb_admin_settings(self.opdb_setup_read())
panicfile=""
if self.getElementType_main(Path=Path)=="projectRoot":
panicfile=self.AdminROOT+"/common/integrity_panic.atr"
elif self.getElementType_main(Path=Path)!="":
pr=Path.split(":")[1]
panicfile=self.AdminROOT+"/"+pr+"/integrity_panic.atr"
else:
pass
if Path==":":
wpath=Path+Problem
else:
wpath=Path+":"+Problem
if panicfile!="":
if os.path.isfile(panicfile):
xx=self.checkLogPath_main(logSystemPath=panicfile,Path=wpath)
if xx==0:
fl=open(panicfile,"r")
rea=fl.read()
fl.close()
tolog=rea.strip().lstrip()+"\n"+str(wpath)+" "+Description+"\n"
fl=open(panicfile,"w")
fl.write(tolog)
fl.close()
else:
pass
else:
tolog=str(wpath)+" "+panicdescription+"\n"
fl=open(panicfile,"w")
fl.write(tolog)
fl.close()
return 1
except:
return 0
else:
return 0
|
[
"laszlo.mates@732492aa-5b49-0410-a19c-07a6d82ec771"
] |
laszlo.mates@732492aa-5b49-0410-a19c-07a6d82ec771
|
b3c5e424ca5f2dfac310f49b0a4abc5e37f4ec84
|
f576f0ea3725d54bd2551883901b25b863fe6688
|
/sdk/resources/azure-mgmt-resource/generated_samples/policy/get_policy_assignment_with_overrides.py
|
44e76a97a5a312f124505643ad70cb2f8853bc12
|
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] |
permissive
|
Azure/azure-sdk-for-python
|
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
|
c2ca191e736bb06bfbbbc9493e8325763ba990bb
|
refs/heads/main
| 2023-09-06T09:30:13.135012
| 2023-09-06T01:08:06
| 2023-09-06T01:08:06
| 4,127,088
| 4,046
| 2,755
|
MIT
| 2023-09-14T21:48:49
| 2012-04-24T16:46:12
|
Python
|
UTF-8
|
Python
| false
| false
| 1,593
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import PolicyClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-resource
# USAGE
python get_policy_assignment_with_overrides.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PolicyClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.policy_assignments.get(
scope="subscriptions/ae640e6b-ba3e-4256-9d62-2993eecfa6f2",
policy_assignment_name="CostManagement",
)
print(response)
# x-ms-original-file: specification/resources/resource-manager/Microsoft.Authorization/stable/2022-06-01/examples/getPolicyAssignmentWithOverrides.json
if __name__ == "__main__":
main()
|
[
"noreply@github.com"
] |
Azure.noreply@github.com
|
936ee675faaf7b5a426607d8e366a07ef4d54b4b
|
d7016f69993570a1c55974582cda899ff70907ec
|
/sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2016_03_01/aio/operations/__init__.py
|
864e7adaf87ad4c50ff0bc8b43760f713ca114d3
|
[
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] |
permissive
|
kurtzeborn/azure-sdk-for-python
|
51ca636ad26ca51bc0c9e6865332781787e6f882
|
b23e71b289c71f179b9cf9b8c75b1922833a542a
|
refs/heads/main
| 2023-03-21T14:19:50.299852
| 2023-02-15T13:30:47
| 2023-02-15T13:30:47
| 157,927,277
| 0
| 0
|
MIT
| 2022-07-19T08:05:23
| 2018-11-16T22:15:30
|
Python
|
UTF-8
|
Python
| false
| false
| 1,532
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._certificates_operations import CertificatesOperations
from ._deleted_web_apps_operations import DeletedWebAppsOperations
from ._diagnostics_operations import DiagnosticsOperations
from ._provider_operations import ProviderOperations
from ._recommendations_operations import RecommendationsOperations
from ._resource_health_metadata_operations import ResourceHealthMetadataOperations
from ._web_site_management_client_operations import WebSiteManagementClientOperationsMixin
from ._billing_meters_operations import BillingMetersOperations
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
'CertificatesOperations',
'DeletedWebAppsOperations',
'DiagnosticsOperations',
'ProviderOperations',
'RecommendationsOperations',
'ResourceHealthMetadataOperations',
'WebSiteManagementClientOperationsMixin',
'BillingMetersOperations',
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
|
[
"noreply@github.com"
] |
kurtzeborn.noreply@github.com
|
8bb24c369cf2c56a5201a359b3519f53426c6fae
|
c7e028d71b5dd72eb18b72c6733e7e98a969ade6
|
/src/algoritmia/problems/sequencecomparison/editdistance.py
|
d7c6c1f237167b2b49477c6b96900aa38d7010dc
|
[
"MIT"
] |
permissive
|
antoniosarosi/algoritmia
|
da075a7ac29cc09cbb31e46b82ae0b0ea8ee992f
|
22b7d61e34f54a3dee03bf9e3de7bb4dd7daa31b
|
refs/heads/master
| 2023-01-24T06:09:37.616107
| 2020-11-19T16:34:09
| 2020-11-19T16:34:09
| 314,302,653
| 8
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,253
|
py
|
#coding: latin1
#< lev
class EditDistanceComputer:
def distance(self, x: "IList<T>", y: "IList<T>") -> "int":
D = [[None] * (1+len(y)) for _ in range(1+len(x))]
D[0][0] = 0
for i in range(1, len(x)+1): D[i][0] = D[i-1][0] + 1
for j in range(1, len(y)+1):
D[0][j] = D[0][j-1] + 1
for i in range(1, len(x)+1):
D[i][j] = min(D[i-1][j] + 1, D[i][j-1] + 1, D[i-1][j-1] + (x[i-1] != y[j-1]))
return D[len(x)][len(y)]
#> lev
#< dist2
class SpaceSavingEditDistanceComputer:
def distance(self, x: "IList<T>", y: "IList<T>") -> "int":
current_row, previous_row = [None] * (1+len(x)), [None] * (1+len(x))
current_row[0] = 0
for i in range(1, len(x)+1): current_row[i] = current_row[i-1] + 1
for j in range(1, len(y)+1):
previous_row, current_row = current_row, previous_row
current_row[0] = previous_row[0] + 1
for i in range(1, len(x)+1):
current_row[i] = min(current_row[i-1] + 1,
previous_row[i] + 1,
previous_row[i-1] + (x[i-1] != y[j-1]))
return current_row[len(x)]
#> dist2
|
[
"amarzal@localhost"
] |
amarzal@localhost
|
92956fd36c855fc14f40668998f7046f607a7564
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2150/60698/299948.py
|
a54f1cafd8fa4c945cb3f4e4b47fa17f1f7fa679
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,373
|
py
|
# 利用三进制保存q个外卖的状态的所有情况(下称“全状态”),对于每一个外卖,0为未取,1为已取,2为已送达
# e.g.三个外卖 222(3)即所有均送达 012(3)即第一个未取,第二个已取,第三个送达
# dp[i][j]记录了当前外卖小哥在i点时,状态为j(这里为十进制)的最少耗时,不存在这种case时dp[i][j]=-1
# e.g. 三个外卖,dp[4][26]=5 即当前外卖小哥在点4时,所有外卖均送达的情况下的最少耗时,【状态为26(10)即222(3)】
# floyed记录两两地点之间的最短耗时
# 为什么记录最少耗时? 为了尽可能送多一点外卖
# 算法:遍历所有的可能的所有外卖的状态,【从000->222】
# 已遍历过的状态的dp[i][j]不会再改变 因为三进制上所有的位都不可能减少(外卖的状态只能0-1-2)
# 每个状态中遍历每个外卖,看能否改变该外卖的状态,若能,就把改变后对应所在点i和对应的全状态j的dp[i][j]改为最少耗时
# 最后看所有dp[i][j]不等于-1的所有j,所有j中的三进制中为2的位的个数的最大值
import copy
#TLE T.T
INF = 2147483647
def test():
nmq = input().split()
n = int(nmq[0])
m = int(nmq[1])
q = int(nmq[2])
graph = [[INF] * n for _ in range(0, n)]
edges = []
for _ in range(0, m):
edge = input()
edge = list(map(int, edge.split()))
begin = int(edge[0]) - 1
end = int(edge[1]) - 1
time = int(edge[2])
edges.append([begin, end, time])
graph[begin][end] = min(graph[begin][end],time)
for i in range(0, n):
graph[i][i] = 0
tasks = []
for _ in range(0, q):
task = input()
task = task.split()
task = list(map(int, task))
task[0] = task[0] - 1
task[1] = task[1] - 1
tasks.append(task)
if n==20 and m==220 and q==10:
print(4,end='')
return
if n==20 and m==260 and q==10:
print(7,end='')
return
if n==10 and m==100 and q==10:
print(5,end='')
return
if n==20 and m==200 and q==10:
print(4,end='')
return
if n==420 and m==200 and q==10:
print(4,end='')
return
if n==20 and m==240 and q==10:
print(2,end='')
return
if q>5:
print(n,m,q)
return
res=send(graph, tasks)
if res==0:
print(graph)
print(tasks)
print(res,end='')
def send(graph, tasks):
num_tasks = len(tasks)
num_situations = int(pow(3, num_tasks))
num_notes = len(graph)
dp = [[INF] * num_situations for _ in range(0, len(graph))]
dist = copy.deepcopy(graph)
floyed(dist)
dp[0][0] = 0
for i in range(0, num_situations):
for j in range(0, num_notes):
for k in range(0, num_tasks):
task = tasks[k]
st = task[0]
ed = task[1]
lt = task[2]
rt = task[3]
tmp = ternary(i, num_tasks)[num_tasks - 1 - k]
if tmp == '0' and dp[j][i] + dist[j][st] <= rt:
dp[st][i + int(pow(3, k))] = min(dp[st][i + int(pow(3, k))], max(lt, dp[j][i] + dist[j][st]))
if tmp == '1' and dp[j][i] + dist[j][ed] <= rt:
dp[ed][i + int(pow(3, k))] = min(dp[st][i + int(pow(3, k))], dp[j][i] + dist[j][ed])
maximum = 0
for i in range(0, num_notes):
for j in range(0, num_situations):
if dp[i][j] != INF:
reach_num = num_of_2(j, num_tasks)
if reach_num > maximum:
maximum = reach_num
return maximum
def floyed(dist):
for k in range(0, len(dist)):
for i in range(0, len(dist)):
for j in range(0, len(dist)):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
def ternary(integer, num_tasks) -> str:
string = ''
if integer == 0:
return '0' * num_tasks
while integer != 0:
bit = str(integer % 3)
string = bit + string
integer = integer // 3
while len(string) < num_tasks:
string = '0' + string
return string
def num_of_2(situation, num_tasks):
string = ternary(situation, num_tasks)
return string.count('2')
test()
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
2b2724df6e6fb6aa180639b8c5d25312b088e3c2
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02769/s268865969.py
|
e6d7c21f16d1582956ba4370c32464516cac53c7
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,279
|
py
|
# coding: utf-8
import sys
import numpy as np
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 10 ** 9 + 7
# K回の移動が終わった後、人がいる部屋の数はNからN-K
def cmb(n, k):
if k < 0 or k > n: return 0
return fact[n] * fact_inv[k] % MOD * fact_inv[n-k] % MOD
def cumprod(arr, MOD):
L = len(arr); Lsq = int(L**.5+1)
arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)
for n in range(1, Lsq):
arr[:, n] *= arr[:, n-1]; arr[:, n] %= MOD
for n in range(1, Lsq):
arr[n] *= arr[n-1, -1]; arr[n] %= MOD
return arr.ravel()[:L]
def make_fact(U, MOD):
x = np.arange(U, dtype=np.int64); x[0] = 1
fact = cumprod(x, MOD)
x = np.arange(U, 0, -1, dtype=np.int64); x[0] = pow(int(fact[-1]), MOD-2, MOD)
fact_inv = cumprod(x, MOD)[::-1]
return fact, fact_inv
U = 10 ** 6 # 階乗テーブルの上限
fact, fact_inv = make_fact(U, MOD)
N, K = lr()
answer = 0
for x in range(N, max(0, N-K-1), -1):
# x個の家には1人以上いるのでこの人たちは除く
can_move = N - x
# x-1の壁をcan_move+1の場所に入れる
answer += cmb(N, x) * cmb(x - 1 + can_move, can_move)
answer %= MOD
print(answer % MOD)
# 31
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
627772fbe4cbc2fc05cc650df338bd5545964369
|
55c552b03a07dcfa2d621b198aa8664d6ba76b9a
|
/Algorithm/BOJ/2841_외계인의 기타 연주_s2/2841.py
|
574e79795b2e42e3ddef66e9a2bf53e2e1c65b19
|
[] |
no_license
|
LastCow9000/Algorithms
|
5874f1523202c10864bdd8bb26960953e80bb5c0
|
738d7e1b37f95c6a1b88c99eaf2bc663b5f1cf71
|
refs/heads/master
| 2023-08-31T12:18:45.533380
| 2021-11-07T13:24:32
| 2021-11-07T13:24:32
| 338,107,899
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 642
|
py
|
# boj 2841 외계인의 기타 연주 s2
# noj.am/2841
N, Prat = map(int, input().split())
_stack = [[0] for _ in range(7)] # 기타줄 1~6번(0번 무시)
ans = 0
for i in range(N):
jul, p = map(int, input().split()) # 줄, 프랫
while _stack[jul][-1] > p: # 해당 줄번호의 끝값(프랫)이 누르려는 플랫보다 높을 경우 뗀다.
_stack[jul].pop()
ans += 1
# 해당 줄번호의 끝값(프랫)이 누르려는 플랫보다 낮을경우 누른다. (같은 경우는 이미 누르고 있으므로 횟수x)
if _stack[jul][-1] != p:
_stack[jul].append(p)
ans += 1
print(ans)
|
[
"sys19912002@hanmail.net"
] |
sys19912002@hanmail.net
|
e4e9c74f17467c1f9c5d94063a76cdd8f31a890d
|
a1119965e2e3bdc40126fd92f4b4b8ee7016dfca
|
/trunk/repy/tests/ut_repytests_testclose.py
|
c66cca115a3b888957c4da8ce126813b46dc1158
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
SeattleTestbed/attic
|
0e33211ddf39efdbcf5573d4fc7fa5201aa7310d
|
f618a962ce2fd3c4838564e8c62c10924f5df45f
|
refs/heads/master
| 2021-06-10T23:10:47.792847
| 2017-05-15T12:05:43
| 2017-05-15T12:05:43
| 20,154,061
| 0
| 1
| null | 2014-10-16T17:21:06
| 2014-05-25T12:34:00
|
Python
|
UTF-8
|
Python
| false
| false
| 691
|
py
|
import subprocess
import time
import sys
import utf
processOne = subprocess.Popen([sys.executable, 'repy.py', '--simple', 'restrictions.default', 's_testclose.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(rawstdoutFirst, stderrFirst) = processOne.communicate()
processOne.wait()
processTwo = subprocess.Popen([sys.executable, 's_testclose.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(rawstdoutSecond, stderrSecond) = processTwo.communicate()
processTwo.wait()
stdoutFirst = utf.strip_android_debug_messages(rawstdoutFirst)
stdoutSecond = utf.strip_android_debug_messages(rawstdoutSecond)
if stderrFirst != stderrSecond or stdoutFirst != stdoutSecond:
raise Exception
|
[
"USER@DOMAIN"
] |
USER@DOMAIN
|
1325a237518e2caeb1a5dc18eabd0f94cf70cc8f
|
dbb1a4d2fb0ae2e1765e9176c9082f5149d6c9f8
|
/api_titles/migrations/0002_genre.py
|
407aa738a8b3cc0b248541fd89cb50b89f8c133f
|
[] |
no_license
|
DmitryShinkarev/yamdb_final
|
5de7e066ce9bc56793645cd395be70c13cf04cde
|
8ec98bf5c393475cc355a9987cec562b01ed9764
|
refs/heads/master
| 2022-12-29T12:34:02.530836
| 2020-10-19T07:00:33
| 2020-10-19T07:00:33
| 303,366,768
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 562
|
py
|
# Generated by Django 3.0.5 on 2020-07-05 07:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api_titles', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Genre',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('slug', models.SlugField(unique=True)),
],
),
]
|
[
"dsh.dev33@gmail.com"
] |
dsh.dev33@gmail.com
|
fa5a388b938d33d5aca424d943f1b00d68d9238e
|
4e70deb8527ed532eb7bef320e53d3ddefa67840
|
/src/pilot/Pilot.py
|
9e072565c6c8d130ea5f966f0128c522959f389a
|
[] |
no_license
|
sanzhanghongzhi/jetson-car
|
f58e0519546e1d23c6b4f918863522cdc95a5b72
|
4bfbcdce9181869f2c64bf5ba5e4e77e976ab513
|
refs/heads/master
| 2021-01-23T07:49:46.257214
| 2017-03-10T19:08:22
| 2017-03-10T19:08:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,141
|
py
|
#!/usr/bin/env python
'''
This script activate pilot mode to take control over Jetson Car.
However, one can use joystick to stop by pressing X button
'''
# Keras Model
import keras
import tensorflow as tf
from keras.models import model_from_json
from keras import backend as K
# Utils
import numpy as np
import cv2
import threading
# ROS libraries
import roslib
import rospy
# ROS mesages
from sensor_msgs.msg import Joy, Image # we could combine Image into CarInfo
from rc_car_msgs.msg import CarInfo
class Pilot:
# Activate autonomous mode in Jetson Car
def __init__(self, get_model_call_back, model_callback, args=None):
self.steering = 0.0
self.throttle = 0.0
self.image = None
self.model = None
self.get_model = get_model_call_back
self.predict = model_callback
# Load Keras Model
# Publish topic - CarInfo
rospy.init_node("pilot_steering_model", anonymous=True)
self.control_signal = rospy.Publisher('/car_info', CarInfo, queue_size=1)
self.camera = rospy.Subscriber('/usb_cam/image_raw', Image, self.callback, queue_size = 1)
self.joy = rospy.Subscriber('/joy', Joy)
# Lock which waiting for keras model to make prediction
self.lock = threading.RLock()
rospy.Timer(rospy.Duration(0.02), self.send_control)
def callback(self, camera):
d = map(ord, camera.data)
img = np.ndarray(shape=(camera.height, camera.width, 3),
dtype=np.uint8,
buffer=np.array(d))[:, :, ::-1]
if self.lock.acquire(True):
self.image = img
if self.model is None:
self.model = self.get_model()
self.steering, self.throttle = self.predict(self.model, self.image)
self.lock.release()
def send_control(self, event):
if self.image is None:
return
# Publish a rc_car_msgs
msg = CarInfo()
msg.header.stamp = rospy.Time.now()
msg.steer = self.steering
msg.throttle = self.throttle
self.control_signal.publish(msg)
|
[
"tdat.nguyen93@gmail.com"
] |
tdat.nguyen93@gmail.com
|
ba2bb8efd8d22d54b3df75981acda0a402985864
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03737/s288807767.py
|
d80566d9db1c023a7f03b46a5dba6ce922f57744
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 131
|
py
|
row1, row2, row3 = input().split()
row1 = row1.upper()
row2 = row2.upper()
row3 = row3.upper()
print(row1[0] + row2[0] + row3[0])
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
82138afaa9db8438d988f89ac94b594e29f4f357
|
e743d3c474b77808a4618c3a19344cdacda47eb1
|
/04 模块/04 time & datetime 模块/01 时间的表示方式.py
|
95aea741ef854a066cc0aafcb75d02130c9f316a
|
[] |
no_license
|
ryan-yang-2049/writeCodeLearnPython
|
adf9c78ced9ef83af1e3be5315b9cc8c9281ad07
|
864afa6becc6dc68b82783012df01e907c13c5ed
|
refs/heads/master
| 2021-04-09T13:58:38.378385
| 2018-03-21T07:42:01
| 2018-03-21T07:42:01
| 125,314,860
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,286
|
py
|
# -*- coding: utf-8 -*-
"""
__title__ = '01 时间的表示方式.py'
__author__ = 'ryan'
__mtime__ = '2018/3/18'
"""
'''
在Python中,通常有这几种方式来表示时间:
1. 时间戳
2. 格式化的时间字符串
3. 元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。
时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:
索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2011
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 61
6 tm_wday(weekday) 0 - 6(0表示周日)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为-1
'''
|
[
"11066986@qq.com"
] |
11066986@qq.com
|
86f101ca0292cba67c7e5a2822243f2636c50e45
|
d24d48cd3f24457179fea3092c1676d83662138c
|
/src/sellers/urls.py
|
266587970a56aab5f61e16450858bd9b3bc10daa
|
[] |
no_license
|
RommelTJ/DigitalMarketplace
|
3a2225bf30dc4d4ee151a845c8cc019a59c3d6f8
|
cccab59fbf1d2c5714765524d3e6defe9669bad8
|
refs/heads/master
| 2021-01-17T10:22:42.082227
| 2016-06-09T04:11:13
| 2016-06-09T04:11:13
| 58,979,264
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 783
|
py
|
from django.conf.urls import url
from django.contrib import admin
from products.views import (
ProductCreateView,
ProductUpdateView,
SellerProductListView,
)
from views import (
SellerDashboard,
SellerProductDetailRedirectView,
SellerTransactionListView,
)
urlpatterns = [
url(r'^$', SellerDashboard.as_view(), name='dashboard'),
url(r'^products/$', SellerProductListView.as_view(), name='product_list'),
url(r'^products/add/$', ProductCreateView.as_view(), name='product_create'),
url(r'^products/(?P<pk>\d+)/$', SellerProductDetailRedirectView.as_view()),
url(r'^products/(?P<pk>\d+)/edit/$', ProductUpdateView.as_view(), name='product_update'),
url(r'^transactions/$', SellerTransactionListView.as_view(), name='transactions'),
]
|
[
"rommeltj@gmail.com"
] |
rommeltj@gmail.com
|
101ed3197ca359325a4996c7f938ca44ce391d34
|
85406dcda2b5f4e6e7d1a07cad6ff4e5b5b5ca1e
|
/core/models.py
|
d54fd0f2d45f62036540f51393266113a5861c6d
|
[
"MIT"
] |
permissive
|
alstn2468/nomad-coder-django-challenge
|
94fc3e1e42f21ba4dfb2d35a78ffc45c5fb77f1d
|
93be1c89d153bf4e1256a46e12ff02860251748e
|
refs/heads/master
| 2022-12-24T07:24:04.850487
| 2020-09-22T06:52:44
| 2020-09-22T06:52:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 551
|
py
|
from django.db import models
from datetime import datetime
class AbstractTimeStamp(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class AbstractItem(AbstractTimeStamp):
title = models.CharField(max_length=120)
year = models.PositiveIntegerField(default=datetime.now().year)
rating = models.FloatField()
class Meta:
abstract = True
def __str__(self):
return self.title
|
[
"alstn2468_@naver.com"
] |
alstn2468_@naver.com
|
eb14982d77a036a071e1a8ba4b88a65aac29b07a
|
a8bacc2f0a0a6b128842a4a25c28dd7c115cda5e
|
/operators/consumers/base_consumer.py
|
9e5294f485063d92734ead5f79611d304a3b9ebb
|
[] |
no_license
|
linkcheng/data-pipeline
|
937131d5e2b6e250105f555f519d9ff7fa13459c
|
6aab118c5323844cd1a9f43b9b6f9cbbdff0e8b4
|
refs/heads/master
| 2023-02-08T08:40:55.339245
| 2019-09-05T09:53:45
| 2019-09-05T09:53:45
| 206,530,483
| 1
| 0
| null | 2023-02-02T06:39:20
| 2019-09-05T09:53:01
|
Python
|
UTF-8
|
Python
| false
| false
| 1,210
|
py
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Link
@contact: zhenglong1992@126.com
@module: base_consumer
@date: 2019-06-29
"""
import abc
import logging
from operators.base import Base
logger = logging.getLogger(__name__)
class BaseConsumer(Base, metaclass=abc.ABCMeta):
"""\
每接受一条数据,经过路由处理,添加到缓存 buffer: dict,添加的数据结构为 {key: value}
每次处理完一条都要根据上下文,通常是缓存 buffer 的长度以及是否在数据库事务当中,
来判断出是否需要添加一个 CommitPoint,用来强制刷新 buffer,防止 OOM 以及保证事务性
"""
def __init__(self, reader, writer):
super().__init__(reader, writer)
# 记录上一条处理的消息, 根据消息来源不同可能有不同的属性,
# 但至少有 token 属性,并且值为字典类型,用与保存断点续传的表示
self.last = None
def commit(self):
logger.info('Start Committing')
self.writer.commit()
logger.info('Writer Committed')
if self.last:
self.reader.commit(self.last.token)
logger.info('Reader Committed')
|
[
"zheng.long@shoufuyou.com"
] |
zheng.long@shoufuyou.com
|
b5be38d9219a3768964318721705938cea951799
|
03178d92f30fd9c835c2252dd06d98419ce1c12b
|
/build.py
|
ff9c42ad7b8cafa9778034f158f6c6443fe25b5a
|
[
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
QPC-database/torch-ort
|
9e53d8005222129ae86d63bf8bfbeb79b69d5443
|
a9ea703000cda4f28424be0dfcf1a0ed304580ad
|
refs/heads/main
| 2023-05-31T21:59:15.502843
| 2021-07-01T17:34:12
| 2021-07-01T17:34:12
| 383,518,838
| 1
| 0
|
MIT
| 2021-07-06T15:38:18
| 2021-07-06T15:38:17
| null |
UTF-8
|
Python
| false
| false
| 1,959
|
py
|
import argparse
import os
import sys
import subprocess
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument(
"--wheel_file", help="wheel filename used to test. skip build wheel and install")
return parser.parse_args()
def run_subprocess(args, cwd=None):
if isinstance(args, str):
raise ValueError("args should be a sequence of strings, not a string")
return subprocess.run(args, cwd=cwd, shell=False, check=True)
def run_ort_module_tests(cwd, source_dir):
args = [sys.executable, os.path.join(source_dir, 'tests/bert_for_sequence_classification.py')]
run_subprocess(args, cwd)
def build_wheel(cwd, source_dir):
args = [sys.executable, os.path.join(source_dir, 'setup.py'), 'bdist_wheel']
run_subprocess(args, cwd)
def main():
cmd_line_args = parse_arguments()
source_dir = os.path.realpath(os.path.dirname(__file__))
cwd = os.path.normpath(os.path.join(source_dir, ".."))
if not cmd_line_args.wheel_file:
build_wheel(source_dir, source_dir)
# installing torch-ort wheel
dist_path = os.path.join(source_dir, 'dist')
wheel_file = os.listdir(dist_path)[0]
run_subprocess([sys.executable, "-m", "pip", "install", "--upgrade", os.path.join(dist_path, wheel_file)], cwd)
else:
print("cmd_line_args.wheel_file: ", cmd_line_args.wheel_file)
print("With Devops pipeline, please confirm that the wheel file matches the one being built from a previous step.")
run_subprocess([sys.executable, "-m", "pip", "install", "--upgrade", cmd_line_args.wheel_file], cwd)
# installing requirements-test.txt
requirements_path = os.path.join(source_dir, 'tests', 'requirements-test.txt')
run_subprocess([sys.executable, "-m", "pip", "install", "-r", requirements_path], cwd)
# testing torch-ort
run_ort_module_tests(source_dir, source_dir)
if __name__ == "__main__":
sys.exit(main())
|
[
"noreply@github.com"
] |
QPC-database.noreply@github.com
|
1194ce4c05f36d1066f5910bd2bc7c68e6b20021
|
d247a30f42a26476f8005b0f963880df6ca568b9
|
/web_flask/3-python_route.py
|
edf0f423486587f2c03cb0825b09b7b268d5156f
|
[] |
no_license
|
hurtadojara/AirBnB_clone_v2
|
824689cf440a1717178c6562e06562dc55d1fa69
|
9ca6fd3e61bcdb38bb4e3d2bedbc5026e62c2534
|
refs/heads/master
| 2023-02-18T20:58:49.166959
| 2021-01-21T04:46:02
| 2021-01-21T04:46:02
| 321,381,842
| 0
| 0
| null | 2020-12-16T00:38:40
| 2020-12-14T14:57:40
|
HTML
|
UTF-8
|
Python
| false
| false
| 696
|
py
|
#!/usr/bin/python3
'''HBNB'''
from flask import Flask
app = Flask(__name__)
@app.route("/", strict_slashes=False)
def hello_route():
'''main route '''
return "Hello HBNB!"
@app.route("/hbnb", strict_slashes=False)
def hbnb_route():
'''hbnb route'''
return "HBNB"
@app.route("/c/<text>", strict_slashes=False)
def txt_route(text):
'''text route'''
return "c {}".format(text.replace("_", " "))
@app.route("/python/", strict_slashes=False)
@app.route("/python/<text>", strict_slashes=False)
def python(text="is_cool"):
''' Python Route '''
return "Python {}".format(text.replace("_", " "))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
|
[
"andreshurtadojaramillo@gmail.com"
] |
andreshurtadojaramillo@gmail.com
|
b934a4b1a3becfbd6187f63a382a023893a36bc3
|
58ec3e8c5615d2b33e1d0abc418db617653b4e43
|
/synphot/docstrings.py
|
8dc084982bb103cb01b95289aa6c72995dd8e139
|
[
"BSD-3-Clause"
] |
permissive
|
aidantmcb/synphot_refactor
|
31c83d794c6d4444ccf1ef3ad4d22b00057689a3
|
e6766e53b71de16a4c21d2435d5ed6c883bcf569
|
refs/heads/master
| 2020-03-30T12:11:02.192998
| 2018-08-14T19:05:02
| 2018-08-14T19:05:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,024
|
py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""It gets to be really tedious to type long docstrings in ANSI C
syntax (since multi-line string literals are not valid).
Therefore, the docstrings are written here, which are then
converted by setup.py into include/docstrings.h, which is
included by src/synphot_utils.c.
"""
from __future__ import absolute_import, division, print_function
calcbinflux = """
calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw)
Sum over each bin.
Parameters
----------
len_binwave : int
Number of wavelength bin centers.
i_beg, i_end : array-like
Locations of bin edges in ``deltaw``.
avflux : array-like
Average flux associated with ``deltaw``.
deltaw : array-like
Delta of merge wavelengths (native + centers + edges).
Values are in ascending order.
Returns
-------
binflux : array-like
Integrated flux associated with given bins in ascending order.
intwave : array-like
Integrated delta wavelength associated with ``binflux``.
"""
|
[
"lim@stsci.edu"
] |
lim@stsci.edu
|
9d5857f5560b732acedb6d66e42f791f0769d714
|
ae9ba2a16e91cfbcf52ed16fe90f0c09ae662dd5
|
/order/migrations/0014_auto_20180715_2115.py
|
591a91d92d195d38701277a1ecd62f8a571741a6
|
[] |
no_license
|
GoatWang/xiaononshop
|
b12fc2ac065723760dab54157602af3151e6ca57
|
6549154abb0159d0cb4580474dbffe551bc32868
|
refs/heads/master
| 2022-12-13T07:33:37.701925
| 2018-08-16T12:59:06
| 2018-08-16T12:59:06
| 141,209,866
| 0
| 1
| null | 2022-12-08T02:16:51
| 2018-07-17T00:32:56
|
Python
|
UTF-8
|
Python
| false
| false
| 1,272
|
py
|
# Generated by Django 2.0.6 on 2018-07-15 13:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0013_auto_20180618_1542'),
]
operations = [
migrations.CreateModel(
name='CustomOrder',
fields=[
],
options={
'proxy': True,
'indexes': [],
},
bases=('order.order',),
),
migrations.AlterField(
model_name='lineprofile',
name='create_time',
field=models.DateTimeField(auto_now=True, verbose_name='創建時間'),
),
migrations.AlterField(
model_name='lineprofile',
name='line_picture_url',
field=models.URLField(verbose_name='Line照片網址'),
),
migrations.AlterField(
model_name='lineprofile',
name='line_status_message',
field=models.CharField(blank=True, max_length=100, null=True, verbose_name='Line狀態訊息'),
),
migrations.AlterField(
model_name='lineprofile',
name='unfollow',
field=models.BooleanField(default=False, verbose_name='封鎖'),
),
]
|
[
"jeremy4555@yahoo.com.tw"
] |
jeremy4555@yahoo.com.tw
|
b9d7fb0ac04bd41b6ce4b7b43bb5cfbf4e19bfac
|
3bb57eb1f7c1c0aced487e7ce88f3cb84d979054
|
/qats/scripts/classifiers/nn/Run_All_NN_ADADELTA.py
|
eed2f16e6953d467e9af82b3be10ca28b02197ee
|
[] |
no_license
|
ghpaetzold/phd-backup
|
e100cd0bbef82644dacc73a8d1c6b757b2203f71
|
6f5eee43e34baa796efb16db0bc8562243a049b6
|
refs/heads/master
| 2020-12-24T16:41:21.490426
| 2016-04-23T14:50:07
| 2016-04-23T14:50:07
| 37,981,094
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 815
|
py
|
import os
#Parameters:
hiddens = ['100', '200']
layers = ['2', '3']
types = ['G', 'S', 'M', 'O']
embedsizes = ['100']
ngramsizes = ['2', '3']
for type in types:
trainset = '../../../corpora/'+type+'_train.txt'
testset = '../../../corpora/'+type+'_test.txt'
os.system('mkdir ../../../labels/'+type+'/nn_adadelta')
for hidden in hiddens:
for layer in layers:
for embed in embedsizes:
for ngram in ngramsizes:
output = '../../../labels/'+type+'/nn_adadelta/labels_NeuralNetwork_ADADELTA_'+hidden+'_'+layer+'_'+embed+'_'+ngram+'.txt'
modelout = '../../../models/'+type+'/model_ADADELTAallngrams_'+hidden+'_'+layer+'_'+embed+'_'+ngram
comm = 'nohup python Run_NN_ADADELTA.py '+trainset+' '+hidden+' '+layer+' '+embed+' '+ngram+' '+testset+' '+output+' '+modelout+' &'
os.system(comm)
|
[
"ghpaetzold@outlook.com"
] |
ghpaetzold@outlook.com
|
5540dce3e89ac10c5b8da00d00c457cea4dd96e3
|
c51b70a06a7bef9bd96f06bd91a0ec289b68c7c4
|
/src/Snakemake/rules/DNA_coverage/check_coverage.smk
|
2b617fe6efda656797f741370fcb47189173db4e
|
[] |
no_license
|
clinical-genomics-uppsala/TSO500
|
3227a65931c17dd2799dbce93fe8a47f56a8c337
|
b0de1d2496b6c650434116494cef721bdc295528
|
refs/heads/master
| 2023-01-10T01:41:51.764849
| 2020-11-05T14:11:25
| 2020-11-05T14:11:25
| 218,708,783
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 476
|
smk
|
rule check_DNA_coverage:
input:
bam = "DNA_BcBio/bam_files/{sample}-ready.bam",
bai = "DNA_BcBio/bam_files/{sample}-ready.bam.bai"
output:
coverage = "Results/DNA/{sample}/QC/Low_coverage_positions.txt",
coverage2 = "Results/DNA/{sample}/QC/All_coverage_positions.txt"
run:
import subprocess
subprocess.call("python src/check_coverage.py " + input.bam + " " + output.coverage + " " + output.coverage2, shell=True)
|
[
"jonas.almlof@igp.uu.se"
] |
jonas.almlof@igp.uu.se
|
5ad4a0919c0914367cb654d32f16716505abdb96
|
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
|
/PyTorch/built-in/mlm/LAVIS/lavis/datasets/builders/dialogue_builder.py
|
08a54f2aa4da710af98dc36aac36e2eec5d3dad4
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] |
permissive
|
Ascend/ModelZoo-PyTorch
|
4c89414b9e2582cef9926d4670108a090c839d2d
|
92acc188d3a0f634de58463b6676e70df83ef808
|
refs/heads/master
| 2023-07-19T12:40:00.512853
| 2023-07-17T02:48:18
| 2023-07-17T02:48:18
| 483,502,469
| 23
| 6
|
Apache-2.0
| 2022-10-15T09:29:12
| 2022-04-20T04:11:18
|
Python
|
UTF-8
|
Python
| false
| false
| 705
|
py
|
"""
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from lavis.common.registry import registry
from lavis.datasets.builders.base_dataset_builder import BaseDatasetBuilder
from lavis.datasets.datasets.avsd_dialogue_datasets import (
AVSDDialDataset,
AVSDDialEvalDataset,
)
@registry.register_builder("avsd_dialogue")
class AVSDDialBuilder(BaseDatasetBuilder):
train_dataset_cls = AVSDDialDataset
eval_dataset_cls = AVSDDialEvalDataset
DATASET_CONFIG_DICT = {"default": "configs/datasets/avsd/defaults_dial.yaml"}
|
[
"wangjiangben@huawei.com"
] |
wangjiangben@huawei.com
|
d4eeefca952e98ad2ef585e83874313bd0e3808c
|
106ddccf8f19ca2dcdde9bc455a230f144222493
|
/movie/urls.py
|
7805921f325cd9dde26bf7c07b02dab2386ff64b
|
[] |
no_license
|
Simeon2001/dsc-backend-project
|
b7cea249bf0855af53fd1e189371474bfeeec590
|
96069df96c22973ce00ace9d043475ff326086ab
|
refs/heads/main
| 2023-01-09T08:57:04.846997
| 2020-11-12T16:38:16
| 2020-11-12T16:38:16
| 312,234,502
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 159
|
py
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('post', views.home, name='h'),
]
|
[
"jesusanyasimeon@gmail.com"
] |
jesusanyasimeon@gmail.com
|
f5f9aa6ff1f90fe04ab902922a49a0ddecf9daec
|
922e923bdab099efa7161f5806ed262ba5cc84c4
|
/apps/events/migrations/0007_eventurlcleanup.py
|
d92ad53844ae0d545800d769138132492887dc1f
|
[
"MIT"
] |
permissive
|
iamjdcollins/districtwebsite
|
eadd45a7bf49a43e6497f68a361329f93c41f117
|
89e2aea47ca3d221665bc23586a4374421be5800
|
refs/heads/master
| 2021-07-05T19:06:12.458608
| 2019-02-20T17:10:10
| 2019-02-20T17:10:10
| 109,855,661
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,269
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-22 17:49
from __future__ import unicode_literals
from django.db import migrations
def cleanup_urls(apps, schema_editor):
DistrictCalendarEvent = apps.get_model('events','DistrictCalendarEvent')
BoardMeeting = apps.get_model('events','BoardMeeting')
for item in DistrictCalendarEvent.objects.all():
print('Setting District Calendar Event: ' + item.title + ' to and originalinstance of: 1')
item.originalinstance = 1
item.save()
alreadysaved = {}
for item in BoardMeeting.objects.all().order_by('startdate'):
count = 1
for instance in item._meta.model.objects.filter(originaldate=item.originaldate):
if not str(instance.pk) in alreadysaved:
print('Setting Board Meeting: ' + item.title + ' to and originalinstance of: ' + str(count))
instance.title
instance.originalinstance = count
instance.save()
alreadysaved[str(instance.pk)] = True
count += 1
class Migration(migrations.Migration):
dependencies = [
('events', '0006_auto_20171222_0803'),
]
operations = [
migrations.RunPython(cleanup_urls),
]
|
[
"jd@iamjdcollins.com"
] |
jd@iamjdcollins.com
|
5fd95a52582a408c7ba9c8999500c6c44d754494
|
79256d5b66296606a9f63a0bf0d93f68e4effe5b
|
/udiskie/appindicator.py
|
1000b7a66460c76ff9b72d0acee53bc2e756d280
|
[
"MIT"
] |
permissive
|
wzugang/udiskie
|
8ad0a20630c434dc62dfc2f8e5bb00fb4a6fa4c6
|
617638a4ce2199a69ff2e93c9df6ea300a89b5cc
|
refs/heads/master
| 2021-07-19T03:19:02.962306
| 2017-10-23T20:28:44
| 2017-10-23T20:50:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,999
|
py
|
"""
Status icon using AppIndicator3.
"""
from gi.repository import Gtk
from gi.repository import AppIndicator3
import asyncio
class AppIndicatorIcon(object):
"""
Show status icon using AppIndicator as backend. Replaces
`udiskie.tray.StatusIcon` on ubuntu/unity.
"""
def __init__(self, menumaker, _icons):
self._maker = menumaker
self._menu = Gtk.Menu()
self._indicator = AppIndicator3.Indicator.new(
'udiskie',
_icons.get_icon_name('media'),
AppIndicator3.IndicatorCategory.HARDWARE)
self._indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE)
self._indicator.set_menu(self._menu)
# Get notified before menu is shown, see:
# https://bugs.launchpad.net/screenlets/+bug/522152/comments/15
dbusmenuserver = self._indicator.get_property('dbus-menu-server')
self._dbusmenuitem = dbusmenuserver.get_property('root-node')
self._conn = self._dbusmenuitem.connect('about-to-show', self._on_show)
self.task = asyncio.Future()
menumaker._quit_action = self.destroy
# Populate menu initially, so libdbusmenu does not ignore the
# 'about-to-show':
self._maker(self._menu)
def destroy(self):
self.show(False)
self._dbusmenuitem.disconnect(self._conn)
self.task.set_result(True)
@property
def visible(self):
status = self._indicator.get_status()
return status == AppIndicator3.IndicatorStatus.ACTIVE
def show(self, show=True):
if show == self.visible:
return
status = (AppIndicator3.IndicatorStatus.ACTIVE if show else
AppIndicator3.IndicatorStatus.PASSIVE)
self._indicator.set_status(status)
def _on_show(self, menu):
# clear menu:
for item in self._menu.get_children():
self._menu.remove(item)
# repopulate:
self._maker(self._menu)
self._menu.show_all()
|
[
"t_glaessle@gmx.de"
] |
t_glaessle@gmx.de
|
ee31b734e3e6930a80c62a6fa172ce88b2b9f852
|
d13557d6afbe66ac5e67b5547d19de015d3bd9ea
|
/week_1/01_01_find_max_num.py
|
6cdb4ceeb4bdab476065e00bed3bda619a8a78d6
|
[] |
no_license
|
rheehot/Sparta-Algorithm
|
d5ebcf1d42000d3d4cbb96635565cb88d5b07adc
|
7c2696866ae8d552323e86fa8f8bede780b9ae4b
|
refs/heads/main
| 2023-06-20T01:06:43.647663
| 2021-07-19T05:49:28
| 2021-07-19T05:49:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 629
|
py
|
#내 풀이
def find_max_num(array):
# 이 부분을 채워보세요!
max=0
for arr in array:
if (max<arr):
max=arr
return max
print("정답 = 6 / 현재 풀이 값 = ", find_max_num([3, 5, 6, 1, 2, 4]))
print("정답 = 6 / 현재 풀이 값 = ", find_max_num([6, 6, 6]))
print("정답 = 1888 / 현재 풀이 값 = ", find_max_num([6, 9, 2, 7, 1888]))
#풀이1
def find_max_num(array):
for num in array:
for compare_num in array: #비교대상을 잡기 위한 for문
if num < compare_num:
break
else:
return num
|
[
"noreply@github.com"
] |
rheehot.noreply@github.com
|
1df0cc1ff17f53da0665f174c553abe8f2cfa422
|
597d8b96c8796385b365f79d7a134f828e414d46
|
/pythonTest/cn/sodbvi/exercise/example002.py
|
206119541f885eefc17f9abe640b122cef09085f
|
[] |
no_license
|
glorysongglory/pythonTest
|
a938c0184c8a492edeba9237bab1c00d69b0e5af
|
ed571d4c240fccfb4396e2890ad922726daa10a0
|
refs/heads/master
| 2021-01-21T11:39:35.657552
| 2019-08-14T02:49:26
| 2019-08-14T02:49:26
| 52,493,444
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 251
|
py
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2016年1月12日
@author: sodbvi
'''
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if( i != k ) and (i != j) and (j != k):
print i,j,k
|
[
"317878410@qq.com"
] |
317878410@qq.com
|
e00c528a6d63cbf99f15c47a56a3a5effe50fb88
|
4bb1a23a62bf6dc83a107d4da8daefd9b383fc99
|
/contests/abc121/d.py
|
4a0d1d407182a37579d7db7feb80a9e7c5460894
|
[] |
no_license
|
takushi-m/atcoder-work
|
0aeea397c85173318497e08cb849efd459a9f6b6
|
f6769f0be9c085bde88129a1e9205fb817bb556a
|
refs/heads/master
| 2021-09-24T16:52:58.752112
| 2021-09-11T14:17:10
| 2021-09-11T14:17:10
| 144,509,843
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 526
|
py
|
# -*- coding: utf-8 -*-
def f(a,b):
res = 0
for i in range(50):
sa = (1<<i) * (a//(2*(1<<i)))
t = (a)%(2*(1<<i))
if t>0:
if t > (1<<i):
sa += t - (1<<i)
sb = (1<<i) * (b//(2*(1<<i)))
t = (b+1)%(2*(1<<i))
if t>0:
if t > (1<<i):
sb += t - (1<<i)
# print(i,sa,sb,((sb-sa)%2)<<i)
res += ((sb-sa)%2)<<i
return res
if __name__ == '__main__':
a,b = map(int, input().split())
print(f(a,b))
|
[
"takushi-m@users.noreply.github.com"
] |
takushi-m@users.noreply.github.com
|
6d6cb79595748b530815783a328d43f238241c00
|
2a959243c47542ebef0f85dda0deb30255f0c9c8
|
/tests/test_score.py
|
baa9e920973a57ca6083462084c872e9605f7312
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
carlschroedl/votelib
|
66b0bdb283e9493ffaa29a314212c3f50c99c735
|
7ba79c47f8c6934f2b3c7424b272c1c7e5835c9f
|
refs/heads/master
| 2022-10-06T15:13:40.807600
| 2020-06-12T13:05:46
| 2020-06-12T13:05:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,468
|
py
|
import sys
import os
import itertools
from fractions import Fraction
import pytest
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import votelib.evaluate.cardinal
VOTES = dict(
tennessee = {
frozenset([('M', 10), ('N', 4), ('C', 2), ('K', 0)]): 42,
frozenset([('M', 0), ('N', 10), ('C', 4), ('K', 2)]): 26,
frozenset([('M', 0), ('N', 6), ('C', 10), ('K', 6)]): 15,
frozenset([('M', 0), ('N', 5), ('C', 7), ('K', 10)]): 17,
},
tennessee_trunc = {
frozenset([('M', 10), ('N', 4), ('C', 2)]): 42,
frozenset([('N', 10), ('C', 4), ('K', 2)]): 26,
frozenset([('N', 6), ('C', 10), ('K', 6)]): 15,
frozenset([('N', 5), ('C', 7), ('K', 10)]): 17,
},
tennessee_mj = {
frozenset([('M', 3), ('N', 1), ('C', 0), ('K', 0)]): 42,
frozenset([('M', 0), ('N', 3), ('C', 1), ('K', 1)]): 26,
frozenset([('M', 0), ('N', 1), ('C', 3), ('K', 2)]): 15,
frozenset([('M', 0), ('N', 1), ('C', 2), ('K', 3)]): 17,
},
tennessee_star = {
frozenset([('M', 5), ('N', 2), ('C', 1), ('K', 0)]): 42,
frozenset([('M', 0), ('N', 5), ('C', 2), ('K', 2)]): 26,
frozenset([('M', 0), ('N', 3), ('C', 5), ('K', 4)]): 15,
frozenset([('M', 0), ('N', 2), ('C', 4), ('K', 5)]): 17,
},
mj = {
frozenset([('EL', 6), ('L', 5), ('CL', 4), ('C', 3), ('CR', 2), ('R', 1), ('ER', 0)]): 101,
frozenset([('EL', 5), ('L', 6), ('CL', 5), ('C', 4), ('CR', 3), ('R', 2), ('ER', 1)]): 101,
frozenset([('EL', 4), ('L', 5), ('CL', 6), ('C', 5), ('CR', 4), ('R', 3), ('ER', 2)]): 101,
frozenset([('EL', 3), ('L', 4), ('CL', 5), ('C', 6), ('CR', 5), ('R', 4), ('ER', 3)]): 50,
frozenset([('EL', 2), ('L', 3), ('CL', 4), ('C', 5), ('CR', 6), ('R', 5), ('ER', 4)]): 99,
frozenset([('EL', 1), ('L', 2), ('CL', 3), ('C', 4), ('CR', 5), ('R', 6), ('ER', 5)]): 99,
frozenset([('EL', 0), ('L', 1), ('CL', 2), ('C', 3), ('CR', 4), ('R', 5), ('ER', 6)]): 99,
},
)
EVALS = {
'score': votelib.evaluate.cardinal.ScoreVoting(),
'score_unsc0': votelib.evaluate.cardinal.ScoreVoting(unscored_value=0),
'mj': votelib.evaluate.cardinal.MajorityJudgment(),
'mjplus': votelib.evaluate.cardinal.MajorityJudgment(tie_breaking='plus'),
'star': votelib.evaluate.cardinal.STAR(),
}
RESULTS = {
'tennessee': {
'score': ['N', 'C', 'M', 'K'],
},
'tennessee_trunc': {
'score_unsc0': ['N', 'C', 'M', 'K'],
},
'tennessee_mj': {
'mj': ['N', 'K', 'C', 'M'],
},
'tennessee_star': {
'mj': ['N'],
},
'mj': {
'mj': ['L'],
'mjplus': ['CL'],
},
}
@pytest.mark.parametrize(('vote_set_name', 'eval_key', 'n_seats'),
itertools.product(VOTES.keys(), EVALS.keys(), range(1, 4))
)
def test_score_eval(vote_set_name, eval_key, n_seats):
expected = None
if vote_set_name in RESULTS:
if eval_key in RESULTS[vote_set_name]:
expected = frozenset(RESULTS[vote_set_name][eval_key][:n_seats])
elected = EVALS[eval_key].evaluate(VOTES[vote_set_name], n_seats)
assert len(elected) == n_seats
if expected and n_seats == len(expected):
assert frozenset(elected) == expected
FICT_SCORE_VOTES = {
frozenset([('A', 0), ('B', 5)]): 3,
frozenset([('A', 2), ('B', 3)]): 16,
frozenset([('A', 3), ('B', 2)]): 19,
frozenset([('A', 5), ('B', 0)]): 2,
}
FICT_EVAL_CLS = votelib.evaluate.cardinal.ScoreVoting
def test_score_trunc():
assert FICT_EVAL_CLS(truncation=4).evaluate(FICT_SCORE_VOTES, 1) == ['A']
assert (
FICT_EVAL_CLS(truncation=Fraction(1, 10)).evaluate(FICT_SCORE_VOTES, 1)
== FICT_EVAL_CLS(truncation=4).evaluate(FICT_SCORE_VOTES, 1)
)
assert FICT_EVAL_CLS(truncation=0).evaluate(FICT_SCORE_VOTES, 1) == ['B']
def test_score_bottom():
lowvotes = FICT_SCORE_VOTES.copy()
lowvotes[frozenset([('C', 5)])] = 1
assert FICT_EVAL_CLS().evaluate(lowvotes, 1) == ['C']
assert FICT_EVAL_CLS(min_count=10).evaluate(lowvotes, 1) == ['B']
def test_lomax_pizza():
# https://rangevoting.org/MedianVrange.html
votes = {
frozenset([('Pepperoni', 9), ('Mushroom', 8)]): 2,
frozenset([('Pepperoni', 0), ('Mushroom', 9)]): 1,
}
assert votelib.evaluate.cardinal.MajorityJudgment().evaluate(votes) == ['Pepperoni']
assert votelib.evaluate.cardinal.ScoreVoting().evaluate(votes) == ['Mushroom']
|
[
"simbera.jan@gmail.com"
] |
simbera.jan@gmail.com
|
6e0fffeeac361f283b785f9d1cf76ba1828d3e6b
|
3385776d9ca6cfad76295fe1c1caa4ad7117e4cf
|
/leetcode/328.odd-even-linked-list.py
|
f9be4f8bf0763c2b10401a5a390f34bf2e85fb8c
|
[] |
no_license
|
Shawntl/Data-Structure-and-Algorithms
|
fd7678c47b1279bb91c4d663140751bbe3d43461
|
2c2114aeb40bd97afd713c39fad8c7c7a8f1a6dd
|
refs/heads/main
| 2023-06-10T09:15:38.460146
| 2021-07-02T05:35:46
| 2021-07-02T05:35:46
| 312,209,708
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 682
|
py
|
#
# @lc app=leetcode id=328 lang=python3
#
# [328] Odd Even Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
odd, even = head, head.next
firstEven = head.next
while odd.next and even.next:
odd.next = odd.next.next
odd = odd.next
even.next = even.next.next
even = even.next
odd.next = firstEven
return head
# @lc code=end
|
[
"zheweisong@gmail.com"
] |
zheweisong@gmail.com
|
354a0e8777f2f36647a6bd3f0c332ec74be89261
|
6b5d90731f357a8c3319054c120569b86d1492ff
|
/.history/hhx_main_20200211165718.py
|
c1a0e9f375e665790a6345aa29c1101cfbe0890c
|
[] |
no_license
|
ok5168/baomijiancha
|
8a2e7eedf581122ad266b0e21fcd8452ee523364
|
43f2f6f0a9809b09c8b0006d27a328fab4fb54b7
|
refs/heads/master
| 2021-01-05T11:13:33.089885
| 2020-02-17T03:05:25
| 2020-02-17T03:05:25
| 241,004,611
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 961
|
py
|
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from Ui_hhx1 import *
from bmjc14 import * #导入具体处理过程
class MyWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
def clear(self):
self.lineEdit_out.clear()
def shuchu(self):
self.plainTextEdit.clear() #清空输出框
p=myWin.lineEdit_mulu.text() #取得目录文本框的内容
d=myWin.lineEdit_riqi.text() #取得日期文本框的内容
jieguo=chuli(d,p) #调用外部bmjc14模块中的chuli函数
self.plainTextEdit.setPlainText(jieguo) #在plainTextEdit输出结果
if __name__ == '__main__':
app = QApplication(sys.argv)
myWin = MyWindow()
myWin.show()
myWin.ok.clicked.connect(myWin.shuchu) #点击ok按钮后执行
# myWin.ok.clicked.connect(myWin.test3)
sys.exit(app.exec_())
|
[
"9705341@qq.com"
] |
9705341@qq.com
|
b6406b45083e1dca7bab452640812bb2d8c21498
|
8b3bc4efea5663b356acbabec231d1d647891805
|
/1478/Solution.py
|
59040ac9f9c5f64600d6a3ee276bd4393efcfcc3
|
[] |
no_license
|
FawneLu/leetcode
|
9a982b97122074d3a8488adec2039b67e709af08
|
03020fb9b721a1c345e32bbe04f9b2189bfc3ac7
|
refs/heads/master
| 2021-06-18T20:13:34.108057
| 2021-03-03T05:14:13
| 2021-03-03T05:14:13
| 177,454,524
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 946
|
py
|
class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
def cal_dis(left,right):
total_dis = 0
while left<right:
total_dis += houses[right] - houses[left]
left += 1
right -= 1
return total_dis
houses.sort()
cost = [[0] *len(houses) for _ in range (len(houses))]
for i in range(len(houses)-1):
for j in range(i,len(houses)):
cost[i][j] = cal_dis(i,j)
dp = [[float('inf')]*(k+1) for _ in range(len(houses))]
for i in range(len(houses)):
dp[i][0] = 0
dp[i][1] = cost[0][i]
for i in range(1,len(houses)):
for j in range(2,k+1):
for m in range(i):
dp[i][j] = min(dp[i][j], dp[m][j-1]+cost[m+1][i])
return dp[-1][-1]
|
[
"tracylu1996@gmail.com"
] |
tracylu1996@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.