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
9bd4b64ebb38e2e59820dd722970e0e96371a90f
54c22fdcb44c42b1c0855be576e934939a2a2c5c
/contragents/models.py
0b10a0036da5a0300652633c3a2677971c2eb556
[]
no_license
flashboyka/build_yard
84e50600e03c0124f1fdf3991491852f5f469774
c25b419f445bc5c751966850f3860cf19dfd33a1
refs/heads/master
2020-12-11T06:43:44.601335
2020-01-15T14:34:37
2020-01-15T14:34:37
233,791,548
0
0
null
2020-01-14T08:19:53
2020-01-14T08:19:52
null
UTF-8
Python
false
false
716
py
from django.db import models class Contragent(models.Model): last_name = models.CharField(max_length=25, verbose_name='Фамилия') first_name = models.CharField(max_length=25, verbose_name='Имя') middle_name = models.CharField(max_length=25, verbose_name='Отчество') email = models.EmailField(verbose_name='Почта') phone = models.CharField(max_length=13, verbose_name='Номер телефона') address = models.TextField(verbose_name='Адрес') def __str__(self): return f'{self.last_name} {self.first_name} {self.middle_name}' class Meta: verbose_name = 'Контрагента' verbose_name_plural = 'Контрагенты'
[ "dcopm999@gmail.com" ]
dcopm999@gmail.com
9dff0431f838a1a504fe9b24ea59c733529ae5fa
25d6371928dc91e2593edf04d7428f4cf886da42
/students/wzh/pyfile/playmusic.py
3cec9f688f00be432a2e29637a297462a40713ab
[]
no_license
ophwsjtu18/ohw
7d4ecca6fc98cadbabd3c088c0d69efa3d20a10f
67677baad6d0b92d3d453309b66ed274c097dfd6
refs/heads/master
2021-05-25T10:28:59.872340
2018-12-19T13:18:34
2018-12-19T13:18:34
127,097,829
1
3
null
2018-11-07T10:53:03
2018-03-28T06:58:57
Python
UTF-8
Python
false
false
929
py
import serial import serial.tools.list_ports import time import csv print ('hello') ports = list(serial.tools.list_ports.comports()) print (ports) f=open("song.csv",'r') songs=list(csv.reader(f)) song_dictionary={} i=0 for song in songs: song_dictionary[song[0]]=song[1:] i+=1 for p in ports: print (p[1]) if "SERIAL" in p[1] or "UART" in p[1]: ser=serial.Serial(port=p[0]) else : print ("No Arduino Device was found connected to the computer") #ser=serial.Serial(port='COM4') #ser=serial.Serial(port='/dev/ttymodem542') #wait 2 seconds for arduino board restart time.sleep(2) def run(): action = "empty" while action != "q": print ('q for quit,others for command') name=input() for voice in song_dictionary[name]: ser.write(voice.encode()) ser.write("a".encode()) time.sleep(0.1) run()
[ "noreply@github.com" ]
ophwsjtu18.noreply@github.com
7fff60cccdbfed5de914c812bb9d37476fabd96d
4ed038a638725ac77731b0b97ddd61aa37dd8d89
/cairis/gui/TraceDialog.py
93dfa69fbf3f7c968e04ca274567b4895b3f5e8f
[ "Apache-2.0" ]
permissive
RachelLar/cairis_update
0b784101c4aff81ff0390328eb615e335301daa2
0b1d6d17ce49bc74887d1684e28c53c1b06e2fa2
refs/heads/master
2021-01-19T06:25:47.644993
2016-07-11T20:48:11
2016-07-11T20:48:11
63,103,727
0
0
null
null
null
null
UTF-8
Python
false
false
3,041
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. import wx from cairis.core.armid import * import WidgetFactory import cairis.core.TraceParameters import cairis.core.UpdateTraceParameters import TracePanel class TraceDialog(wx.Dialog): def __init__(self,parent,parameters): wx.Dialog.__init__(self,parent,parameters.id(),parameters.label(),style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(400,275)) if (parameters.__class__.__name__ == 'TraceDialogParameters'): self.theOriginalFromObject = parameters.fromObject() self.theOriginalFromId = parameters.fromId() self.theOriginalToObject = parameters.toObject() self.theOriginalToId = parameters.toId() else: self.theOriginalFromObject = -1 self.theOriginalFromId = -1 self.theOriginalToObject = -1 self.theOriginalToId = -1 self.theFromObject = -1 self.theFromId = -1 self.theToObject = -1 self.theToId = -1 self.panel = 0 self.buildControls(parameters) self.theCommitVerb = 'Add' def buildControls(self,parameters): mainSizer = wx.BoxSizer(wx.VERTICAL) self.panel = TracePanel.TracePanel(self) self.panel.buildControls(parameters.createFlag()) mainSizer.Add(self.panel,1,wx.EXPAND) self.SetSizer(mainSizer) wx.EVT_BUTTON(self,TRACE_BUTTONCOMMIT_ID,self.onCommit) def load(self,threat): self.panel.loadControls(threat) self.theCommitVerb = 'Edit' def onCommit(self,evt): self.theFromObject = self.panel.theFromObject self.theFromId = self.panel.theFromId self.theToObject = self.panel.theToObject self.theToId = self.panel.theToId self.theFromName = self.panel.theFromName self.theToName = self.panel.theToName self.EndModal(TRACE_BUTTONCOMMIT_ID) def parameters(self): parameters = 0 if (self.theOriginalFromObject == -1): parameters = TraceParameters.TraceParameters(self.theFromObject,self.theFromId,self.theToObject,self.theToId,self.theFromName,self.theToName) else: parameters = UpdateTraceParameters.UpdateTraceParameters(self.theFromObject,self.theFromId,self.theToObject,self.theToId,self.theFromName,self.theToName,self.theOriginalFromId,self.theOriginalToId) parameters.setId(-1) return parameters
[ "shamal.faily@googlemail.com" ]
shamal.faily@googlemail.com
a39ac72e3dd8293bb7c5a117983a0650437216be
8e52e07428cb9ded3e96db45e9d9e4444ba80224
/vegetableOrder/migrations/0007_auto_20170422_1146.py
dff84affaada50f0eb21a18d502b84f3ebcf05f5
[]
no_license
prashantspandey/mohanamandi
c2f8a1763813f7df21db7579bcb44b9f390d870f
99231feaa9eb442d20a65a6754ec5b1df4e5208c
refs/heads/master
2021-01-20T05:15:31.741033
2017-04-29T05:44:32
2017-04-29T05:44:32
89,766,250
0
0
null
null
null
null
UTF-8
Python
false
false
747
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-22 06:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('vegetables', '0005_vegetable_subpricekg'), ('vegetableOrder', '0006_auto_20170422_1142'), ] operations = [ migrations.RemoveField( model_name='vegetable_order', name='ordercart', ), migrations.AddField( model_name='vegetable_order', name='orderveg', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='vegetables.Vegetable'), ), ]
[ "prashants_pandey@outlook.com" ]
prashants_pandey@outlook.com
b996c977517f5ce622b698b1872d39647e064362
06a863150a7a3a7bfc0c341b9c3f267727606464
/lib/gii/qt/controls/Settings.py
417bb2b0cbf6570f8ede7d3aaa6f6f5318978c4f
[ "MIT" ]
permissive
brucelevis/gii
c843dc738a958b4a2ffe42178cff0dd04da44071
03624a57cf74a07e38bfdc7f53c50bd926b7b5a7
refs/heads/master
2020-10-02T00:41:02.723597
2016-04-08T07:44:45
2016-04-08T07:44:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
426
py
from PyQt4 import QtCore globalSettings=QtCore.QSettings('Hatrix','GII') def setGlobalSettingFile(filepath): global globalSettings globalSettings=QtCore.QSettings(filepath, QtCore.QSettings.IniFormat) def getGlobalSettings(): return globalSettings def setSettingValue(name, value): globalSettings.setValue(name, value) def getSettingValue(name): return globalSettings.getValue(name) setGlobalSettingFile('gii.ini')
[ "tommo.zhou@gmail.com" ]
tommo.zhou@gmail.com
ddcb78be7a534d96575e83381e99bcf1d76d713c
a2706c66c4f2769c00fc5f67e1a85742cfa7e17c
/MODULES/Execution_UserExecution_NtCreateSection.py
f244911cfec971ee6844a6865d5e9bd77056d65a
[ "BSD-3-Clause" ]
permissive
Jeromeyoung/viperpython
48800312dcbdde17462d28d45865fbe71febfb11
ba794ee74079285be32191e898daa3e56305c8be
refs/heads/main
2023-09-01T18:59:23.464817
2021-09-26T04:05:36
2021-09-26T04:05:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,122
py
# -*- coding: utf-8 -*- # @File : SimpleRewMsfModule.py # @Date : 2019/1/11 # @Desc : import time from Lib.ModuleAPI import * class PostModule(PostPythonModule): NAME_ZH = "NtCreateSection进程注入" DESC_ZH = "使用NtCreateSection及NtMapViewOfSection远程线程注入技术打开共享内存,将shellcode注入到其他进程中" NAME_EN = "NtCreateSection process injection" DESC_EN = "Use NtCreateSection and NtMapViewOfSection remote thread injection technology to open shared memory and inject shellcode into other processes" MODULETYPE = TAG2TYPE.Execution PLATFORM = ["Windows"] # 平台 PERMISSIONS = ["User", "Administrator", "SYSTEM"] # 所需权限 ATTCK = [] # ATTCK向量 README = ["https://www.yuque.com/vipersec/module/hncv58"] REFERENCES = ["https://idiotc4t.com/code-and-dll-process-injection/untitled"] AUTHOR = "Viper" OPTIONS = register_options([ OptionHander(), ]) def __init__(self, sessionid, ipaddress, custom_param): super().__init__(sessionid, ipaddress, custom_param) def check(self): """执行前的检查函数""" payload = self.get_handler_payload() if "windows" not in payload: return False, "选择handler错误,请选择windows平台的监听", "Select the handler error, please select the handler of the windows platform" return True, None def run(self): shellcode = self.generate_hex_reverse_shellcode_by_handler() FUNCTION = self.random_str(8) FUNCTION1 = self.random_str(9) source_code = self.generate_context_by_template(filename="main.cpp", SHELLCODE_STR=shellcode, FUNCTION=FUNCTION, FUNCTION1=FUNCTION1) filename = f"NtCreateSection_{int(time.time())}.zip" self.write_zip_vs_project(filename, source_code, ) self.log_info("模块执行完成", "Module operation completed") self.log_good(f"请在<文件列表>中查看生成的源码: {filename}", f"Please check the generated source code in <Files>: {filename}")
[ "yu5890681@gmail.com" ]
yu5890681@gmail.com
22ff3c8ec043a748f85e7e330611f00ac0949c95
e86d020f8ade86b86df6ad8590b4458a9d415491
/projects/test-crrr/base_mission/utils/check_logger.py
c944ef41446f4be841f1c6a115e7d739a4cbadc0
[]
no_license
g842995907/guops-know
e4c3b2d47e345db80c27d3ba821a13e6bf7191c3
0df4609f3986c8c9ec68188d6304d033e24b24c2
refs/heads/master
2022-12-05T11:39:48.172661
2019-09-05T12:35:32
2019-09-05T12:35:32
202,976,887
1
4
null
2022-11-22T02:57:53
2019-08-18T08:10:05
JavaScript
UTF-8
Python
false
false
1,610
py
# -*- coding: utf-8 -*- import hashlib import logging import os import sys from cr_scene.utils.uitls import get_cr_scene_name from cr import settings def scene_log_key(scene_name, name): _key = hashlib.md5('{}-scene'.format(scene_name)).hexdigest() return _key class SceneLogFactory(object): logger_pool = {} def __new__(cls, scene_id, name): scene_name = get_cr_scene_name(scene_id) _key = scene_log_key(scene_name, name) if _key in cls.logger_pool: _logger = cls.logger_pool[_key] else: _logger = cls._generate(_key, scene_name) cls.logger_pool[_key] = _logger return _logger @classmethod def _generate(cls, key, scene_name): logger = logging.getLogger(key) # 指定logger输出格式 # formatter = logging.Formatter('%(levelname)s %(asctime)s %(module)s - %(message)s') formatter = logging.Formatter('%(levelname)s %(asctime)s - %(message)s') # 文件日志 file_handler = logging.FileHandler(os.path.join(settings.BASE_DIR, 'log/scene-{}.log'.format(scene_name))) file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式 # 控制台日志 console_handler = logging.StreamHandler(sys.stdout) console_handler.formatter = formatter # 也可以直接给formatter赋值 # 为logger添加的日志处理器 logger.addHandler(file_handler) logger.addHandler(console_handler) logger.setLevel(logging.INFO) logger.propagate = 0 return logger
[ "842995907@qq.com" ]
842995907@qq.com
e5766dadf98150deffa339dbefa2d888f7af7282
44869749f8af2b548a2fbb23403e1a623e29d691
/mysite/mysite/settings.py
208621a7982a95d9f9f745f6e2c27df05323735f
[]
no_license
Ojou/my-first-blog
4536c4db194d325508fd000ccd5919a722772994
e29be78c3c87b39c474dabf2a27387797c2d2a41
refs/heads/master
2016-08-12T15:27:52.761420
2016-03-12T05:06:06
2016-03-12T05:06:06
53,712,106
0
0
null
null
null
null
UTF-8
Python
false
false
3,164
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/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/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ze-3#6+ge)9r78ditv6bquz(&+2wkfs9a8o_zm$$_03r=c+c6m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/'
[ "admin@admin.com" ]
admin@admin.com
2d2a84da60052c7bbdf576522c35aae0207f76a4
75136cd1865bd72ebad8ba31446d57d9fdedce22
/pepysdiary/common/templatetags/search_tags.py
b9f9268357944463a88b44a9e284a80ec47c36ea
[]
no_license
hugovk/pepysdiary
ca9a1d39ed62e7299509daa69b5df0d5164aec31
1a67c11efb62f5392914732ad15a4db71872ed05
refs/heads/main
2021-12-03T01:36:16.626676
2021-11-08T17:29:51
2021-11-08T17:29:51
60,296,270
0
0
null
2016-06-02T20:48:07
2016-06-02T20:48:05
null
UTF-8
Python
false
false
1,582
py
from django import template from django.utils.html import format_html from django.utils.safestring import mark_safe from pepysdiary.common.utilities import hilite_words, trim_hilites register = template.Library() @register.simple_tag() def search_summary(obj, search_string): """ Returns the HTML to display search results summary text for an object. It's a series of bits of the object's text fields that contain the searched-for string, with the search term highlighted. obj - One of Annotation, Article, Entry, Letter, Post, Topic search_string - The string that was searched for. """ obj_name = obj.__class__.__name__ contents = [] if obj_name == "Entry": contents = [obj.text, obj.footnotes] elif obj_name == "Topic": contents = [obj.title, obj.summary_html, obj.wheatley_html, obj.wikipedia_html] elif obj_name == "Annotation": contents = [obj.comment] elif obj_name == "Letter": contents = [obj.title, obj.text, obj.footnotes] else: # Article, Post contents = [obj.title, obj.intro_html, obj.text_html] content = " ".join(contents) content = hilite_words(content, search_string) hilites = trim_hilites(content, allow_empty=False, max_hilites_to_show=10) if hilites["hilites_shown"] < hilites["total_hilites"]: difference = hilites["total_hilites"] - hilites["hilites_shown"] extra = f" <em>and {difference} more.</em>" else: extra = "" return format_html("{}{}", mark_safe(hilites["html"]), mark_safe(extra))
[ "phil@gyford.com" ]
phil@gyford.com
b6a956b9818da0da10270c5fa6aa0eaccf12a1d7
743c1aa4ae8336645785a5afd768a3c6c7189439
/BGWpy/BGW/__init__.py
460615f95d9f5ce43be3666023199be3687052ec
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause-LBNL" ]
permissive
kcantosh/BGWpy
566e03e888ab17b7d8ff7a68a6033d121532d905
fc5eda118ccdd18cdcdb88141df2b673456e8bd2
refs/heads/master
2021-06-25T14:21:33.426910
2017-08-28T18:43:40
2017-08-28T18:43:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
415
py
from __future__ import print_function from . import inputs # Core from . import bgwtask # Public from .kgrid import * from .epsilontask import * from .sigmatask import * from .kerneltask import * from .absorptiontask import * from .inteqptask import * __all__ = (epsilontask.__all__ + sigmatask.__all__ + kerneltask.__all__ + absorptiontask.__all__ + kgrid.__all__ + inteqptask.__all__)
[ "gabriel.antonius@gmail.com" ]
gabriel.antonius@gmail.com
3055b260778cf417707db8721cce2a574e8742a8
a9e3f3ad54ade49c19973707d2beb49f64490efd
/Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/discussion/rest_api/pagination.py
244d9b96a12060f9438120bf55da8fccfa069296
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
permissive
luque/better-ways-of-thinking-about-software
8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d
5809eaca7079a15ee56b0b7fcfea425337046c97
refs/heads/master
2021-11-24T15:10:09.785252
2021-11-22T12:14:34
2021-11-22T12:14:34
163,850,454
3
1
MIT
2021-11-22T12:12:31
2019-01-02T14:21:30
JavaScript
UTF-8
Python
false
false
2,689
py
""" Discussion API pagination support """ from edx_rest_framework_extensions.paginators import NamespacedPageNumberPagination from rest_framework.utils.urls import replace_query_param class _Page: """ Implements just enough of the django.core.paginator.Page interface to allow PaginationSerializer to work. """ def __init__(self, page_num, num_pages): """ Create a new page containing the given objects, with the given page number and number of pages """ self.page_num = page_num self.num_pages = num_pages def has_next(self): """Returns True if there is a page after this one, otherwise False""" return self.page_num < self.num_pages def has_previous(self): """Returns True if there is a page before this one, otherwise False""" return self.page_num > 1 def next_page_number(self): """Returns the number of the next page""" return self.page_num + 1 def previous_page_number(self): """Returns the number of the previous page""" return self.page_num - 1 class DiscussionAPIPagination(NamespacedPageNumberPagination): """ Subclasses NamespacedPageNumberPagination to provide custom implementation of pagination metadata by overriding it's methods """ def __init__(self, request, page_num, num_pages, result_count=0): """ Overrides parent constructor to take information from discussion api essential for the parent method """ self.page = _Page(page_num, num_pages) self.base_url = request.build_absolute_uri() self.count = result_count super().__init__() def get_result_count(self): """ Returns total number of results """ return self.count def get_num_pages(self): """ Returns total number of pages the response is divided into """ return self.page.num_pages def get_next_link(self): """ Returns absolute url of the next page if there's a next page available otherwise returns None """ next_url = None if self.page.has_next(): next_url = replace_query_param(self.base_url, "page", self.page.next_page_number()) return next_url def get_previous_link(self): """ Returns absolute url of the previous page if there's a previous page available otherwise returns None """ previous_url = None if self.page.has_previous(): previous_url = replace_query_param(self.base_url, "page", self.page.previous_page_number()) return previous_url
[ "rafael.luque@osoco.es" ]
rafael.luque@osoco.es
09c13e8d7e182c779642a9945ae1d18db780e082
dec7cac75fb472ab28b57228496b17fdbcf5df1d
/accounting/views.py
2b319b1591a9b8b214b969d1b42c9bb045ff0ca9
[]
no_license
sofide/apicolapp
a21be58982957b1115f73a3cc80bbce58832a739
32f9df4109540c6fb0c07dc9de2f557ec583a9d9
refs/heads/master
2021-06-22T22:34:53.075938
2019-03-28T01:27:13
2019-03-28T01:27:13
133,557,526
0
0
null
null
null
null
UTF-8
Python
false
false
8,131
py
from datetime import datetime, timedelta, date from django.contrib.auth.decorators import login_required from django.db.models import Q, Sum, Count, Prefetch from django.db.models.functions import Coalesce from django.shortcuts import render, get_object_or_404, redirect from accounting import forms from accounting.manage_data import purchases_by_categories from accounting.models import Product, Purchase, Category, Sale def dates_form_processor(request): """ Use this function inside a view to process DateFromToForm data. Return from_date, to_date and an instance of DateFromToForm. THIS FUNCTION IS NOT A VIEW """ # defaults from_date and to_date params # default period starts the last August 8 and ends today. to_date = datetime.now().date() if to_date.month >= 8: from_year = to_date.year else: from_year = to_date.year - 1 from_date = date(from_year, 8, 1) if request.GET.get('from_date'): dates_form = forms.DateFromToForm(request.GET) if dates_form.is_valid(): to_date = dates_form.cleaned_data['to_date'] from_date = dates_form.cleaned_data['from_date'] else: dates_form = forms.DateFromToForm() return from_date, to_date, dates_form @login_required def accounting_index(request): """ Show user's incomes and investments from last year, or between from_date and to_date recived in POST params. """ from_date, to_date, dates_form = dates_form_processor(request) # INVESTMENTS purchases = purchases_by_categories(request.user.pk, from_date, to_date) invested_money = 0 direct_expenses_data = {} depreciation_purchases_data = {} for categ_purchase in purchases.values(): invested_money += categ_purchase['amount'] if categ_purchase['depreciation_period']: data_dict = depreciation_purchases_data else: data_dict = direct_expenses_data data_dict['invested_money'] = round(data_dict.get('invested_money', 0) + categ_purchase['amount'], 2) data_dict['products_count'] = round(data_dict.get('products_count', 0) + categ_purchase['products']) data_dict['purchases_count'] = round(data_dict.get('purchases_count', 0) + categ_purchase['total']) # INCOMES sales = Sale.objects.filter( user=request.user, date__range=(from_date, to_date) ).aggregate( total=Coalesce(Count('id'), 0), total_income=Coalesce(Sum('value'), 0), total_kg=Coalesce(Sum('amount'), 0) ) result = round(sales['total_income'] - invested_money, 2) profit = result > 0 return render(request, 'accounting/accounting_index.html', { 'from_date': from_date, 'to_date': to_date, 'dates_form': dates_form, 'invested_money': invested_money, 'direct_expenses_data': direct_expenses_data, 'depreciation_purchases_data': depreciation_purchases_data, 'sales': sales, 'result': result, 'profit': profit, 'datepicker_fields_ids': ['id_from_date', 'id_to_date'], }) @login_required def purchase_list(request): from_date, to_date, dates_form = dates_form_processor(request) purchases = purchases_by_categories(request.user.pk, from_date, to_date) return render(request, 'accounting/purchases_list.html', { 'purchases': purchases, 'from_date': from_date, 'to_date': to_date, 'dates_form': dates_form, 'datepicker_fields_ids': ['id_from_date', 'id_to_date'], }) def product_index(request): pass @login_required def product_edit(request, product_pk=None): """Create or edit a product.""" def _next_page(product_object): """Define next page if form is valid.""" next = request.GET.get('next', None) if next == 'purchase': return redirect('purchase_detail', product_pk=product_object.pk) else: return redirect('product_index') if product_pk: product_instance = get_object_or_404(Product, pk=product_pk, user=request.user) else: product_instance = None if request.user.is_authenticated: if request.method == 'POST': product_form = forms.ProductForm(request.POST, instance=product_instance) if product_form.is_valid(): new_product = product_form.save(commit=False) new_product.user = request.user new_product.save() return _next_page(new_product) else: product_form = forms.ProductForm(instance=product_instance) return render(request, 'accounting/product_edit.html', { 'product_form': product_form, 'instance': product_instance, }) @login_required def purchase_product(request): """First purchase step. Select the product from historical purchases or load a new product. """ products = Product.objects.filter(user=request.user) categories = Category.objects.prefetch_related(Prefetch('products', queryset=products)) if products.exists(): response = render(request, 'accounting/purchase_product.html', { 'categories': categories, }) else: # edit redirect response to use new product in a purchase response = redirect('product_new') response['Location'] += '?next=purchase' return response @login_required def purchase_detail(request, product_pk, purchase_pk=None): """Second purchase step. Ask user for purchase information. """ product = get_object_or_404(Product, pk=product_pk, user=request.user) purchase_instance = None if purchase_pk: purchase_instance = get_object_or_404(Purchase, pk=purchase_pk, product=product) if request.method == 'POST': purchase_form = forms.PurchaseForm(request.POST, instance=purchase_instance) if purchase_form.is_valid(): new_purchase = purchase_form.save(commit=False) new_purchase.user = request.user new_purchase.product = product new_purchase.save() return redirect('purchase_list') else: purchase_form = forms.PurchaseForm(instance=purchase_instance) return render(request, 'accounting/purchase_detail.html', { 'purchase_form': purchase_form, 'product': product, 'purchase_instance': purchase_instance, }) @login_required def purchase_delete(request, purchase_pk): purchase = get_object_or_404(Purchase, pk=purchase_pk) purchase.delete() return redirect('purchase_list') @login_required def sales_list(request): """Show user's sales list.""" from_date, to_date, dates_form = dates_form_processor(request) sales = request.user.sales.filter(date__range=(from_date, to_date)) return render(request, 'accounting/sales_list.html', { 'sales': sales, 'from_date': from_date, 'to_date': to_date, 'dates_form': dates_form, 'datepicker_fields_ids': ['id_from_date', 'id_to_date'], }) @login_required def sale_new(request, sale_pk=None): """Save a new sale on the database.""" if sale_pk: sale_instance = get_object_or_404(Sale, pk=sale_pk) else: sale_instance = None if request.method == 'POST': sale_form = forms.SaleForm(request.POST, instance=sale_instance) if sale_form.is_valid(): new_sale = sale_form.save(commit=False) new_sale.user = request.user new_sale.save() return redirect('sales_list') else: sale_form = forms.SaleForm(instance=sale_instance) return render(request, 'accounting/sale_new.html', { 'sale_form': sale_form, 'sale_instance': sale_instance, }) @login_required def sale_delete(request, sale_pk): sale = get_object_or_404(Sale, pk=sale_pk) sale.delete() return redirect('sales_list')
[ "sofi.denner@gmail.com" ]
sofi.denner@gmail.com
c2d6f67753d23b501788801fb5ddc9bf1b830795
6cf46f85debb1b0505c0edcbc7296f50a44a615d
/dexy/tests/plugins/test_wordpress_filters.py
59635a82d9934c4853b96ef03431438d88b9812a
[ "MIT" ]
permissive
aioupload/dexy
27b7f5051417093d8336e39d71e824b3ef5c9f56
350b7ed23d2f3aab50097aabf3481229d75d1cf7
refs/heads/master
2021-01-16T22:59:11.707350
2013-08-05T06:08:00
2013-08-05T06:08:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,062
py
from dexy.doc import Doc from dexy.tests.utils import TEST_DATA_DIR from dexy.tests.utils import wrap from dexy.tests.utils import capture_stdout from mock import patch import dexy.exceptions import json import os import shutil import dexy.filter import dexy.wrapper def test_docmd_create_keyfile(): with wrap(): assert not os.path.exists(".dexyapis") dexy.filter.Filter.create_instance("wp").docmd_create_keyfile() assert os.path.exists(".dexyapis") def test_docmd_create_keyfile_if_exists(): with wrap(): with open(".dexyapis", "w") as f: f.write("{}") assert os.path.exists(".dexyapis") try: dexy.filter.Filter.create_instance("wp").docmd_create_keyfile() assert False, ' should raise exception' except dexy.exceptions.UserFeedback as e: assert ".dexyapis already exists" in e.message def test_api_url_with_php_ending(): with wrap(): with open(".dexyapis", "wb") as f: json.dump({ "wordpress" : {"url" : "http://example.com/api/xmlrpc.php"} }, f) url = dexy.filter.Filter.create_instance("wp").api_url() assert url == "http://example.com/api/xmlrpc.php" def test_api_url_without_php_ending(): with wrap(): with open(".dexyapis", "wb") as f: json.dump({ "wordpress" : {"url" : "http://example.com/api"} }, f) url = dexy.filter.Filter.create_instance("wp").api_url() assert url == "http://example.com/api/xmlrpc.php" def test_api_url_without_php_ending_with_trailing_slash(): with wrap(): with open(".dexyapis", "wb") as f: json.dump({ "wordpress" : {"url" : "http://example.com/api/"} }, f) url = dexy.filter.Filter.create_instance("wp").api_url() assert url == "http://example.com/api/xmlrpc.php" def test_wordpress_without_doc_config_file(): with wrap() as wrapper: wrapper.debug = False doc = Doc("hello.txt|wp", contents = "hello, this is a blog post", wrapper=wrapper ) wrapper.run_docs(doc) assert wrapper.state == 'error' def mk_wp_doc(wrapper): doc = Doc("hello.txt|wp", contents = "hello, this is a blog post", dirty = True, wrapper=wrapper ) for d in doc.datas(): d.setup() return doc ATTRS = { 'return_value.metaWeblog.newPost.return_value' : 42, 'return_value.metaWeblog.getPost.return_value' : { 'permaLink' : 'http://example.com/blog/42' }, 'return_value.wp.getCategories.return_value' : [ { 'categoryName' : 'foo' }, { 'categoryName' : 'bar' } ], 'return_value.wp.uploadFile.return_value' : { 'url' : 'http://example.com/example.pdf' } } @patch('xmlrpclib.ServerProxy', **ATTRS) def test_wordpress(MockXmlrpclib): with wrap(): with open("wordpress.json", "wb") as f: json.dump({}, f) with open(".dexyapis", "wb") as f: json.dump({ 'wordpress' : { 'url' : 'http://example.com', 'username' : 'foo', 'password' : 'bar' }}, f) # Create new (unpublished) draft wrapper = dexy.wrapper.Wrapper() doc = mk_wp_doc(wrapper) wrapper.run_docs(doc) with open("wordpress.json", "rb") as f: result = json.load(f) assert result['postid'] == 42 assert result['publish'] == False # Update existing draft wrapper = dexy.wrapper.Wrapper() doc = mk_wp_doc(wrapper) wrapper.run_docs(doc) assert doc.output_data().json_as_dict().keys() == ['permaLink'] result['publish'] = True with open("wordpress.json", "wb") as f: json.dump(result, f) # Publish existing draft wrapper = dexy.wrapper.Wrapper() doc = mk_wp_doc(wrapper) wrapper.run_docs(doc) assert "http://example.com/blog/42" in str(doc.output_data()) # Now, separately, test an image upload. orig = os.path.join(TEST_DATA_DIR, 'color-graph.pdf') shutil.copyfile(orig, 'example.pdf') from dexy.wrapper import Wrapper wrapper = Wrapper() doc = Doc("example.pdf|wp", wrapper=wrapper) with open(".dexyapis", "wb") as f: json.dump({ 'wordpress' : { 'url' : 'http://example.com', 'username' : 'foo', 'password' : 'bar' }}, f) wrapper.run_docs(doc) assert doc.output_data().as_text() == "http://example.com/example.pdf" # test list categories with capture_stdout() as stdout: dexy.filter.Filter.create_instance("wp").docmd_list_categories() assert stdout.getvalue() == "categoryName\nfoo\nbar\n"
[ "ana@ananelson.com" ]
ana@ananelson.com
179136706a176c379e4e834a4aa983bf7e7f6ac6
421f42acd37d3d02dda23bad4bc68cc58b481c00
/forensics/ekoparty-vnc/getvnckeys.py
0656a55d4ed0be982b14ead90bf9394e324d41a2
[]
no_license
sourcekris/ctf-solutions
6963d0a1524c4d5bd738d187e72f571bf608bd7a
3251f113c3a94732e432885fc785fb71d67d05e8
refs/heads/master
2021-08-27T18:13:00.902502
2021-08-25T07:59:46
2021-08-25T07:59:46
38,923,614
5
6
null
null
null
null
UTF-8
Python
false
false
1,048
py
#!/usr/bin/python # # Extract the VNC keystrokes from a PCAP using tshark # # kris, Capture The Swag # # http://github.com/sourcekris/ # import subprocess import sys import os import re if len(sys.argv) < 2: print "Usage: " + sys.argv[0] + " <pcap or pcapng>" sys.exit(-1) # read the tshark data in PDML format - hope its not huge DEVNULL = open(os.devnull,'w') print "[+] Reading pcap file: " + sys.argv[1] pdmllines = subprocess.check_output(['tshark','-r',sys.argv[1],'-Tpdml'],stderr=DEVNULL).splitlines() message = [] keydown = False for line in pdmllines: if 'name="vnc.key_down"' in line and 'showname="Key down: Yes"' in line: keydown = True elif 'name="vnc.key_down"' in line and 'showname="Key down: No"' in line: keydown = False elif keydown and 'name="vnc.key"' in line and 'showname="Key: ' in line: keyval = re.sub(r'[^a-f0-9]','',line.split('value=')[1])[-2:] try: chr(int(keyval,16)).decode('ascii') except: pass else: message.append(chr(int(keyval,16))) print "[+] Message: " + "".join(message)
[ "root@localhost.localdomain" ]
root@localhost.localdomain
4357960f8e003e9c912bd7ac3fd0ed1852c7932b
169e75df163bb311198562d286d37aad14677101
/tensorflow/tensorflow/contrib/autograph/utils/builtins_test.py
0c2312178a921037fa419818bf309d671c33914d
[ "Apache-2.0" ]
permissive
zylo117/tensorflow-gpu-macosx
e553d17b769c67dfda0440df8ac1314405e4a10a
181bc2b37aa8a3eeb11a942d8f330b04abc804b3
refs/heads/master
2022-10-19T21:35:18.148271
2020-10-15T02:33:20
2020-10-15T02:33:20
134,240,831
116
26
Apache-2.0
2022-10-04T23:36:22
2018-05-21T08:29:12
C++
UTF-8
Python
false
false
4,569
py
# Copyright 2017 The TensorFlow 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. # ============================================================================== """Tests for builtins module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import six from tensorflow.contrib.autograph.utils import builtins from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.platform import test class BuiltinsTest(test.TestCase): def test_dynamic_len_tf_scalar(self): a = constant_op.constant(1) with self.assertRaises(ValueError): with self.test_session() as sess: sess.run(builtins.dynamic_builtin(len, a)) def test_dynamic_len_tf_array(self): a = constant_op.constant([1, 2, 3]) with self.test_session() as sess: self.assertEqual(3, sess.run(builtins.dynamic_builtin(len, a))) def test_dynamic_len_tf_matrix(self): a = constant_op.constant([[1, 2], [3, 4]]) with self.test_session() as sess: self.assertEqual(2, sess.run(builtins.dynamic_builtin(len, a))) def test_dynamic_len_py_list(self): a = [3] * 5 self.assertEqual(5, builtins.dynamic_builtin(len, a)) def test_dynamic_range_all_python(self): self.assertListEqual(list(builtins.dynamic_builtin(range, 3)), [0, 1, 2]) self.assertListEqual(list(builtins.dynamic_builtin(range, 1, 3)), [1, 2]) self.assertListEqual( list(builtins.dynamic_builtin(range, 2, 0, -1)), [2, 1]) def test_dynamic_range_tf(self): with self.test_session() as sess: self.assertAllEqual( sess.run(builtins.dynamic_builtin(range, constant_op.constant(3))), [0, 1, 2]) self.assertAllEqual( sess.run(builtins.dynamic_builtin(range, 1, constant_op.constant(3))), [1, 2]) self.assertAllEqual( sess.run( builtins.dynamic_builtin(range, 2, 0, constant_op.constant(-1))), [2, 1]) def test_dynamic_range_detection(self): def range(x): # pylint:disable=redefined-builtin return x # Functions that just have the names of builtins are rejected. with self.assertRaises(NotImplementedError): self.assertEqual(builtins.dynamic_builtin(range, 1), 1) if six.PY2: self.assertListEqual( list(builtins.dynamic_builtin(xrange, 3)), [0, 1, 2]) self.assertListEqual( list(builtins.dynamic_builtin(six.moves.range, 3)), [0, 1, 2]) self.assertListEqual( list(builtins.dynamic_builtin(six.moves.xrange, 3)), [0, 1, 2]) def test_casts(self): i = constant_op.constant(2, dtype=dtypes.int32) f = constant_op.constant(1.0, dtype=dtypes.float32) self.assertEqual(builtins.dynamic_builtin(int, i).dtype, dtypes.int32) self.assertEqual(builtins.dynamic_builtin(int, f).dtype, dtypes.int32) self.assertEqual(builtins.dynamic_builtin(float, i).dtype, dtypes.float32) self.assertEqual(builtins.dynamic_builtin(float, f).dtype, dtypes.float32) self.assertEqual(builtins.dynamic_builtin(int, True), 1) self.assertEqual(builtins.dynamic_builtin(int, False), 0) self.assertEqual(builtins.dynamic_builtin(float, True), 1.0) self.assertEqual(builtins.dynamic_builtin(float, False), 0.0) def test_dynamic_print_tf(self): try: out_capturer = six.StringIO() sys.stdout = out_capturer with self.test_session() as sess: sess.run(builtins.dynamic_print('test message', 1)) self.assertEqual(out_capturer.getvalue(), 'test message 1\n') finally: sys.stdout = sys.__stdout__ def test_dynamic_print_complex(self): try: out_capturer = six.StringIO() sys.stdout = out_capturer with self.test_session() as sess: sess.run(builtins.dynamic_print('test message', [1, 2])) self.assertEqual(out_capturer.getvalue(), 'test message [1, 2]\n') finally: sys.stdout = sys.__stdout__ if __name__ == '__main__': test.main()
[ "thomas.warfel@pnnl.gov" ]
thomas.warfel@pnnl.gov
c8e05da4b1e368920092b454e82ee0183422509a
0c6b47f5647fa048e701c743bd61e05667b3b569
/101_Common_Dialogs/SingleChoiceDialog/__demo__.py
3556b9bda73bf996e3b30c39c0042e5e6c1cfb11
[]
no_license
pythonthings/wxPython-Sample-Apps-and-Demos
bbfa5c307c08bd0e732083a7e7ec0aaefa234033
65e6828e92217445367420c9c2ebb4a7ed9a1d6e
refs/heads/master
2022-10-02T18:41:01.697132
2020-06-10T00:18:15
2020-06-10T00:18:15
281,526,555
1
0
null
2020-07-21T23:32:51
2020-07-21T23:32:51
null
UTF-8
Python
false
false
2,243
py
#!/usr/bin/env python # -*- coding: utf-8 -*- #-MetaData -------------------------------------------------------------------- __doc__ = """ This module contains the meta data needed for integrating the samples in the directory into the wxPython demo framework. Once imported, this module returns the following information: * GetDemoBitmap: returns the bitmap used in the wxPython tree control to characterize the package; * GetDemos: returns all the demos in the package; * GetOverview: returns a wx.html-ready representation of the package's docs. These meta data are merged into the wxPython demo tree at startup. Last updated: User's Name @ 08 Aug 20xx, 21.00 GMT. Version 0.0.1 """ __version__ = "0.0.1" __author__ = "wxPython Team" #-Imports---------------------------------------------------------------------- #--wxPython Imports. import wx from wx.lib.embeddedimage import PyEmbeddedImage def GetDemoBitmap(): """ Returns the bitmap to be used for the demo tree item's bitmap. """ # Get the image as PyEmbeddedImage image = dialog16 = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAKRJ" "REFUeJytk0EOwjAMBGdRH+DvVOJVqLfCBZVbxadaJc8yB5RCSguEMhdLK3uzshWZGVuomkPj" "vw73114VQHtqkS5fD7q3SMLM2AFFw/P+KjmWIh0B7gkScYxFFYDu3Lm7exhCUQXczB4GpSYv" "Bn9J8AwwNS/pyWBa4tKC6n29qmdnTKKk7FRxjKt6Ikvg7oQhTDUlWNKzBPMXStDW37j73PKe" "G2AyEYLJPQvVAAAAAElFTkSuQmCC") # Return the bitmap to use in the wxPython demo tree control. return image def GetDemos(): """ Returns all the demo names in the package, together with the tree item name which will go in the wxPython demo tree control. """ # The tree item text. TreeItemText = "SingleChoiceDialog" # The tree item's demos. TreeItemDemos = ( 'SingleChoiceDialog_extended.py', 'SingleChoiceDialog_minimal.py', ) return TreeItemText, TreeItemDemos def GetOverview(): """ Creates the wxHTML code to display on the tree item's Overview tab. """ wxHtmlOverviewStr = '''\ <html><body> <center><h2>SingleChoiceDialog</h2></center> <p>SingleChoiceDialog demos. </body></html> ''' return wxHtmlOverviewStr
[ "metaliobovinus@gmail.com" ]
metaliobovinus@gmail.com
604e26e48551410e05524b6f2d4cec5c440f5fbf
ff1137a7d8f9c01632cf757495e065ec5e3817a2
/爬虫精进/第9关/第9关 selenium提取网页源代码后用bs解析.py
900588bc680a8a8384ae9a8b2ae68d504b017129
[]
no_license
yuqiuming2000/Python-code
3d5e5d8ba5c5f477b4cfab67b0d63d838eefc591
b16a6c425d4bf400df6b365d091f56bc8c5c4d34
refs/heads/master
2023-06-22T04:22:25.991172
2021-07-24T13:49:38
2021-07-24T13:49:38
389,100,344
0
0
null
null
null
null
UTF-8
Python
false
false
571
py
from selenium import webdriver #从selenium库中调用webdriver模块 import time from bs4 import BeautifulSoup driver = webdriver.Chrome() # 设置引擎为Chrome,真实地打开一个Chrome浏览器 driver.get('https://localprod.pandateacher.com/python-manuscript/hello-spiderman/') # 访问页面 time.sleep(2) # 等待2秒 page_source=driver.page_source print(page_source) bs=BeautifulSoup(page_source,'html.parser') labels=bs.find_all('label') # print(type(labels)) # 打印labels的数据类型 for i in labels: print(i.text) driver.close() # 关闭浏览器
[ "76746694@qq.com" ]
76746694@qq.com
317167f3c7c18125e0cf23dbcaad084d793b878d
01fa2aca31eb73a559d192fd29e44350f26a13a9
/HAX/18.CocoJoe/script.module.lambdascrapers/lib/lambdascrapers/sources_quick/unchecked/putlockersio.py
66419b703d52903a2d204fa04395dc04459b9fd2
[ "Beerware" ]
permissive
RandomIntermition/k4y108837s
b4beedeff375645bd4fa9ad348631a9a9f3640b6
e9115aad49795dfe30a96c278cedaf089abcc11d
refs/heads/master
2022-05-01T18:45:57.298903
2022-03-30T03:41:08
2022-03-30T03:41:08
109,356,425
1
0
null
2019-11-08T02:20:47
2017-11-03T05:36:48
Python
UTF-8
Python
false
false
1,662
py
# -*- coding: UTF-8 -*- # -Cleaned and Checked on 10-16-2019 by JewBMX in Scrubs. import re from resources.lib.modules import client from resources.lib.modules import cleantitle from resources.lib.modules import more_sources class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['putlockers.io'] self.base_link = 'https://putlockers.io' def movie(self, imdb, title, localtitle, aliases, year): try: mTitle = cleantitle.geturl(title) url = self.base_link + '/movies/' + mTitle return url except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year): try: url = cleantitle.geturl(tvshowtitle) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if not url: return url = self.base_link + '/episodes/' + url + '-' + season + 'x' + episode return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources page = client.request(url) links = re.compile('<iframe.+?src="(.+?)"', re.DOTALL).findall(page) for link in links: for source in more_sources.getMore(link, hostDict): sources.append(source) return sources except: return sources def resolve(self, url): return url
[ "github+github@github.github" ]
github+github@github.github
7cc3e50af6a48ca74abfc02656c9019972018641
499fc7e223551d434582417353203ecd53b7d731
/DataTypeandManipulation/TypeCasting.py
efab449b81a11562cf61c91d04d3c343f363a5ba
[]
no_license
pravinherester/LearnPython
df53045e4b098a9923e7ecbbeffedb75f6c82f81
05c06dccd9ac45fc30cf0675f89f0bb2c7db6644
refs/heads/master
2023-08-11T10:12:50.494666
2021-06-19T04:44:12
2021-09-10T01:20:58
338,636,734
0
1
null
null
null
null
UTF-8
Python
false
false
342
py
num_char=len(input("What is your name")) print(type(num_char)) new_num_char=str(num_char) print("After type casting") print(type(new_num_char)) print("Your name has "+new_num_char+ " characters") # This will not break as the Type of new_num_char is String now #other #Guess what will print print(100+float(100.75)) print(str(100)+str(100))
[ "replituser@example.com" ]
replituser@example.com
3423017cde1fa95647f30b289fef5e2249c48c80
25114b282d36bf67448582fa73eb50ee350c4da7
/multicolor_backend_theme/__init__.py
aa487b80d227678e989bbb6cdf900a094b116d0e
[]
no_license
inst-sol4u/CybroAddons
7b888628e1a1bdc21eee3c82f0c975271cc5f238
39a50294785209c4964f5925d7129bdc9d4af4e4
refs/heads/14.0
2023-08-18T11:51:45.494958
2021-09-24T09:50:43
2021-09-24T09:50:43
372,519,765
0
0
null
2021-05-31T13:40:19
2021-05-31T13:40:19
null
UTF-8
Python
false
false
992
py
# -*- coding: utf-8 -*- ############################################################################## # # Cybrosys Technologies Pvt. Ltd. # # Copyright (C) 2020-TODAY Cybrosys Technologies(<https://www.cybrosys.com>). # Author: Cybrosys Techno Solutions (<https://www.cybrosys.com>) # you can modify it under the terms of the GNU LESSER # GENERAL PUBLIC LICENSE (AGPL v3), Version 3. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU LESSER GENERAL PUBLIC LICENSE (AGPL v3) for more details. # # You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE # GENERAL PUBLIC LICENSE (AGPL v3) along with this program. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import models from . import controllers
[ "ajmal@cybrosys.in" ]
ajmal@cybrosys.in
a7ea9d535013853895485bb04c94a3fbfcc123c2
7fc03f7d28ea7bbdca650a51a23fc0b13cbefde1
/reinforcement_learning/0x00-q_learning/1-q_init.py
d42a24aba80da020f4cb8c8a81a025823604dba3
[]
no_license
HeimerR/holbertonschool-machine_learning
54c410e40d38635de482773f15e26ce1c2c95e46
e10b4e9b6f3fa00639e6e9e5b35f0cdb43a339a3
refs/heads/master
2021-07-24T09:33:25.833269
2021-01-14T00:21:45
2021-01-14T00:21:45
236,603,791
0
6
null
null
null
null
UTF-8
Python
false
false
401
py
#!/usr/bin/env python3 """ Initialize Q-table """ import numpy as np def q_init(env): """ initializes the Q-table - env is the FrozenLakeEnv instance Returns: the Q-table as a numpy.ndarray of zeros """ action_space_size = env.action_space.n state_space_size = env.observation_space.n q_table = np.zeros((state_space_size, action_space_size)) return q_table
[ "ing.heimer.rojas@gmail.com" ]
ing.heimer.rojas@gmail.com
f622e236dad0ae272bf7f9ba003242f9017f8e62
faf512a387355c5a6e5af59fc48aa2a79762344c
/playground/bot_runner.py
2dfbcdc23780892642059da3e9d5e2c61716e453
[ "Apache-2.0" ]
permissive
lawrencechen0921/ExcelLexBot
f80f848058af284f8595206a9e510baf21d013b1
97041c47c06ba42cb10630d78b2300b113b6b3bf
refs/heads/master
2021-07-09T10:58:51.155580
2019-10-28T08:15:15
2019-10-28T08:15:15
229,690,075
0
0
Apache-2.0
2021-03-20T05:10:26
2019-12-23T06:23:00
null
UTF-8
Python
false
false
271
py
import boto3 import json client = boto3.client('lex-runtime', region_name='us-east-1') response = client.post_text( botName='ScheduleAppointmentBot', botAlias='$LATEST', userId='UserOne', inputText='book a hotel') print(json.dumps(response, indent=4))
[ "cywong@vtc.edu.hk" ]
cywong@vtc.edu.hk
28fb47d43c5f1a043a47867a3eea10ad3e89707d
53cb38bba0f95ddbffd83a9e45c9eed602694265
/muddery/commands/default_cmdsets.py
9564a9cc053c9b9d55621a2346b48167a0c66bd4
[ "BSD-3-Clause" ]
permissive
elove88/muddery
4356eb0203edeb26285b2bf032f410a8e6e4fb3b
55dabb2d8d5fbf87ef0e7f2a2a0722251510a254
refs/heads/master
2021-09-05T23:30:33.835858
2018-01-31T13:50:26
2018-01-31T13:50:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,733
py
""" Command sets All commands in the game must be grouped in a cmdset. A given command can be part of any number of cmdsets and cmdsets can be added/removed and merged onto entities at runtime. To create new commands to populate the cmdset, see `commands/command.py`. """ import traceback from evennia import CmdSet from evennia import default_cmds from muddery.commands import combat from muddery.commands import general from muddery.commands import player from muddery.commands import unloggedin class CharacterCmdSet(default_cmds.CharacterCmdSet): """ The `CharacterCmdSet` contains general in-game commands like `look`, `goto`, etc available on in-game Character objects. It is merged with the `PlayerCmdSet` when a Player puppets a Character. """ key = "DefaultCharacter" def at_cmdset_creation(self): """ Populates the cmdset """ super(CharacterCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # self.add(general.CmdLook()) self.add(general.CmdGoto()) self.add(general.CmdInventory()) self.add(general.CmdTalk()) self.add(general.CmdDialogue()) self.add(general.CmdLoot()) self.add(general.CmdUse()) self.add(general.CmdDiscard()) self.add(general.CmdEquip()) self.add(general.CmdTakeOff()) self.add(general.CmdCastSkill()) self.add(general.CmdAttack()) self.add(general.CmdMakeMatch()) self.add(general.CmdGetRankings()) self.add(general.CmdQueueUpCombat()) self.add(general.CmdQuitCombatQueue()) self.add(general.CmdConfirmCombat()) self.add(general.CmdRejectCombat()) self.add(general.CmdUnlockExit()) self.add(general.CmdGiveUpQuest()) self.add(general.CmdShopping()) self.add(general.CmdBuy()) self.add(general.CmdSay()) self.add(general.CmdAction()) self.add(general.CmdTest()) # Add empty login commands to the normal cmdset to # avoid showing wrong cmd messages. self.add(general.CmdConnect()) self.add(general.CmdCreate()) self.add(general.CmdCreateConnect()) class AccountCmdSet(default_cmds.AccountCmdSet): """ This is the cmdset available to the Player at all times. It is combined with the `CharacterCmdSet` when the Player puppets a Character. It holds game-account-specific commands, channel commands, etc. """ key = "DefaultAccount" def at_cmdset_creation(self): """ Populates the cmdset """ super(AccountCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # self.add(player.CmdQuit()) self.add(player.CmdPuppet()) self.add(player.CmdUnpuppet()) self.add(player.CmdCharCreate()) self.add(player.CmdCharDelete()) self.add(player.CmdCharAll()) class UnloggedinCmdSet(default_cmds.UnloggedinCmdSet): """ Command set available to the Session before being logged in. This holds commands like creating a new account, logging in, etc. """ key = "DefaultUnloggedin" def at_cmdset_creation(self): """ Populates the cmdset. """ self.add(unloggedin.CmdUnconnectedLoginStart()) self.add(unloggedin.CmdUnconnectedLook()) self.add(unloggedin.CmdUnconnectedCreate()) self.add(unloggedin.CmdUnconnectedConnect()) self.add(unloggedin.CmdUnconnectedQuit()) self.add(unloggedin.CmdQuickLogin()) class SessionCmdSet(default_cmds.SessionCmdSet): """ This cmdset is made available on Session level once logged in. It is empty by default. """ key = "DefaultSession" def at_cmdset_creation(self): """ This is the only method defined in a cmdset, called during its creation. It should populate the set with command instances. As and example we just add the empty base `Command` object. It prints some info. """ super(SessionCmdSet, self).at_cmdset_creation() # # any commands you add below will overload the default ones. # class CombatCmdSet(CmdSet): """ When players are in combat, the combat cmdset will replace the normal cmdset. The normal cmdset will be recoverd when the combat is over. """ key = "combat_cmdset" mergetype = "Replace" priority = 10 no_exits = True def at_cmdset_creation(self): self.add(general.CmdLook()) self.add(general.CmdCastSkill()) self.add(combat.CmdCombatInfo())
[ "luyijun999@gmail.com" ]
luyijun999@gmail.com
98981f55c9eccb1768ee4877f1033ddb4650bbc7
749cf1cfba5e0113b9619d46aa55edc7abb4aca4
/src/scs_mfr/test/test.py
ecca4b9e84bbd9f1834c0eea55da6dda3ad04b4f
[ "MIT" ]
permissive
caspar/scs_mfr
b65fcd51e6561370f9fb1d6482f0717d7058e535
90f3604190c883c39ceddd1ce56a36d72e628e8d
refs/heads/master
2020-03-22T22:07:35.063124
2018-07-06T12:20:38
2018-07-06T12:20:38
140,734,794
0
0
null
2018-07-12T15:52:36
2018-07-12T15:52:36
null
UTF-8
Python
false
false
1,278
py
""" Created on 18 May 2017 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ from abc import abstractmethod # -------------------------------------------------------------------------------------------------------------------- class Test(object): """ classdocs """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): self.__verbose = verbose self.__datum = None # ---------------------------------------------------------------------------------------------------------------- @abstractmethod def conduct(self): pass # ---------------------------------------------------------------------------------------------------------------- @property def datum(self): return self.__datum @datum.setter def datum(self, value): self.__datum = value @property def verbose(self): return self.__verbose # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return self.__class__.__name__ + ":{datum:%s, verbose:%s}" % (self.datum, self.verbose)
[ "bruno.beloff@southcoastscience.com" ]
bruno.beloff@southcoastscience.com
bb711b9545190d0bb301ef3888269d53576f13a7
8d9318a33afc2c3b5ca8ac99fce0d8544478c94a
/Books/Casandra DB/opscenter-5.1.0/lib/py-win32/2.7/twisted/internet/address.py
aea84bf68bbed91d502c7072beb96a2ac2766dff
[]
no_license
tushar239/git-large-repo
e30aa7b1894454bf00546312a3fb595f6dad0ed6
9ee51112596e5fc3a7ab2ea97a86ec6adc677162
refs/heads/master
2021-01-12T13:48:43.280111
2016-11-01T22:14:51
2016-11-01T22:14:51
69,609,373
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:a515bfec9ac845d6ff70998513414bc502c31a8567def729df1252d0faeb057b size 4196
[ "tushar239@gmail.com" ]
tushar239@gmail.com
69ee5e0cc7739ebcbee9d1a3e5819b28dde34833
32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd
/benchmark/signal/testcase/firstcases/testcase1_016.py
e81237d6fa82e693c08ba184b53c1b1c193da30e
[]
no_license
Prefest2018/Prefest
c374d0441d714fb90fca40226fe2875b41cf37fc
ac236987512889e822ea6686c5d2e5b66b295648
refs/heads/master
2021-12-09T19:36:24.554864
2021-12-06T12:46:14
2021-12-06T12:46:14
173,225,161
5
0
null
null
null
null
UTF-8
Python
false
false
3,616
py
#coding=utf-8 import os import subprocess import time import traceback from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, WebDriverException desired_caps = { 'platformName' : 'Android', 'deviceName' : 'Android Emulator', 'platformVersion' : '4.4', 'appPackage' : 'org.thoughtcrime.securesms', 'appActivity' : 'org.thoughtcrime.securesms.ConversationListActivity', 'resetKeyboard' : True, 'androidCoverage' : 'org.thoughtcrime.securesms/org.thoughtcrime.securesms.JacocoInstrumentation', 'noReset' : True } def command(cmd, timeout=5): p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) time.sleep(timeout) p.terminate() return def getElememt(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str) return element def getElememtBack(driver, str1, str2) : for i in range(0, 2, 1): try: element = driver.find_element_by_android_uiautomator(str1) except NoSuchElementException: time.sleep(1) else: return element for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str2) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str2) return element def swipe(driver, startxper, startyper, endxper, endyper) : size = driver.get_window_size() width = size["width"] height = size["height"] try: driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) except WebDriverException: time.sleep(1) driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) return # testcase016 try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) element = getElememt(driver, "new UiSelector().resourceId(\"org.thoughtcrime.securesms:id/sms_failed_indicator\").className(\"android.widget.ImageView\")") TouchAction(driver).long_press(element).release().perform() element = getElememt(driver, "new UiSelector().resourceId(\"org.thoughtcrime.securesms:id/sms_failed_indicator\").className(\"android.widget.ImageView\")") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"133\")", "new UiSelector().className(\"android.widget.TextView\").instance(3)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Your version of Signal has expired!\")", "new UiSelector().className(\"android.widget.TextView\").instance(1)") TouchAction(driver).tap(element).perform() except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"1_016\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() if (cpackage != 'org.thoughtcrime.securesms'): cpackage = "adb shell am force-stop " + cpackage os.popen(cpackage)
[ "prefest2018@gmail.com" ]
prefest2018@gmail.com
d38fe136135727031be58d9f7ae57117d9659ff6
0d45e05e1eda670b233081118bbcb63743c166db
/web/act_assist/settings.py
98cdcc4d0b82667a1b1f93b5264afd75a34cc1cd
[ "MIT" ]
permissive
maleriepace/activity-assistant
24ef7e4e6488e31726ba21c07acda83a7119f979
c5baa21f3d22db18da591ddf76e7bf6a7e7229cc
refs/heads/master
2023-01-31T15:53:30.100115
2020-12-13T14:41:04
2020-12-13T14:41:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,996
py
""" Django settings for hassbrain_web project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import logging logger = logging.getLogger(__name__) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] # allow hosts for the home net #ALLOWED_HOSTS += ['192.168.178.{}'.format(j) for j in range(256)] ALLOWED_HOSTS = ['*'] # TODO debug measure # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'qr_code', 'rest_framework.authtoken', 'frontend.apps.FrontendConfig', 'backend.apps.BackendConfig', ] 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 = 'act_assist.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'act_assist.wsgi.application' # Password validation # https://docs.djangoproject.com/en/2.1/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.1/topics/i18n/ LANGUAGE_CODE = 'en-us' # every use is corrected by using own methods e.g current_time in frontend.util TIME_ZONE = 'UTC' USE_TZ = False USE_I18N = True USE_L10N = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' SERVE_MEDIA = True MEDIA_URL = '/media/' HASS_API_URL = 'http://supervisor/core/api' DATA_ROOT = '/data/' MEDIA_ROOT = DATA_ROOT + 'media/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DATA_ROOT + 'db.sqlite3', } } # experiment POLL_INTERVAL_LST = ['5s', '1m', '10m', '30m', '2h', '6h'] DATASET_PATH = DATA_ROOT + 'datasets/' # path where all the datasets lie ACTIVITY_FILE_NAME="activities_subject_%s.csv" ACTIVITY_MAPPING_FILE_NAME="activity_mapping.csv" DATA_FILE_NAME='devices.csv' DATA_MAPPING_FILE_NAME='device_mapping.csv' PRIOR_ACTIVITY_FILE_NAME = "prior_activities_subject_%s.csv" DEV_ROOM_ASSIGNMENT_FILE_NAME = "devices_and_areas.csv" ACT_ROOM_ASSIGNMENT_FILE_NAME = "activities_and_areas.csv" DB_URL = 'sqlite:////config/home-assistant_v2.db' ACT_ASSIST_VERSION = "v0.0.1-alpha" ACT_ASSIST_RELEASE_LINK = "https://github.com/tcsvn/activity-assistant-logger/releases/download/{}/activity-assistant.apk".format(ACT_ASSIST_VERSION) # API URLS URL_SERVER = r'server' URL_DEVICE_PREDICTIONS = r'devicepredictions' URL_ACTIVITY_PREDICTIONS = r'activitypredictions' URL_PERSONS = r'/person/' URL_SYNTHETIC_ACTIVITY = r'syntheticactivity' URL_DEVICE_COMPONENT = r'devcomp' # qrcode cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'qr-code': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'qr-code-cache', 'TIMEOUT': 3600 } } QR_CODE_CACHE_ALIAS = 'qr-code' from os import environ ENV_SETTINGS = environ.get('DJANGO_ENV') or 'development' if ENV_SETTINGS == 'development': try: from act_assist.local_settings.development import * except ImportError: logger.error('couldn\'t import development settings') raise elif ENV_SETTINGS == 'production': try: from act_assist.local_settings.production import * except ImportError: logger.error('couldn\'t import development settings') raise
[ "account@meier-lossburg.com" ]
account@meier-lossburg.com
3e28462872d134c1fbcd211fc3c8b0fff0004cc3
c50c7111279fc9cfb75f414bf72b7faeb3aa93bc
/raise.py
7161dd53a065fee7228038e606e670a75e67b1e7
[]
no_license
Hemanthtm2/Python
d95cbd89778074dc87d75e86c75f998b6e419c93
64a21c9a6dadf2bb92616fbdc4209119afcaa562
refs/heads/master
2021-08-24T07:24:20.509134
2017-11-07T18:35:44
2017-11-07T18:35:44
108,621,725
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
#!/usr/bin/pyrhon def inputnumber(): x=input('Pick a number') if x==17: raise ValueError,'17 is a bad number' return x print inputnumber()
[ "hemanthtm2@gmail.com" ]
hemanthtm2@gmail.com
c8f4bb67eb5023fb6754b7accaaecaa3d3c89059
b7312dc013ba06e5b44b33c0411f4948c4794346
/study4/decorator3.py
866d868685ac97384a6c6229bf76635ac05af61f
[]
no_license
GaoFuhong/python-code
50fb298d0c1e7a2af55f1e13e48063ca3d1a189f
7d17c98011e5a1e74d49332da9f87f5cb576822d
refs/heads/master
2021-02-07T20:25:06.997173
2020-03-01T02:22:41
2020-03-01T02:26:04
244,072,971
1
0
null
null
null
null
UTF-8
Python
false
false
947
py
# Author:Fuhong Gao #嵌套函数 # def foo(): # print("in the foo...") # def bar(): # print("in the bar...") # bar() # foo() #一个简单的装饰器(注意:在定义函数时,函数名应避免使用test1、rest2...否则容易出错) import time def timer(func): #将test1和test2传给func #定义一个函数(“变量”) def deco(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print("the func running time is %s" %(stop_time - start_time)) return deco #返回函数名 @timer #等价于:test1 = timer(test1),哪个函数要使用装饰器,就在它的头部加上@timer def fun1(): #不含参数 time.sleep(1) print("in the test1...") @timer #test2 = timer(test2) test2(name,age) = deco(name,age) def fun2(name,age): #含参数 time.sleep(1) print("name:",name,"age:",age) fun1() fun2("gfh",22)
[ "1350086369@qq.com" ]
1350086369@qq.com
62b6f24a18c8dc7368fbaa3d566c57711600b466
e2e08d7c97398a42e6554f913ee27340226994d9
/pyautoTest-master(ICF-7.5.0)/test_case/scg/scg_LOG/test_c142794.py
1fff26fd926e1ae41c0fb8a21027628e495f9ba9
[]
no_license
lizhuoya1111/Automated_testing_practice
88e7be512e831d279324ad710946232377fb4c01
b3a532d33ddeb8d01fff315bcd59b451befdef23
refs/heads/master
2022-12-04T08:19:29.806445
2020-08-14T03:51:20
2020-08-14T03:51:20
287,426,498
0
0
null
null
null
null
UTF-8
Python
false
false
1,709
py
import pytest import time import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from page_obj.scg.scg_def_physical_interface import * from page_obj.scg.scg_def_vlan_interface import * from page_obj.scg.scg_def_bridge import * from page_obj.common.rail import * from page_obj.scg.scg_def_log import * from page_obj.common.ssh import * from page_obj.scg.scg_def_dhcp import * from page_obj.scg.scg_dev import * from page_obj.scg.scg_def_ifname_OEM import * from page_obj.scg.scg_def import * test_id = 142794 def test_c142794(browser): try: login_web(browser, url=dev1) add_email_alarm_jyl(browser, enable="yes", email_name="email_alert_jia_1", email_add="jyl@baomutech.com", cc_email="yes", cc_email_add="m18822678505@163.com", format="syslog", project="yes", project_content="300", disk_full="yes", save="yes") edit_email_alarm_jyl(browser, email_alert="email_alert_jia_1", format="welf", save="yes") edit_email_alarm_jyl(browser, email_alert="email_alert_jia_1", format="csv", save="yes") loginfo = get_log(browser, 管理日志) # print(loginfo) delete_email_alarm_server_jyl(browser, email_alarm="email_alert_jia_1") try: assert "配置 [EMAIL ALERT]对象成功" in loginfo rail_pass(test_run_id, test_id) except: rail_fail(test_run_id, test_id) assert "配置 [EMAIL ALERT]对象成功" in loginfo except Exception as err: # 如果上面的步骤有报错,重新设备,恢复配置 print(err) reload(hostip=dev1) rail_fail(test_run_id, test_id) assert False if __name__ == '__main__': pytest.main(["-v", "-s", "test_c" + str(test_id) + ".py"])
[ "15501866985@163.com" ]
15501866985@163.com
eed1238d3a0fd05c591f3ee36a20a12e4ab9be07
74bf86f99cc75006716edf5e25b040d1265ea134
/forms.py
ae87ae5091d5c25ebab6d13b38b9d4a2d40c1c31
[]
no_license
guoweikuang/flask_blog
65ed13c9660e699d4ec3b01212c6dcd41bb7e5d9
1292918b81029fd5b149486d8a8478fc02b92618
refs/heads/master
2022-12-09T05:46:17.093246
2017-07-12T15:28:27
2017-07-12T15:28:27
94,674,289
0
0
null
2022-12-07T23:59:57
2017-06-18T08:15:43
JavaScript
UTF-8
Python
false
false
623
py
# -*- coding: utf-8 -*- import re from flask_wtf import FlaskForm from wtforms import StringField, TextField from wtforms import ValidationError from wtforms.validators import DataRequired, Length def custom_email(form_object, field_object): """自定义检验器,邮箱格式检验""" if not re.match(r"[^@+@[^@]+\.[^@]]+", field_object): raise ValidationError(u'邮箱地址格式不对!!!') class CommentForm(FlaskForm): """评论表单""" name = StringField(u'名字', validators=[DataRequired(), Length(max=255)]) text = TextField(u"内容", validators=[DataRequired()])
[ "673411814@qq.com" ]
673411814@qq.com
44886b5540adf62e789a3e14c8bdb407164c6454
fc6bc4cf23f713e3e4a97c00f724c977b3adbf82
/venv/Scripts/rst2html4.py
cea8afb9d0e6e8c96822dd5798e93d5ce73aa0b3
[]
no_license
Startrekker007/SInglePhotons
8b429e29f78977adfa7711e8dae2cb864a13ea53
529c2ab3ea3c3797db4dd4e0a336ce35ea2e64a1
refs/heads/master
2022-12-12T16:38:56.412370
2020-02-04T00:19:57
2020-02-04T00:19:57
223,832,514
2
2
null
2022-12-08T09:25:43
2019-11-25T00:41:41
VHDL
UTF-8
Python
false
false
738
py
#!D:\SInglePhotons\venv\Scripts\python.exe # $Id: rst2html4.py 7994 2016-12-10 17:41:45Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing (X)HTML. The output conforms to XHTML 1.0 transitional and almost to HTML 4.01 transitional (except for closing empty tags). """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) publish_cmdline(writer_name='html4', description=description)
[ "joe.borbely@gmail.com" ]
joe.borbely@gmail.com
74d32a699bdd95a5f76f5892163733b31d4f7216
e203ddace08580170e3b4de9c79588209e857c1c
/dice.py
abdae853c875404a92648d58684acab4c6db318b
[]
no_license
stradtkt/OOPTreehouse-Python
e17f3fd48840049b8b741aa0e30e54d1409804b2
84e0ef2142118bf44c416a3b1dde3519ff57fd15
refs/heads/main
2023-02-26T15:03:27.053205
2021-02-04T13:04:26
2021-02-04T13:04:26
334,620,181
0
0
null
null
null
null
UTF-8
Python
false
false
935
py
import random class Die: def __init__(self, sides=2, value=0): if not sides >= 2: raise ValueError("Must have at least 2 sides") if not isinstance(sides, int): raise ValueError("Sides must be a whole number") self.value = value or random.randint(1, sides) def __int__(self): return self.value def __eq__(self, other): return int(self) == other def __ne__(self, other): return int(self) != other def __gt__(self, other): return int(self) > other def __lt__(self, other): return int(self) < other def __ge__(self, other): return int(self) > other or int(self) == other def __le__(self, other): return int(self) < other or int(self) == other def __repr__(self): return str(self.value) class D6(Die): def __init__(self, value=0): super().__init__(sides=6, value=value)
[ "stradtkt22@gmail.com" ]
stradtkt22@gmail.com
b99a5769e37c7e91afb7a10ecf5019595817fcd5
09120532659f7eb134163f92ac2f65423a04dc03
/zproject/django/survey/teacher/migrations/0006_remove_question_page.py
b68e92589867082131f7e2af6969e05cc1c2cfca
[]
no_license
hoboland21/survey
7b2dafd76db0e9317037a0cec163a97c0ec9a8ec
93e71f3304b381a6be03c8f813d2ba3a0b6eb218
refs/heads/master
2023-01-28T07:38:38.934710
2019-05-13T08:55:41
2019-05-13T08:55:41
182,874,928
0
0
null
null
null
null
UTF-8
Python
false
false
328
py
# Generated by Django 2.2.1 on 2019-05-13 07:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('teacher', '0005_auto_20190502_0008'), ] operations = [ migrations.RemoveField( model_name='question', name='page', ), ]
[ "jc@saipantech.com" ]
jc@saipantech.com
0a2d611f2578b26b114f89d0df16482b4e00844f
37b2998b537673f0b2b0237887fe3ab1b4c525d1
/workbench/offers/migrations/0002_offer_project.py
0ced7448d48e952a677f636985a60ce7075c79c0
[ "MIT" ]
permissive
ndarvishev/workbench
1076fc86522884a3128fab25cd7f6f8162a152f4
e93c35180990ee3424fbb7b73e26400cb869e29a
refs/heads/main
2023-05-30T23:47:36.948646
2021-06-25T08:43:15
2021-06-25T08:43:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
619
py
# Generated by Django 2.1.7 on 2019-03-04 21:39 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [("projects", "0001_initial"), ("offers", "0001_initial")] operations = [ migrations.AddField( model_name="offer", name="project", field=models.ForeignKey( on_delete=django.db.models.deletion.PROTECT, related_name="offers", to="projects.Project", verbose_name="project", ), ) ]
[ "mk@feinheit.ch" ]
mk@feinheit.ch
dbadb79e1a21ae2572a427526517b255f2b2e995
2b25aae9266437b657e748f3d6fea4db9e9d7f15
/graphics/3d/8/Andreas_Wang/parser.py
6a3bff914ce674c14def05ef60a827e30890a319
[]
no_license
Zilby/Stuy-Stuff
b1c3bc23abf40092a8a7a80e406e7c412bd22ae0
5c5e375304952f62667d3b34b36f0056c1a8e753
refs/heads/master
2020-05-18T03:03:48.210196
2018-11-15T04:50:03
2018-11-15T04:50:03
24,191,397
0
0
null
null
null
null
UTF-8
Python
false
false
5,670
py
from display import * from matrix import * from draw import * from math import * from types import * # I had a neurotic need for everything to match the math notation of # matrices being defined as rows x columns, so my matrix items I read # as matrix[row][column] # Since this would mean our point matrix is an n by 4 matrix, # not a 4 by n matrix, in order to make this work, I flipped... # everything. So every single transformation is... flipped. # As is the order of the multiplication (I do points x transform). # Fortunately this only means my transform matrix is flipped along # a diagonal and should only be mildly instead of hair-wrenchingly confusing. # Enjoy! def parse_file( fname, points, transform ): screen = new_screen() color = [ 0, 255, 0 ] f = open(fname, "r") line = f.readline().strip() while line: if line == "l": p = [] for x in f.readline().strip().split(' '): p.append(int(x)) add_edge(points, p[0], p[1], p[2], p[3], p[4], p[5]) elif line == "i": for x in range(4): for y in range(4): transform[x][y] = 0 transform[x][x] = 1 elif line == "s": p = [] for x in f.readline().strip().split(): p.append(float(x)) for n in range(3): transform[n][n] *= p[n] elif line == "t": p = [] for x in f.readline().strip().split(): p.append(int(x)) for n in range(3): transform[3][n] += p[n] elif line == "c": p = [] for x in f.readline().strip().split(): p.append(float(x)) make_circle(points, p[0], p[1], p[2]) elif line == "h": p = [] for x in f.readline().strip().split(): p.append(float(x)) make_spline(points, "hermite",p) elif line == "b": p = [] for x in f.readline().strip().split(): p.append(float(x)) make_spline(points, "bezier",p) elif line == "w": points = new_matrix() elif line == "p": p = [] for x in f.readline().strip().split(): p.append(int(x)) make_prism(points, p[0], p[1], p[2], p[3], p[4], p[5]) elif line =="m": p = [] for x in f.readline().strip().split(): p.append(int(x)) make_sphere(points, p[0], p[1], p[2]) elif line =="d": p = [] for x in f.readline().strip().split(): p.append(int(x)) make_torus(points, p[0], p[1], p[2], p[3]) elif line == "x": transform = rotate("x", f.readline().strip(), points, transform) elif line == "y": transform = rotate("y", f.readline().strip(), points, transform) elif line == "z": transform = rotate("z", f.readline().strip(), points, transform) elif line == "a": #print "transform: " #print_matrix(transform) points = mult(points, transform, True) elif line == "v": clear_screen(screen) draw_lines( points, screen, color ) display(screen) elif line == "g": save_ppm(screen, f.readline().strip().strip()) display(screen) line = f.readline().strip() #print_matrix( points) f.close() def rotate(axis, theta, points, transform): theta = float(theta) * pi / 180 #print cos(theta) if axis == "x": t = new_matrix() t[0][0] = 1 t[1][1] = cos(theta) t[1][2] = sin(theta) t[2][1] = -1.0 * sin(theta) t[2][2] = cos(theta) elif axis == "y": t = new_matrix() t[1][1] = 1 t[0][0] = cos(theta) t[0][2] = -1.0 * sin(theta) t[2][0] = sin(theta) t[2][2] = cos(theta) elif axis == "z": t = new_matrix() t[2][2] = 1 t[0][0] = cos(theta) t[0][1] = sin(theta) t[1][0] = -1.0 * sin(theta) t[1][1] = cos(theta) t[3][3] = 1 #print_matrix(t) #print_matrix(transform) transform = mult(t, transform, False) #print_matrix(transform) return transform def make_prism(points, x, y, z, w, h, d): add_edge(points, x, y, z, x, y, z) add_edge(points, x, y, z - d, x, y, z - d) add_edge(points, x, y - h, z, x, y - h, z) add_edge(points, x, y - h, z - d, x, y - h, z - d) add_edge(points, x + w, y, z, x + w, y, z) add_edge(points, x + w, y, z - d, x + w, y, z - d) add_edge(points, x + w, y - h, z, x + w, y - h, z) add_edge(points, x + w, y - h, z - d, x + w, y - h, z - d) def make_sphere(points, x0, y0, r): z0 = 0 for a in range(100): for b in range(100): theta = a / 100.0 * pi * 2.0 phi = b / 100.0 * pi x = x0 + int(r * cos(theta) * sin(phi)) y = y0 + int(r * sin(theta) * sin(phi)) z = z0 + int(r * cos(phi)) add_edge(points, x, y, z, x, y,z) def make_torus(points, x0, y0, r, R): z0 = 0 for a in range(100): for b in range(100): theta = a / 100.0 * pi * 2.0 phi = b / 100.0 * pi * 2.0 x = x0 + int(cos(phi) * (r * cos(theta) + R)) y = y0 + int(r * sin(theta)) z = z0 + int(-1.0 * sin(phi) * (r * cos(theta) + R)) add_edge(points, x, y, z, x, y,z) points = [] transform = new_matrix(4,4) parse_file( 'script_c', points, transform )
[ "azilby@gmail.com" ]
azilby@gmail.com
8741b9aed2a4193f98da42908af3309846ac847d
23805cffc86ac4dfb5bcce672b8c7070b4616e41
/Apprendre-Python/is-prime/scripts/generate.py
6c3f901f4ee05d4b2bf8c0c39ea1473a1f97b3d0
[]
no_license
ukonline/pythia-tasks
f90ff90299fe0eedd0e2787bcf666df07c709a00
81a3731eb0cdfe16b26a4e75a165a5071fb48ff5
refs/heads/master
2021-01-25T03:26:33.915795
2016-01-04T20:03:24
2016-01-04T20:03:24
40,974,655
0
2
null
2016-12-21T13:12:14
2015-08-18T13:49:39
Python
UTF-8
Python
false
false
467
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Course: Apprendre Python # Problem: Es-tu premier ? # Test generation script import csv import json import os import sys sys.path.append('/task/static') from lib import pythia # Read test configuration and generate test data with open('/task/config/test.json', 'r', encoding='utf-8') as file: content = file.read() config = json.loads(content) pythia.generateTestData('/tmp/work/input', 'data.csv', config)
[ "seb478@gmail.com" ]
seb478@gmail.com
c3ad0423c6d8b271ee252911c594199f7ab74981
98a9e00e0e3148e296cecf8bb5e5493d5e7c9cda
/pavement.py
d2b4556aeac8553cddab8d302a000b78bed97169
[]
no_license
cfobel/barcode-scanner
62b81f4d1bd36a61fea369703f9dee833916a982
a59acd8fef93769992b3d7a50365fbbef2d475e6
refs/heads/master
2016-09-14T01:42:03.545862
2016-04-20T18:46:02
2016-04-20T18:46:02
56,710,781
1
1
null
null
null
null
UTF-8
Python
false
false
1,877
py
import platform import sys from paver.easy import task, needs, path, sh, cmdopts, options from paver.setuputils import setup, install_distutils_tasks from distutils.extension import Extension from distutils.dep_util import newer sys.path.insert(0, path('.').abspath()) import version install_requires = ['matplotlib>=1.5.0', 'numpy', 'pygst-utils>=0.3.post4', 'zbar'] # Platform-specific package requirements. if platform.system() == 'Windows': install_requires += ['opencv-python', 'pygtk2-win', 'pycairo-gtk2-win', 'pygst-0.10-win'] else: try: import gtk except ImportError: print >> sys.err, ('Please install Python bindings for Gtk 2 using ' 'your systems package manager.') try: import cv2 except ImportError: print >> sys.err, ('Please install OpenCV Python bindings using your ' 'systems package manager.') try: import gst except ImportError: print >> sys.err, ('Please install GStreamer Python bindings using ' 'your systems package manager.') setup(name='barcode-scanner', version=version.getVersion(), description='Barcode scanner based on GStreamer, zbar, and gtk.', keywords='gtk, zbar, gstreamer', author='Christian Fobel and Michael D. M. Dryden', author_email='christian@fobel.net and mdryden@chem.utoronto.ca', url='https://github.com/wheeler-microfluidics/barcode-scanner', license='GPL', packages=['barcode_scanner', ], install_requires=install_requires, # Install data listed in `MANIFEST.in` include_package_data=True) @task @needs('generate_setup', 'minilib', 'setuptools.command.sdist') def sdist(): """Overrides sdist to make sure that our setup.py is generated.""" pass
[ "christian@fobel.net" ]
christian@fobel.net
9fab66e95f7f0019a0d653ed7dd76704f7ec115a
3473c619629ed2b6c69c9d89bc0b3229b6930137
/Day 06 - Functions and Modules/Prime.py
3577b2eec902655e2f93a4d6832b4d5b1d1c9034
[]
no_license
Bobby981229/Python-Learning
621b185e212bf7102f75c9b8ff5992ceffa0c78b
e37c37fab504597ddca569213394cec4f88ad1f4
refs/heads/master
2022-10-14T07:56:59.117446
2020-06-09T13:42:12
2020-06-09T13:42:12
259,191,244
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
""" 素数 """ from math import sqrt # 开根号 def prime(num): result = int(sqrt(num)) # 对输入的数字进行开根号计算 for x in range(2, result + 1): if num % x == 0: # 判断数字的模 return False return True if num != 1 else False num = int(input('Please input a integer number: ')) # 0 is false, 1 is true print('%d result: %d' % (num, prime(num)))
[ "729461836@qq.com" ]
729461836@qq.com
26cda9d143eff38c26755fdc0f64aac127dfe784
cd0a284c47fb03121e05284b6d5f2940ea6457ba
/fb/misc/subset-backtracking.py
5e9517de45750964ef37a1896e73ff591ccb175c
[]
no_license
franktank/py-practice
5803933c07c07a06670f83b059806385d0d029fa
1dec441f1975d402d093031569cfd301eb71d465
refs/heads/master
2021-03-22T04:33:20.818891
2017-11-14T03:40:54
2017-11-14T03:40:54
101,592,046
1
1
null
null
null
null
UTF-8
Python
false
false
480
py
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.res = [] self.helper(nums, [], 0) return self.res def helper(self, nums, cur_set, start): self.res.append(list(cur_set)) for i in range(start, len(nums)): cur_set.append(nums[i]) self.helper(nums, cur_set, i + 1) # i+1 because no duplicates cur_set.pop()
[ "fliangz96@gmail.com" ]
fliangz96@gmail.com
bb6aea31ed8fa714e9f3e4f9efea69c2821b47ef
dfcb9827b966a5055a47e27b884eaacd88269eb1
/ssseg/cfgs/ce2p/cfgs_atr_resnet101os8.py
92f1a161fe76d80856d312d01c4f8809fa71a746
[ "MIT" ]
permissive
RiDang/sssegmentation
cdff2be603fc709c1d03897383032e69f850f0cd
2a79959a3d7dff346bab9d8e917889aa5621615a
refs/heads/main
2023-02-05T12:52:35.391061
2020-12-27T05:59:58
2020-12-27T05:59:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,326
py
'''define the config file for atr and resnet101os8''' from .base_cfg import * # modify dataset config DATASET_CFG = DATASET_CFG.copy() DATASET_CFG['train'].update( { 'type': 'atr', 'rootdir': 'data/ATR', 'aug_opts': [('Resize', {'output_size': (520, 520), 'keep_ratio': False, 'scale_range': (0.75, 1.25)}), ('RandomCrop', {'crop_size': (473, 473), 'one_category_max_ratio': 0.75}), ('RandomFlip', {'flip_prob': 0.5, 'fix_ann_pairs': [(9, 10), (12, 13), (14, 15)]}), ('RandomRotation', {'angle_upper': 30, 'rotation_prob': 0.6}), ('PhotoMetricDistortion', {}), ('Normalize', {'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375]}), ('ToTensor', {}), ('Padding', {'output_size': (473, 473), 'data_type': 'tensor'}),] } ) DATASET_CFG['test'].update( { 'type': 'atr', 'rootdir': 'data/ATR', 'aug_opts': [('Resize', {'output_size': (473, 473), 'keep_ratio': False, 'scale_range': None}), ('Normalize', {'mean': [123.675, 116.28, 103.53], 'std': [58.395, 57.12, 57.375]}), ('ToTensor', {}),] } ) # modify dataloader config DATALOADER_CFG = DATALOADER_CFG.copy() DATALOADER_CFG['train'].update( { 'batch_size': 32, } ) # modify optimizer config OPTIMIZER_CFG = OPTIMIZER_CFG.copy() OPTIMIZER_CFG.update( { 'max_epochs': 150 } ) # modify losses config LOSSES_CFG = LOSSES_CFG.copy() # modify model config MODEL_CFG = MODEL_CFG.copy() MODEL_CFG.update( { 'num_classes': 18, 'backbone': { 'type': 'resnet101', 'series': 'resnet', 'pretrained': True, 'outstride': 8, 'use_stem': True } } ) # modify common config COMMON_CFG = COMMON_CFG.copy() COMMON_CFG['train'].update( { 'backupdir': 'ce2p_resnet101os8_atr_train', 'logfilepath': 'ce2p_resnet101os8_atr_train/train.log', } ) COMMON_CFG['test'].update( { 'backupdir': 'ce2p_resnet101os8_atr_test', 'logfilepath': 'ce2p_resnet101os8_atr_test/test.log', 'resultsavepath': 'ce2p_resnet101os8_atr_test/ce2p_resnet101os8_atr_results.pkl' } )
[ "1159254961@qq.com" ]
1159254961@qq.com
8d99a90f253646661425e340c0b8b5d9743a0554
8a3e59ac20b2667c7f43ab91a7fd09f5a52fec4e
/apps/crm/callcentre/migrations/0001_initial.py
16d3a8789f6799bed13602c35d3f16407455ac78
[]
no_license
suifengdou/tbd2
b1ba8ed423ace8624366ddbdd788f0ab7025d062
39093cdd45bb652e9cdfa3dc31e07344cf6628a1
refs/heads/master
2021-06-22T20:19:15.743182
2021-01-08T03:59:47
2021-01-08T03:59:47
159,639,770
0
0
null
null
null
null
UTF-8
Python
false
false
6,422
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-11-27 10:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OriCallLogInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('creator', models.CharField(default='system', max_length=30, verbose_name='创建者')), ('call_time', models.DateTimeField(verbose_name='时间')), ('mobile', models.CharField(max_length=30, verbose_name='客户电话')), ('location', models.CharField(blank=True, max_length=30, null=True, verbose_name='归属地')), ('relay_number', models.CharField(max_length=30, verbose_name='中继号')), ('customer_service', models.CharField(blank=True, max_length=30, null=True, verbose_name='客服')), ('call_category', models.CharField(max_length=30, verbose_name='通话类型')), ('source', models.CharField(max_length=30, verbose_name='来源')), ('line_up_status', models.CharField(blank=True, max_length=30, null=True, verbose_name='排队状态')), ('line_up_time', models.TimeField(verbose_name='排队耗时')), ('device_status', models.CharField(blank=True, max_length=30, null=True, verbose_name='设备状态')), ('result', models.CharField(max_length=30, verbose_name='通话结果')), ('failure_reason', models.CharField(blank=True, max_length=30, null=True, verbose_name='外呼失败原因')), ('call_recording', models.TextField(blank=True, null=True, verbose_name='通话录音')), ('call_length', models.TimeField(verbose_name='通话时长')), ('message', models.TextField(verbose_name='留言')), ('ring_time', models.TimeField(verbose_name='响铃时间')), ('ring_off', models.CharField(blank=True, max_length=30, null=True, verbose_name='通话挂断方')), ('degree_satisfaction', models.CharField(max_length=30, verbose_name='满意度评价')), ('theme', models.CharField(blank=True, max_length=230, null=True, verbose_name='主题')), ('sequence_ring', models.CharField(max_length=30, verbose_name='顺振')), ('relevant_cs', models.CharField(blank=True, max_length=30, null=True, verbose_name='相关客服')), ('work_order', models.CharField(blank=True, max_length=30, null=True, verbose_name='生成工单')), ('email', models.CharField(blank=True, max_length=60, null=True, verbose_name='邮箱')), ('tag', models.CharField(blank=True, max_length=30, null=True, verbose_name='标签')), ('description', models.TextField(blank=True, null=True, verbose_name='描述')), ('leading_cadre', models.CharField(blank=True, max_length=30, null=True, verbose_name='负责人')), ('group', models.CharField(blank=True, max_length=30, null=True, verbose_name='负责组')), ('degree', models.CharField(max_length=30, verbose_name='等级')), ('is_blacklist', models.CharField(max_length=30, verbose_name='是否在黑名单')), ('call_id', models.CharField(max_length=230, verbose_name='call_id')), ('reason', models.CharField(blank=True, max_length=60, null=True, verbose_name='补寄原因')), ('call_class', models.CharField(blank=True, max_length=60, null=True, verbose_name='来电类别')), ('goods_name', models.CharField(blank=True, max_length=60, null=True, verbose_name='商品型号')), ('process_category', models.CharField(blank=True, max_length=60, null=True, verbose_name='处理方式')), ('goods_id', models.CharField(blank=True, max_length=60, null=True, verbose_name='产品编号')), ('purchase_time', models.CharField(blank=True, max_length=60, null=True, verbose_name='购买日期')), ('service_info', models.CharField(blank=True, max_length=230, null=True, verbose_name='补寄配件记录')), ('shop', models.CharField(blank=True, max_length=60, null=True, verbose_name='店铺')), ('order_status', models.IntegerField(choices=[(0, '已取消'), (1, '未处理'), (2, '未抽检'), (3, '已完成')], default=1, verbose_name='单据状态')), ('process_tag', models.IntegerField(choices=[(0, '未处理'), (1, '待核实'), (2, '已确认'), (3, '待清账'), (4, '已处理'), (5, '特殊订单')], default=0, verbose_name='处理标签')), ('mistake_tag', models.SmallIntegerField(choices=[(0, '正常'), (1, '重复建单'), (2, '无补寄原因'), (3, '无店铺'), (4, '补寄配件记录格式错误'), (5, '补寄原因错误'), (6, '单据创建失败')], default=0, verbose_name='错误列表')), ('is_sampling', models.SmallIntegerField(choices=[(0, '否'), (1, '是')], default=0, verbose_name='是否抽检')), ('content_category', models.SmallIntegerField(choices=[(0, '常规'), (1, '订单')], default=0, verbose_name='内容类型')), ], options={ 'verbose_name': 'CRM-原始通话记录-查询', 'verbose_name_plural': 'CRM-原始通话记录-查询', 'db_table': 'crm_cal_oricalllog', }, ), migrations.CreateModel( name='CheckOriCall', fields=[ ], options={ 'verbose_name': 'CRM-原始通话记录-未处理', 'verbose_name_plural': 'CRM-原始通话记录-未处理', 'proxy': True, 'indexes': [], }, bases=('callcentre.oricallloginfo',), ), ]
[ "2689179206@qq.com" ]
2689179206@qq.com
a96d0e6cbfbb17f69233e6f6c4998a16fd37cf02
187a6558f3c7cb6234164677a2bda2e73c26eaaf
/jdcloud_sdk/services/antipro/models/Acl.py
7832071a16e817c78df10dbe5d03f5fb05ad3d38
[ "Apache-2.0" ]
permissive
jdcloud-api/jdcloud-sdk-python
4d2db584acc2620b7a866af82d21658cdd7cc227
3d1c50ed9117304d3b77a21babe899f939ae91cd
refs/heads/master
2023-09-04T02:51:08.335168
2023-08-30T12:00:25
2023-08-30T12:00:25
126,276,169
18
36
Apache-2.0
2023-09-07T06:54:49
2018-03-22T03:47:02
Python
UTF-8
Python
false
false
2,979
py
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. class Acl(object): def __init__(self, id=None, priority=None, sipType=None, sip=None, sipIpSetId=None, sipIpSetName=None, dipType=None, dip=None, dipIpSetId=None, dipIpSetName=None, protocol=None, portType=None, port=None, portSetId=None, portSetName=None, action=None, enable=None, remark=None): """ :param id: (Optional) 访问控制规则 Id :param priority: (Optional) 规则优先级 :param sipType: (Optional) 源IP类型: 0: IP, 1: IP地址库 :param sip: (Optional) 源IP, sipType 为 0 时有效, 否则为空 :param sipIpSetId: (Optional) IP地址库 Id, sipType 为 1 时有效, 否则为空。<br>'-1' IP高防回源地址<br>'-2' Web应用防火墙回源地址 :param sipIpSetName: (Optional) IP地址库名称 :param dipType: (Optional) 目的IP类型: 0: IP, 1: IP地址库 :param dip: (Optional) 目的IP, dipType 为 0 时有效, 否则为空 :param dipIpSetId: (Optional) IP地址库 Id, dipType 为 1 时有效, 否则为空。<br>'-1' IP高防回源地址<br>'-2' Web应用防火墙回源地址 :param dipIpSetName: (Optional) IP地址库名称 :param protocol: (Optional) 协议类型: 支持 All Traffic, TCP, UDP, ICMP :param portType: (Optional) 端口类型: 0: IP, 1: 端口库 :param port: (Optional) 端口或端口范围, portType 为 0 时有效,否则为空 :param portSetId: (Optional) 端口库Id, portType 为 1 时有效,否则为空 :param portSetName: (Optional) 端口库名称 :param action: (Optional) 动作: 0: 放行, 1: 阻断 :param enable: (Optional) 规则状态: 0: 关闭, 1: 打开 :param remark: (Optional) 备注 """ self.id = id self.priority = priority self.sipType = sipType self.sip = sip self.sipIpSetId = sipIpSetId self.sipIpSetName = sipIpSetName self.dipType = dipType self.dip = dip self.dipIpSetId = dipIpSetId self.dipIpSetName = dipIpSetName self.protocol = protocol self.portType = portType self.port = port self.portSetId = portSetId self.portSetName = portSetName self.action = action self.enable = enable self.remark = remark
[ "jdcloud-api@jd.com" ]
jdcloud-api@jd.com
cd6a20e990cb2dbee4a8386d99bf84e07bae879e
98bd2625dbcc955deb007a07129cce8b9edb3c79
/vcf2SelectHapStatsInput.py
cc27f18f4a524c23fd3541a1cbad9fa9ac27e99a
[]
no_license
melanieabrams/bremdata
70d0a374ab5dff32f6d9bbe0a3959a617a90ffa8
df7a12c72a29cca4760333445fafe55bb6e40247
refs/heads/master
2021-12-26T01:57:25.684288
2021-09-30T22:48:05
2021-09-30T22:48:05
166,273,567
0
3
null
null
null
null
UTF-8
Python
false
false
3,175
py
import os import vcf import sys ##USGAGE: python vcf2SelectHapStatsInput.py gvcf_filename ##NOTE: this script assumes gVCF formatting, as generated by GATK. It handles missing data as missing. ##PARAMETERS samples_to_exclude=[] # for 1011 genomes (all pop) heterozygous_present=True # True for 1011 genomes S cerevisiae ##RUN def main(): missing_data={} #samples with uncalled variant positions samples_tested="" num_samples_tested=0 ## with open(outfile_name,"w") as wf: vcf_reader = vcf.Reader(open(vcf_filename, 'r')) for record in vcf_reader: pos_line="" pos=record.POS pos_line+=str(pos) for call in record.samples: sample=call.sample if sample not in samples_to_exclude: if sample not in samples_tested: samples_tested+=sample+", " num_samples_tested+=1 if call.gt_type!=None and call.gt_bases!=None: allele=call.gt_bases if heterozygous_present==True: bases=allele.split('/') if bases[0]!=bases[1]: allele='.' # represent heterozygous GT as dots else: allele=bases[0] #if homozygous, represent GT as the base if len(allele)>1: allele = 'INDEL' else: allele='None' if sample in missing_data: missing_data[sample]+=','+str(pos) else: missing_data[sample]=str(pos) pos_line+=","+str(allele) if 'INDEL' not in pos_line and 'None' not in pos_line: wf.writelines(pos_line+"\n") #omit lines with missing data ## print(pos_line) ## exit() #break for speediness with open(errfile_name,"w") as wf: wf.writelines("the following samples were excluded") wf.writelines("%s," % sample for sample in samples_to_exclude) wf.writelines("shs input generated for the following"+str(num_samples_tested)+"samples\n") wf.writelines(samples_tested+"\n") wf.writelines("sample\tuncalled_pos\n") for sample in missing_data: wf.writelines(sample+"\t"+missing_data[sample]+"\n") if __name__ == '__main__': vcf_filename=sys.argv[1] outfile_name=vcf_filename.split('.')[0]+".shsinput" errfile_name=vcf_filename.split('.')[0]+".missing_call_log" main()
[ "noreply@github.com" ]
melanieabrams.noreply@github.com
ebec731334511b25ef15e389dd83a5ec4e2d6dea
9998f1b6008b290ef1ef895bc0c4ca273dfbe1e0
/leet code/002-Two Sum.py
8be38348c0937606c72f279e23b69bb43af0b139
[ "MIT" ]
permissive
boisde/Greed_Island
51a997dc0e7890ea468c448bc1dda34e61a4aea8
9c4f0195fb7bfaeb6c29e8e9638c7b0ffd9ad90b
refs/heads/master
2021-06-15T06:58:35.036706
2021-04-12T11:14:54
2021-04-12T11:14:54
20,638,183
0
2
null
null
null
null
UTF-8
Python
false
false
6,983
py
#coding=utf-8 """ Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 """ class Solution(object): @staticmethod def two_sum_n_squared(numbers, target): # brute force method N = len(numbers) for i in range(N): for j in range(N): if numbers[i]+numbers[j] == target and i != j: # don't forget the parenthesis, or will report compile error with # "too many values to unpack" smaller, bigger = (i+1, j+1) if i+1 < j+1 else (j+1, i+1) return smaller, bigger @staticmethod def two_sum_n(numbers, target): N = len(numbers) num_dict = {} for i in range(N): num_dict[numbers[i]] = i for i in range(N): to_find = target - numbers[i] # remember to rule self out if to_find in num_dict and num_dict[to_find] != i: smaller, bigger = i+1, num_dict[to_find] + 1 smaller, bigger = (smaller, bigger) if smaller<bigger else (bigger, smaller) return smaller, bigger return -1, -1 @staticmethod def two_sum_n_refined(num, target): num_dict = {} for i in range(len(num)): partner = target - num[i] # no need to rule self out here, cause you won't encounter yourself again. if partner in num_dict: # 1) by the time find your partner, you are already in dictionary, # and you are always the prior one. # 2) no need to deal with duplicates, duplicates that is solution to <target> will # be properly handled; not part of solution, the value of the <num_dict> will be # the later duplication's index, but that does not matter. return num_dict[partner]+1, i+1 else: num_dict[num[i]] = i return -1, -1 """ Follow up Question: What if the given input is already sorted in ascending order? """ @staticmethod # Input: num is sorted def two_sum_2_nlogn(num, target): import bisect N = len(num) for i in range(N): partner = target - num[i] insertion_point = bisect.bisect_left(num, partner) # use binary search, if found it; rule self out if insertion_point != N and num[insertion_point] == partner and i != insertion_point: smaller = i+1 bigger = insertion_point + 1 smaller, bigger = (smaller, bigger) if smaller<bigger else (bigger, smaller) return smaller, bigger return -1, -1 @staticmethod # Input: num is sorted def two_sum_2_n_refined(num, target): N = len(num) prior, later = 0, N-1 # two pointer pointing to ith and jth elements, num[i] and num[j], # num[i]+num[j] can only be >,<,== target. for _ in range(N-1): if num[prior] + num[later] == target: return prior+1, later+1 elif num[prior] + num[later] > target: later -= 1 else: prior += 1 return -1, -1 class TwoSum(object): """ Follow up Question: [HARDER--much more details to consider] Design and implement a TwoSum class. It should support the following operations: add and find. add(input) – Add the number input to an internal data structure. find(value) – Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); add(3); add(5); find(4)  true; find(7)  false """ def __init__(self): self.numbers = {} # <key=number value>: <value=1-based index, could be list if duplicate> self.count = 1 # store input into a hash map, handle duplicates carefully def add_constant_runtime(self, x): # if duplicated and still not a list, change the value to a list. # Do NOT re-list it!!! if x in self.numbers and type(self.numbers[x]) is int: self.numbers[x] = [self.numbers[x]] self.numbers[x].append(self.count) elif x in self.numbers: self.numbers[x].append(self.count) else: self.numbers[x] = self.count self.count += 1 # find target-num[i] in hash map def find_n_runtime(self, target): for elem in self.numbers.iterkeys(): partner = target - elem # edge case: duplicates adds up to target if partner == elem and partner in self.numbers and type(self.numbers[elem]) is list: return self.numbers[elem][0], self.numbers[elem][1] # normal case: found it. if partner in self.numbers: if type(self.numbers[elem]) is int: prior = self.numbers[elem] else: prior = self.numbers[elem][0] if type(self.numbers[partner]) is int: later = self.numbers[partner] else: later = self.numbers[partner][0] return (prior, later) if prior<later else (later, prior) return -1, -1 if __name__ == "__main__": print Solution.two_sum_n_refined([3,2,4], 6) # (2,3) print Solution.two_sum_n_refined([3,2,2], 4) # (2,3) print Solution.two_sum_n_refined([3,2,2,2,2,2,2,2,2,2,2,2,2,2], 4) # (2,3) print Solution.two_sum_n_refined([3], 4) # (-1,-1) # for follow up question 2, with input num array already sorted in ascending order print Solution.two_sum_2_nlogn([2,3,4], 6) # (1,3) print Solution.two_sum_2_nlogn([2,2,3], 4) # (1,2), should not be (1,1) print Solution.two_sum_2_nlogn([2,2,2,2,2,2,2,2,2,2,2,2,3], 4) # (1,2) print Solution.two_sum_2_nlogn([3], 4) # (-1,-1) print Solution.two_sum_2_n_refined([2,3,4], 6) # (1,3) print Solution.two_sum_2_n_refined([2,2,3], 4) # (1,2), should not be (1,1) print Solution.two_sum_2_n_refined([2,2,2,2,2,2,2,2,2,2,2,2,3], 4) # (1,2) print Solution.two_sum_2_n_refined([3], 4) # (-1,-1) # for follow up question 3: data structure design two_sum = TwoSum() for i in [2,3,4]: two_sum.add_constant_runtime(i) print two_sum.find_n_runtime(6) # (1,3) for i in [2,2,2,2,2,2,2,2,2,2,2,2,3]: two_sum.add_constant_runtime(i) print two_sum.find_n_runtime(4) # (1,4) for i in [4]: two_sum.add_constant_runtime(i) print two_sum.find_n_runtime(14) # (-1,-1)
[ "boisde1117@gmail.com" ]
boisde1117@gmail.com
5f9e775a7ab8bd1de57638ea892c2b7c8c3e3e6a
c838b0eaf08c63284bd29442f8a0a297d1558fd5
/lagom/policies/random_policy.py
e19f315de4d7b034ecb4e8bf785077ab607fc0a3
[ "MIT" ]
permissive
vin136/lagom
ccd0f4a3e469c1ee8ef88b1f5248e712b51c5704
54e1890e6450f4b1bf499a838963c5d1a3b2da6a
refs/heads/master
2020-04-22T21:45:51.488458
2019-02-13T16:41:32
2019-02-13T16:41:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,077
py
from .base_policy import BasePolicy class RandomPolicy(BasePolicy): r"""Random policy. The action is uniformly sampled from action space. Example:: policy = RandomPolicy(config=None, env_spec=env_spec, device=None) policy(observation) """ def __init__(self, config, env_spec): self.config = config self._env_spec = env_spec def make_networks(self, config): pass def make_optimizer(self, config, **kwargs): pass def optimizer_step(self, config, **kwargs): pass def reset(self, config, **kwargs): pass def __call__(self, x, out_keys=['action'], **kwargs): out_policy = {} if self.env_spec.is_vec_env: action = [self.action_space.sample() for _ in range(self.env_spec.env.num_env)] else: action = self.action_space.sample() out_policy['action'] = action return out_policy @property def recurrent(self): pass
[ "zuoxingdong@hotmail.com" ]
zuoxingdong@hotmail.com
ba9ca47753df3cc1fa8c8a864a4387c6a3a2f322
9a26d98f6f531b222c332ab6367e9e18beb0633f
/008. Dynamic Programming [동적 프로그래밍]/venv/Scripts/easy_install-3.8-script.py
31936c0e1b179dcf18187893df7efb9e2d4ed4f9
[]
no_license
yoonicode/of-Algorithms
dffac0b422e51dcd7df1f60236675608af73f03d
bbf89df443a3561fbbe0d0f6dfebb97f3ed216aa
refs/heads/master
2022-11-24T08:27:52.679469
2020-07-28T14:58:52
2020-07-28T14:58:52
null
0
0
null
null
null
null
UHC
Python
false
false
523
py
#!"D:\Users\Yoonsung\Documents\GitHub\of-Algorithms\008. Dynamic Programming [동적 프로그래밍]\venv\Scripts\python.exe" -x # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.8' __requires__ = 'setuptools==40.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.8')() )
[ "yoonsungkr@kakao.com" ]
yoonsungkr@kakao.com
5489c893e687e6aed670cc7fdcc9bf6a16248996
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_1/Python/StefanPochmann/A.py
854b3312bd1dba6383f564157857729276cad94e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
220
py
#f = open('A.in') #def input(): # return next(f) for x in range(1, int(input()) + 1): R, C, W = map(int, input().split()) #print(R, C, W) print('Case #%d:' % x, W + (C-1) // W + (R-1) * (C // W))
[ "eewestman@gmail.com" ]
eewestman@gmail.com
e3bf180b1c85b33e05c07e36ed9b8cbfe6534857
309d17b81cea038713ba67bee72a41d2df4d6869
/Python/Python_basic/Python_OOP/OOP6_bmi.py
d2e2087aa8b93b01272764517ec6df4319cee4a3
[]
no_license
Bongkot-Kladklaen/Programming_tutorial_code
ac07e39da2bce396e670611884436b360536cdc5
cda7508c15c3e3d179c64b9aac163b6173ef3519
refs/heads/master
2023-06-20T13:14:17.077809
2021-07-18T04:41:04
2021-07-18T04:41:04
387,081,622
0
0
null
null
null
null
UTF-8
Python
false
false
705
py
class Bmi: def __init__(self,w_kg, h_cm): self.w_kg = w_kg self.h_cm = h_cm def bmi(self): return self.w_kg / (self.h_cm / 100) ** 2 def category(self): diag = "" if self.bmi() < 18.5: diag = "ต่ำกว่าเกณฑ์" elif 18.5 <= self.bmi() <= 25: diag = "ตามเกณฑ์" elif 25 < self.bmi() <= 30: diag = "เกินเกณฑ์" elif self.bmi() > 30: diag = "อ้วน" return diag def __str__(self): return f"BMI = {self.bmi()} ({self.category()})" if __name__ == "__main__": a = Bmi(50,164) print(a)
[ "bongkot.klad@gmail.com" ]
bongkot.klad@gmail.com
291ec277badd9ec84ba46368670827ec4adfb1db
4da55187c399730f13c5705686f4b9af5d957a3f
/resources/sumo_exporter/road.py
f3fe5331d6efe9f5434c28093515462058cc516f
[ "Apache-2.0" ]
permissive
Ewenwan/webots
7111c5587100cf35a9993ab923b39b9e364e680a
6b7b773d20359a4bcf29ad07384c5cf4698d86d3
refs/heads/master
2020-04-17T00:23:54.404153
2019-01-16T13:58:12
2019-01-16T13:58:12
166,048,591
2
0
Apache-2.0
2019-01-16T13:53:50
2019-01-16T13:53:50
null
UTF-8
Python
false
false
7,356
py
"""Road class container.""" import math import re from re_definitions import floatRE, intRE from data_structures import grouper from math_utils import apply_spline_subdivison_to_path from shapely.geometry import LineString, MultiLineString from lxml import etree as ET class Road(object): """Class matching with a Webots Road, containing facilities to export to SUMO edges.""" roads = [] def __init__(self, wbtString, roadType): """Constructor: Extract info from the wbtString matching the node.""" self.startJunction = None self.endJunction = None self.roadType = roadType try: self.id = re.findall(r'id\s*"([^"]*)"', wbtString)[0] except: self.id = "" try: self.width = float(re.findall(r'width\s*(%s)' % floatRE, wbtString)[0]) except: self.width = 7 try: self.speedLimit = float(re.findall(r'speedLimit\s*(%s)' % floatRE, wbtString)[0]) except: self.speedLimit = 50.0 / 3.6 # 50 km/h try: self.translation = [float(x) for x in re.findall(r'translation\s*(%s\s*%s\s*%s)' % (floatRE, floatRE, floatRE), wbtString)[0].split()] except: self.translation = [0.0, 0.0, 0.0] try: self.rotation = [float(x) for x in re.findall(r'rotation\s*(%s\s*%s\s*%s\s*%s)' % (floatRE, floatRE, floatRE, floatRE), wbtString)[0].split()] except: self.rotation = [0.0, 1.0, 0.0, 0.0] try: self.startJunctionID = re.findall(r'startJunction\s*"([^"]*)"', wbtString)[0] except: self.startJunctionID = "" try: self.endJunctionID = re.findall(r'endJunction\s*"([^"]*)"', wbtString)[0] except: self.endJunctionID = "" if self.roadType == 'Road': try: self.wayPoints = grouper(3, [float(x) for x in re.findall(r'wayPoints\s*\[([^\]]*)\]', wbtString)[0].split()]) except: self.wayPoints = [] splineSubdivision = 4 try: splineSubdivision = int(re.findall(r'splineSubdivision\s*(%s)' % intRE, wbtString)[0]) except: splineSubdivision = 4 if splineSubdivision > 0: self.wayPoints = apply_spline_subdivison_to_path(self.wayPoints, splineSubdivision) elif self.roadType == 'StraightRoadSegment': length = 10.0 try: length = float(re.findall(r'length\s*(%s)' % floatRE, wbtString)[0]) except: length = 10.0 self.wayPoints = [[0, 0, 0], [0, 0, length]] elif self.roadType == 'CurvedRoadSegment': self.wayPoints = [] subdivision = 8 try: subdivision = int(re.findall(r'subdivision\s*(%s)' % intRE, wbtString)[0]) except: subdivision = 8 curvatureRadius = 10.0 try: curvatureRadius = float(re.findall(r'curvatureRadius\s*(%s)' % floatRE, wbtString)[0]) except: curvatureRadius = 10.0 totalAngle = 1.5708 try: totalAngle = float(re.findall(r'totalAngle\s*(%s)' % floatRE, wbtString)[0]) except: totalAngle = 1.5708 for i in range(subdivision + 1): x1 = curvatureRadius * math.cos(float(i) * totalAngle / float(subdivision)) y1 = curvatureRadius * math.sin(float(i) * totalAngle / float(subdivision)) self.wayPoints.append([x1, 0, y1]) else: self.wayPoints = [] try: self.lanes = int(re.findall(r'numberOfLanes\s*(%s)' % intRE, wbtString)[0]) except: self.lanes = 2 try: self.forwardLanes = int(re.findall(r'numberOfForwardLanes\s*(%s)' % intRE, wbtString)[0]) except: self.forwardLanes = 1 self.backwardLanes = self.lanes - self.forwardLanes self.oneWay = self.backwardLanes == 0 if self.rotation[0] < 0.01 and self.rotation[2] < 0.01: angle = self.rotation[3] if self.rotation[1] > 0: angle = -angle for i in range(len(self.wayPoints)): wayPoint = self.wayPoints[i] x = math.cos(angle) * wayPoint[0] - math.sin(angle) * wayPoint[2] y = wayPoint[1] z = math.cos(angle) * wayPoint[2] + math.sin(angle) * wayPoint[0] self.wayPoints[i] = [x, y, z] else: print ('Warning: cannot export edge "%s" because the road is rotated not only along axis Y.' % self.id) def create_edge(self, edges): """Create the SUMO edge XML node(s) matching with the Webots road.""" if self.startJunctionID == self.endJunctionID: print ('Warning: cannot export edge "%s" because start and end junctions are identical.' % self.id) return if len(self.wayPoints) < 2: print ('Warning: cannot export edge "%s" because it has less than 2 way-points.' % self.id) return laneWidth = self.width / self.lanes # The original path should be slightly shifted if the case where the # forwardLanes and backwardLanes are not matching. originalCoords = [[- x - self.translation[0], z + self.translation[2]] for [x, y, z] in self.wayPoints] originalLineString = LineString(originalCoords) if self.oneWay: originalLineString = originalLineString.parallel_offset(0.5 * laneWidth * self.forwardLanes, 'left') else: offset = (self.forwardLanes - self.backwardLanes) * laneWidth * 0.5 if offset > 0.0: originalLineString = originalLineString.parallel_offset(offset, 'left') elif offset < 0.0: originalLineString = originalLineString.parallel_offset(offset, 'left') originalLineString = LineString(list(originalLineString.coords[::-1])) if isinstance(originalLineString, MultiLineString): originalPath = originalCoords else: originalPath = list(originalLineString.coords) # Create the forward edge if self.forwardLanes > 0: edge = ET.SubElement(edges, 'edge') edge.attrib['id'] = self.id edge.attrib['from'] = self.startJunctionID edge.attrib['to'] = self.endJunctionID edge.attrib['numLanes'] = str(self.forwardLanes) edge.attrib['width'] = str(laneWidth) edge.attrib['shape'] = Road._pathToString(originalPath) # Create the backward edge if self.backwardLanes > 0: edge = ET.SubElement(edges, 'edge') edge.attrib['id'] = '-' + self.id edge.attrib['to'] = self.startJunctionID edge.attrib['from'] = self.endJunctionID edge.attrib['numLanes'] = str(self.backwardLanes) edge.attrib['width'] = str(laneWidth) edge.attrib['shape'] = Road._pathToString(originalPath[::-1]) @classmethod def _pathToString(cls, path): s = "" for coord in path: s += "%f,%f " % (coord[0], coord[1]) return s
[ "David.Mansolino@cyberbotics.com" ]
David.Mansolino@cyberbotics.com
d42fbc0d64ddce99c3a42871b69a726c42be38af
f8580d2c963b6a3c34e918e0743d0a503a9584bd
/unittests/test_image.py
eb9bc49d20574689e5249f2e3d79f96497b3d369
[]
no_license
pypy/wxpython-cffi
f59c3faeed26e6a26d0c87f4f659f93e5366af28
877b7e6c1b5880517456f1960db370e4bb7f5c90
refs/heads/master
2023-07-08T21:13:22.765786
2016-12-02T22:10:45
2016-12-02T22:10:45
397,124,697
1
0
null
null
null
null
UTF-8
Python
false
false
7,280
py
import imp_unittest, unittest import wtc import wx import wx.lib.six as six from wx.lib.six import BytesIO as FileLikeObject import os pngFile = os.path.join(os.path.dirname(__file__), 'toucan.png') #--------------------------------------------------------------------------- def makeBuf(w, h, bpp=1, init=0): "Make a simple buffer for testing with" buf = bytearray([init] * (w*h*bpp)) return buf class image_Tests(wtc.WidgetTestCase): def test_imageCtor1(self): img = wx.Image() self.assertTrue(not img.IsOk()) img.Create(100,100) self.assertTrue(img.IsOk()) def test_imageCtor2(self): img = wx.Image(100,100) self.assertTrue(img.IsOk()) def test_imageCtor3(self): img = wx.Image(wx.Size(100,100)) self.assertTrue(img.IsOk()) img = wx.Image((100,100)) self.assertTrue(img.IsOk()) def test_imageCtor4(self): w = h = 10 buf = makeBuf(w,h,3) img = wx.Image(w, h, buf) self.assertTrue(img.IsOk()) def test_imageCtor5(self): w = h = 10 buf = makeBuf(w,h,3) alpha = makeBuf(w,h) img = wx.Image(w, h, buf, alpha) self.assertTrue(img.IsOk()) def test_imageCtor4b(self): w = h = 10 buf = makeBuf(w,h,3) img = wx.Image((w, h), buf) self.assertTrue(img.IsOk()) def test_imageCtor4c(self): w = h = 10 buf = makeBuf(w,h,3) with self.assertRaises(ValueError): # should be an exception here because the buffer is the wrong size img = wx.Image((w, h+1), buf) def test_imageCtor5b(self): w = h = 10 buf = makeBuf(w,h,3) alpha = makeBuf(w,h) img = wx.Image((w, h), buf, alpha) self.assertTrue(img.IsOk()) def test_imageCtor6(self): img = wx.Image(pngFile, wx.BITMAP_TYPE_PNG) self.assertTrue(img.IsOk()) def test_imageCtor7(self): img = wx.Image(pngFile, 'image/png') self.assertTrue(img.IsOk()) def test_imageCtor8(self): with open(pngFile, 'rb') as f: data = f.read() stream = FileLikeObject(data) img = wx.Image(stream, wx.BITMAP_TYPE_PNG) self.assertTrue(img.IsOk()) def test_imageCtor9(self): with open(pngFile, 'rb') as f: data = f.read() stream = FileLikeObject(data) img = wx.Image(stream, 'image/png') self.assertTrue(img.IsOk()) def test_imageSetData1(self): w = h = 10 img = wx.Image(w,h) buf = makeBuf(w,h,3, init=2) img.SetData(buf) self.assertTrue(img.IsOk()) self.assertTrue(img.GetRed(1,1) == 2) def test_imageSetData2(self): w = h = 10 img = wx.Image(1,1) buf = makeBuf(w,h,3, init=2) img.SetData(buf, w, h) self.assertTrue(img.IsOk()) self.assertTrue(img.GetRed(1,1) == 2) def test_imageSetAlpha1(self): w = h = 10 img = wx.Image(w,h) buf = makeBuf(w,h, init=2) img.SetAlpha(buf) self.assertTrue(img.IsOk()) self.assertTrue(img.GetRed(1,1) == 0) self.assertTrue(img.GetAlpha(1,1) == 2) def test_imageGetData(self): img = wx.Image(pngFile) data = img.GetData() self.assertEqual(len(data), img.Width * img.Height * 3) self.assertTrue(isinstance(data, bytearray)) def test_imageGetAlpha(self): img = wx.Image(pngFile) data = img.GetAlpha() self.assertEqual(len(data), img.Width * img.Height) self.assertTrue(isinstance(data, bytearray)) def test_imageGetDataBuffer(self): w = h = 10 img = wx.Image(w, h) self.assertTrue(img.IsOk()) data = img.GetDataBuffer() self.assertTrue(isinstance(data, memoryview)) data[0] = 1 if six.PY33 else b'\1' data[1] = 2 if six.PY33 else b'\2' data[2] = 3 if six.PY33 else b'\3' self.assertEqual(1, img.GetRed(0,0)) self.assertEqual(2, img.GetGreen(0,0)) self.assertEqual(3, img.GetBlue(0,0)) def test_imageGetAlphaDataBuffer(self): w = h = 10 img = wx.Image(w, h) img.InitAlpha() self.assertTrue(img.IsOk()) data = img.GetAlphaBuffer() self.assertTrue(isinstance(data, memoryview)) data[0] = 1 if six.PY33 else b'\1' data[1] = 2 if six.PY33 else b'\2' data[2] = 3 if six.PY33 else b'\3' self.assertEqual(1, img.GetAlpha(0,0)) self.assertEqual(2, img.GetAlpha(1,0)) self.assertEqual(3, img.GetAlpha(2,0)) def test_imageSetDataBuffer1(self): w = h = 10 img = wx.Image(w,h) buf = makeBuf(w,h,3) img.SetDataBuffer(buf) buf[0] = 1 buf[1] = 2 buf[2] = 3 self.assertEqual(1, img.GetRed(0,0)) self.assertEqual(2, img.GetGreen(0,0)) self.assertEqual(3, img.GetBlue(0,0)) def test_imageSetDataBuffer2(self): w = h = 10 img = wx.Image(1,1) buf = makeBuf(w,h,3) img.SetDataBuffer(buf, w, h) buf[0] = 1 buf[1] = 2 buf[2] = 3 self.assertEqual(1, img.GetRed(0,0)) self.assertEqual(2, img.GetGreen(0,0)) self.assertEqual(3, img.GetBlue(0,0)) def test_imageSetAlphaBuffer(self): w = h = 10 img = wx.Image(w,h) buf = makeBuf(w,h) img.SetAlphaBuffer(buf) buf[0] = 1 buf[1] = 2 buf[2] = 3 self.assertEqual(1, img.GetAlpha(0,0)) self.assertEqual(2, img.GetAlpha(1,0)) self.assertEqual(3, img.GetAlpha(2,0)) def test_imageNestedClasses(self): rgb = wx.Image.RGBValue(1,2,3) self.assertEqual(rgb.red, 1) self.assertEqual(rgb.green, 2) self.assertEqual(rgb.blue, 3) rgb.red = 4 rgb.green = 5 rgb.blue = 6 hsv = wx.Image.HSVValue(1.1, 1.2, 1.3) self.assertEqual(hsv.hue, 1.1) self.assertEqual(hsv.saturation, 1.2) self.assertEqual(hsv.value, 1.3) hsv.hue = 2.1 hsv.saturation = 2.2 hsv.value = 2.3 def test_imageRGBHSV(self): rgb = wx.Image.RGBValue(1,2,3) hsv = wx.Image.RGBtoHSV(rgb) rgb = wx.Image.HSVtoRGB(hsv) self.assertEqual(rgb.red, 1) self.assertEqual(rgb.green, 2) self.assertEqual(rgb.blue, 3) def test_imageProperties(self): img = wx.Image(pngFile) self.assertTrue(img.IsOk()) img.Width img.Height img.MaskRed img.MaskGreen img.MaskBlue img.Type def test_imageMethodChain(self): img = wx.Image(100,100).Rescale(75,75).Resize((100,100), (0,0), 40,60,80) self.assertTrue(img.IsOk()) def test_imageOtherStuff(self): img = wx.Image(pngFile) self.assertTrue(img.IsOk()) r, g, b = img.FindFirstUnusedColour() r, g, b = img.GetOrFindMaskColour() #--------------------------------------------------------------------------- if __name__ == '__main__': unittest.main()
[ "wayedt@gmail.com" ]
wayedt@gmail.com
656dc7e15b78455cee914cb74a92048e94167263
9d64a438cdfe4f3feb54f2f0dc7431139c4b9fb9
/microsoft_atp/komand_microsoft_atp/actions/get_machine_information/action.py
1d683811c0eb693aaf72cbf02b4acadd6d9b841d
[ "MIT" ]
permissive
PhilippBehmer/insightconnect-plugins
5ad86faaccc86f2f4ed98f7e5d518e74dddb7b91
9195ddffc575bbca758180473d2eb392e7db517c
refs/heads/master
2021-07-25T02:13:08.184301
2021-01-19T22:51:35
2021-01-19T22:51:35
239,746,770
0
0
MIT
2020-02-11T11:34:52
2020-02-11T11:34:51
null
UTF-8
Python
false
false
955
py
import insightconnect_plugin_runtime from .schema import GetMachineInformationInput, GetMachineInformationOutput, Input, Output, Component # Custom imports below class GetMachineInformation(insightconnect_plugin_runtime.Action): def __init__(self): super(self.__class__, self).__init__( name='get_machine_information', description=Component.DESCRIPTION, input=GetMachineInformationInput(), output=GetMachineInformationOutput()) def run(self, params={}): self.logger.info("Running...") machine_id = self.connection.client.find_first_machine(params.get(Input.MACHINE)).get("id") self.logger.info(f"Attempting to get information for machine ID: {machine_id}") return { Output.MACHINE: insightconnect_plugin_runtime.helper.clean( self.connection.client.get_machine_information(machine_id) ) }
[ "noreply@github.com" ]
PhilippBehmer.noreply@github.com
5cd8e84f11d2ea34f343ae402d5c0b33dcf7d2db
958d87cc3b77bb3308d0aa04b92fdef5f97d63ae
/4.OOPS/InheritanceAndPolymorphism.py
8056a618b0d68087183a3df5858998b9bc487e65
[]
no_license
parihar08/PythonJosePortilla
6dec83519af78451c46e323928aedf19dbd908f1
6f47291908ad05daf5a505ba0e13687c46651bc2
refs/heads/master
2022-12-19T07:30:39.603468
2020-09-19T14:56:36
2020-09-19T14:56:36
292,650,778
0
0
null
null
null
null
UTF-8
Python
false
false
2,005
py
class Animal(): def __init__(self): print('ANIMAL CREATED') def who_am_i(self): print("I am an animal") def eat(self): print("I am eating") # myanimal = Animal() # myanimal.who_am_i() # myanimal.who_am_i() class Dog(Animal): def __init__(self): Animal.__init__(self) #Create instance of Animal class when we create instance of Dog class print('DOG CREATED') #METHOD OVERRIDE def who_am_i(self): print("I am a Dog") #ADDITIONAL METHODS def bark(self): print('WOOF!') mydog = Dog() print('*********************************************') mydog.who_am_i() mydog.bark() mydog.eat() print('*******************POLYMORPHISM**************************') #Different object classes can share the same method name class Dog1(): def __init__(self,name): self.name = name def speak(self): return self.name + " says WOOF!" class Cat1(): def __init__(self,name): self.name = name def speak(self): return self.name + " says MEOW!" niko = Dog1('niko') felix = Cat1('felix') print(niko.speak()) print(felix.speak()) print('*********************************************') #Here both Dog1 and Cat1 class has speak() method for pet in [niko,felix]: print(type(pet)) print(pet.speak()) print('*********************************************') def pet_speak(pet): print(pet.speak()) pet_speak(niko) pet_speak(felix) print('*******************ABSTRACT CLASSES & INHERITANCE**************************') class Animal2(): def __init__(self,name): self.name = name def speak(self): raise NotImplementedError('SubClass must implement this abstract method!!') #myanimal = Animal2('fred') class Dog2(Animal2): def speak(self): return self.name + " says WOOF!" class Cat2(Animal2): def speak(self): return self.name + " says MEOW!" fido = Dog2('Fido') isis = Cat2('Isis') print(fido.speak()) print(isis.speak())
[ "sparihar08@yahoo.com" ]
sparihar08@yahoo.com
f13ae364d5454fff0b466fd17c8c4e70af0a9e2e
e836275adf8adca9b77acdd3d25bac157592a995
/examples/graphs_nodal.py
fa9e8e4ec004f0a57bfd774033e20c44044346d4
[ "BSD-3-Clause" ]
permissive
makism/dyconnmap
3de6f482d1370bf25ec3813ddf576b675ed99d9e
cbef247e635d55cb1489ba1e429d9d472b501b56
refs/heads/master
2023-08-03T19:30:40.779333
2022-03-14T18:24:16
2022-03-14T18:24:16
98,643,787
67
25
BSD-3-Clause
2023-07-24T04:49:03
2017-07-28T11:37:17
Python
UTF-8
Python
false
false
360
py
# -*- coding: utf-8 -*- from dyconnmap.graphs import nodal_global_efficiency import numpy as np if __name__ == '__main__': rng = np.random.RandomState(0) mtx = rng.rand(64, 64) mtx_symm = (mtx + mtx.T)/2 np.fill_diagonal(mtx_symm, 1.0) inv_fcg = 1.0 / mtx_symm nodal_ge = nodal_global_efficiency(1.0 / mtx_symm) print(nodal_ge)
[ "makhsm@gmail.com" ]
makhsm@gmail.com
d7796aa004c50f361ca9e8a8a0b3f4ef051ceb67
d9b672fd2096b9e91dda9c82a4ae47d628f023e4
/settings.py
a0655b84c59756eff3b37f60615c035fa474b8bd
[ "Apache-2.0" ]
permissive
homepods/silver-payu
3f314be0b1cd2409b80a79ad1519b0b881506d69
6d2ad761d5972f4b92928c12dde97959939d2786
refs/heads/master
2020-06-22T06:15:20.522288
2018-10-01T09:24:13
2018-10-01T09:24:13
197,654,966
1
0
null
2019-07-18T20:50:09
2019-07-18T20:50:09
null
UTF-8
Python
false
false
3,602
py
# Copyright (c) 2015 Presslabs SRL # # 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 silver import HOOK_EVENTS as _HOOK_EVENTS from django.utils.log import DEFAULT_LOGGING as LOGGING """ These settings are used by the ``manage.py`` command. """ import os DEBUG = False SITE_ID = 1 USE_TZ = True TIME_ZONE = 'UTC' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite', } } EXTERNAL_APPS = [ # Django core apps # 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', ] INSTALLED_APPS = EXTERNAL_APPS ROOT_URLCONF = 'silver.urls' PROJECT_ROOT = os.path.dirname(__file__) FIXTURE_DIRS = ( PROJECT_ROOT, PROJECT_ROOT + '/silver/' ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ PROJECT_ROOT + '/payment_processors/templates/', PROJECT_ROOT + '/templates/', PROJECT_ROOT + '/silver/templates/', ], 'OPTIONS': { 'context_processors': ( "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages" ) } } ] MEDIA_ROOT = PROJECT_ROOT + '/app_media/' MEDIA_URL = '/app_media/' STATIC_ROOT = PROJECT_ROOT + '/app_static/' STATIC_URL = '/app_static/' MIDDLEWARE_CLASSES = ( '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', ) SECRET_KEY = 'secret' REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'silver.api.pagination.LinkHeaderPagination' } LOGGING['loggers']['xhtml2pdf'] = { 'level': 'DEBUG', 'handlers': ['console'] } LOGGING['loggers']['pisa'] = { 'level': 'DEBUG', 'handlers': ['console'] } LOGGING['loggers']['django'] = { 'level': 'DEBUG', 'handlers': ['console'] } LOGGING['loggers']['django.security'] = { 'level': 'DEBUG', 'handlers': ['console'] } LOGGING['formatters'] = {} LOGGING['formatters']['verbose'] = { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
[ "vladtemian@gmail.com" ]
vladtemian@gmail.com
c74db58ad4e08ae2ba7fae4dcad8d34e14650f04
f719dc32c437a15c0eb7a229adc2848e4646a172
/billy/api/customer/forms.py
fd102c147046aae78bf8ff40db5b2ac935fa24db
[ "MIT", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
grang5/billy
db3a88b650962f25b8bdea80a81c5efa5d80dec0
a723c3aca18f817829ae088f469fabc5bea9d538
refs/heads/master
2021-04-18T19:36:05.586549
2014-06-16T21:47:37
2014-06-16T21:47:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
263
py
from __future__ import unicode_literals from wtforms import Form from wtforms import TextField from wtforms import validators class CustomerCreateForm(Form): processor_uri = TextField('URI of customer in processor', [ validators.Optional(), ])
[ "bornstub@gmail.com" ]
bornstub@gmail.com
b25403fc53f5f5969f36e94ee28d051866d5f2e6
5983ea8a59cd0b9763e0eb0dfc7f26dfd2ba5e60
/2019102962刘铎/刘铎-2019102962/DQN-First/maze_env.py
33157255db41910b66f0e97841906122112ce32f
[]
no_license
wanghan79/2020_Master_Python
0d8bdcff719a4b3917caa76ae318e3f8134fa83a
b3f6f3825b66b93ec6c54ed6187f6c0edcad6010
refs/heads/master
2021-01-26T13:29:09.439023
2020-06-23T02:17:52
2020-06-23T02:17:52
243,442,589
11
6
null
2020-03-29T05:59:29
2020-02-27T05:55:52
Python
UTF-8
Python
false
false
4,088
py
""" Reinforcement learning maze example. Red rectangle: explorer. Black rectangles: hells [reward = -1]. Yellow bin circle: paradise [reward = +1]. All other states: ground [reward = 0]. This script is the environment part of this example. The RL is in RL_brain.py. """ import numpy as np import time import sys if sys.version_info.major == 2: import Tkinter as tk else: import tkinter as tk UNIT = 40 # pixels MAZE_H = 4 # grid height MAZE_W = 4 # grid width class Maze(tk.Tk, object): def __init__(self): super(Maze, self).__init__() self.action_space = ['u', 'd', 'l', 'r'] self.n_actions = len(self.action_space) self.n_features = 2 self.title('maze') self.geometry('{0}x{1}'.format(MAZE_H * UNIT, MAZE_H * UNIT)) self._build_maze() def _build_maze(self): self.canvas = tk.Canvas(self, bg='white', height=MAZE_H * UNIT, width=MAZE_W * UNIT) # create grids for c in range(0, MAZE_W * UNIT, UNIT): x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT self.canvas.create_line(x0, y0, x1, y1) for r in range(0, MAZE_H * UNIT, UNIT): x0, y0, x1, y1 = 0, r, MAZE_W * UNIT, r self.canvas.create_line(x0, y0, x1, y1) # create origin origin = np.array([20, 20]) # hell hell1_center = origin + np.array([UNIT * 2, UNIT]) self.hell1 = self.canvas.create_rectangle( hell1_center[0] - 15, hell1_center[1] - 15, hell1_center[0] + 15, hell1_center[1] + 15, fill='black') # hell # hell2_center = origin + np.array([UNIT, UNIT * 2]) # self.hell2 = self.canvas.create_rectangle( # hell2_center[0] - 15, hell2_center[1] - 15, # hell2_center[0] + 15, hell2_center[1] + 15, # fill='black') # create oval oval_center = origin + UNIT * 2 self.oval = self.canvas.create_oval( oval_center[0] - 15, oval_center[1] - 15, oval_center[0] + 15, oval_center[1] + 15, fill='yellow') # create red rect self.rect = self.canvas.create_rectangle( origin[0] - 15, origin[1] - 15, origin[0] + 15, origin[1] + 15, fill='red') # pack all self.canvas.pack() def reset(self): self.update() time.sleep(0.1) self.canvas.delete(self.rect) origin = np.array([20, 20]) self.rect = self.canvas.create_rectangle( origin[0] - 15, origin[1] - 15, origin[0] + 15, origin[1] + 15, fill='red') # return observation return (np.array(self.canvas.coords(self.rect)[:2]) - np.array(self.canvas.coords(self.oval)[:2]))/(MAZE_H*UNIT) def step(self, action): s = self.canvas.coords(self.rect) base_action = np.array([0, 0]) if action == 0: # up if s[1] > UNIT: base_action[1] -= UNIT elif action == 1: # down if s[1] < (MAZE_H - 1) * UNIT: base_action[1] += UNIT elif action == 2: # right if s[0] < (MAZE_W - 1) * UNIT: base_action[0] += UNIT elif action == 3: # left if s[0] > UNIT: base_action[0] -= UNIT self.canvas.move(self.rect, base_action[0], base_action[1]) # move agent next_coords = self.canvas.coords(self.rect) # next state # reward function if next_coords == self.canvas.coords(self.oval): reward = 1 done = True elif next_coords in [self.canvas.coords(self.hell1)]: reward = -1 done = True else: reward = 0 done = False s_ = (np.array(next_coords[:2]) - np.array(self.canvas.coords(self.oval)[:2]))/(MAZE_H*UNIT) return s_, reward, done def render(self): # time.sleep(0.01) self.update()
[ "noreply@github.com" ]
wanghan79.noreply@github.com
cede0e482d3ea3a08d161be9ba8ae74f9c9f82fa
7dc05dc9ba548cc97ebe96ed1f0dab8dfe8d8b81
/trunk/pida/utils/pgd/debugsession.py
6e0c5d6df92cc9f56a44188a64b2d6b59d10bc26
[]
no_license
BackupTheBerlios/pida-svn
b68da6689fa482a42f5dee93e2bcffb167a83b83
739147ed21a23cab23c2bba98f1c54108f8c2516
refs/heads/master
2020-05-31T17:28:47.927074
2006-05-18T21:42:32
2006-05-18T21:42:32
40,817,392
1
0
null
null
null
null
UTF-8
Python
false
false
5,589
py
# -*- coding: utf-8 -*- # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # Copyright (c) 2006 Ali Afshar #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. import os import sys from winpdb import rpdb2 from console import Terminal def get_debugee_script_path(): import pkg_resources req = pkg_resources.Requirement.parse('pgd') try: sfile = pkg_resources.resource_filename(req, 'pgd/winpdb/rpdb2.py') except pkg_resources.DistributionNotFound: sfile = os.path.join( os.path.dirname(__file__), 'winpdb', 'rpdb2.py') if sfile.endswith('c'): sfile = sfile[:-1] return sfile class SessionManagerInternal(rpdb2.CSessionManagerInternal): def _spawn_server(self, fchdir, ExpandedFilename, args, rid): """ Start an OS console to act as server. What it does is to start rpdb again in a new console in server only mode. """ debugger = get_debugee_script_path() baseargs = ['python', debugger, '--debugee', '--rid=%s' % rid] if fchdir: baseargs.append('--chdir') if self.m_fAllowUnencrypted: baseargs.append('--plaintext') if self.m_fRemote: baseargs.append('--remote') if os.name == 'nt': baseargs.append('--pwd=%s' % self.m_pwd) if 'PGD_DEBUG' in os.environ: baseargs.append('--debug') baseargs.append(ExpandedFilename) cmdargs = baseargs + args.split() python_exec = sys.executable self.terminal.fork_command(python_exec, cmdargs) class SessionManager(rpdb2.CSessionManager): def __init__(self, app): self.app = app self.options = app.options self.main_window = app.main_window self.delegate = self._create_view() self._CSessionManager__smi = self._create_smi() def _create_smi(self): smi = SessionManagerInternal( self.options.pwd, self.options.allow_unencrypted, self.options.remote, self.options.host) smi.terminal = self return smi def _create_view(self): view = Terminal(self.app) self.main_window.attach_slave('outterm_holder', view) return view def fork_command(self, *args, **kw): self.delegate.terminal.fork_command(*args, **kw) def launch_filename(self, filename): self.app.launch(filename) class RunningOptions(object): def set_options(self, command_line, fAttach, fchdir, pwd, fAllowUnencrypted, fRemote, host): self.command_line = command_line self.attach = fAttach self.pwd = pwd self.allow_unencrypted = fAllowUnencrypted self.remote = fRemote self.host = host def connect_events(self): event_type_dict = {rpdb2.CEventState: {}} self.session_manager.register_callback(self.update_state, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventStackFrameChange: {}} self.session_manager.register_callback(self.update_frame, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventThreads: {}} self.session_manager.register_callback(self.update_threads, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventNoThreads: {}} self.session_manager.register_callback(self.update_no_threads, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventNamespace: {}} self.session_manager.register_callback(self.update_namespace, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventThreadBroken: {}} self.session_manager.register_callback(self.update_thread_broken, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventStack: {}} self.session_manager.register_callback(self.update_stack, event_type_dict, fSingleUse = False) event_type_dict = {rpdb2.CEventBreakpoint: {}} self.session_manager.register_callback(self.update_bp, event_type_dict, fSingleUse = False) def start(command_line, fAttach, fchdir, pwd, fAllowUnencrypted, fRemote, host): options= RunningOptions() options.set_options(command_line, fAttach, fchdir, pwd, fAllowUnencrypted, fRemote, host) return options def main(start): rpdb2.main(start) def start_as_cl(): rpdb2.main() if __name__ == '__main__': start_as_cl()
[ "aafshar@ef0b12da-61f9-0310-ba38-b2629ec279a7" ]
aafshar@ef0b12da-61f9-0310-ba38-b2629ec279a7
47abd26109c9522bd177dbbf0cd330a30d2b38c2
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03998/s861110715.py
06ced3f35c4b4debbacf590c69b46eaf81a9942e
[]
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
424
py
A = list(input()) B = list(input()) C = list(input()) n = A[0] del A[0] while True: if n == "a": if A == []: print("A") break n = A[0] del A[0] elif n == "b": if B == []: print("B") break n = B[0] del B[0] else: if C == []: print("C") break n = C[0] del C[0]
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
c041ce36c31bab982df6a4db67cbb9e648902b4e
d88e4152c0540c4c3c0a93c997ed8666d6ede863
/daeUSB.py
299f7ae439ebaf4837641b8975188e5fef04d3c2
[]
no_license
mahongquan/word_auto
2ad36383a435a0b020c3939e1efafec13a64a59f
552ecb5dc43fdd71785f6e188de7cd0df66345ac
refs/heads/master
2020-03-21T17:28:03.633892
2018-07-22T02:38:31
2018-07-22T02:38:31
138,833,600
0
0
null
null
null
null
UTF-8
Python
false
false
3,815
py
# -*- coding: utf-8 -*- #安装USB2COM驱动 import pywinauto import pywintypes from pywinauto import findwindows,handleprops import os import _thread import traceback from threading import Thread,Event import time def runUSB(): #cmd=r"start c:\9111\PCIS-DASK\PCIS-DASK.exe" cmd="start c:\\CS3000备份\\CDM21216_Setup.exe" os.system(cmd) class Program(object): """example for AutoResetEvent""" def main(self): _thread.start_new_thread(runUSB,())#start program wind=EastWind(self.mre) wind.start() self.mre.wait()#wait install finish def __init__(self): super(Program, self).__init__() self.mre=Event() class EastWind(Thread): """dmretring for EastWind""" def __init__(self, mreV): super(EastWind, self).__init__() self.mre=mreV def run(self): lookupWindow()#installing self.mre.set()#install finish def treatadlink(h): try: d=pywinauto.controls.hwndwrapper.DialogWrapper(h) #print(dir(d)) cs=d.children() d.set_focus() for c in cs: bt=c.window_text() if c.class_name()=="Button" and "Extract" in bt: c.set_focus() c.click_input() if c.class_name()=="Button" and "下一步" in bt: c.set_focus() c.click_input() if c.class_name()=="Button" and "Finish" in bt: c.set_focus() c.click_input() if c.class_name()=="Button" and "No" in bt: c.set_focus() c.click_input() except pywintypes.error as e: print(e) pass except TypeError as e: print(e) return True def treatQudong(h): try: d=pywinauto.controls.hwndwrapper.DialogWrapper(h) #print(dir(d)) cs=d.children() d.set_focus() for c in cs: bt=c.window_text() if(bt!=None): if c.class_name()=="Button" and "我接受" in bt: c.set_focus() c.click_input() if c.class_name()=="Button" and "下一步" in bt: c.set_focus() c.click_input() # if c.class_name()=="Button" and "完成" in bt: # c.set_focus() # c.click_input() # if c.class_name()=="Button" and "No" in bt: # c.set_focus() # c.click_input() except pywintypes.error as e: print(e) pass return True def lookupWindow(): idle=0 while(True): print("=================") try: wins=findwindows.find_windows() for win in wins: try: title=handleprops.text(win) print(title) if title!=None: if "FTDI" in title: print("--------------------find:"+title) if treatadlink(win): idle=0 elif "设备驱动程序" in title: print("、、、、、、、、、、、find:"+title) if treatQudong(win): idle=0 except UnicodeEncodeError as e: print(e) pass time.sleep(1)#每秒检查一次 idle+=1 if idle>5 :#连续五秒没有查找到窗口则退出 break except: traceback.print_exc() a=input("except") def main(): program=Program() program.main() if __name__=="__main__": lookupWindow()
[ "mahongquan@sina.com" ]
mahongquan@sina.com
132e5c34952c72f35e089c726777abaa59399bcd
daca4a0604a21e4dcdab501369704db24741938e
/webdriver/tests/sessions/new_session/invalid_capabilities.py
8452bfb11e908be7a06fd65f6138f6f0c3958cd8
[ "W3C", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-w3c-03-bsd-license", "BSD-3-Clause" ]
permissive
Spec-Ops/web-platform-tests
4ac91a784d5d363d261bfe92e251e6efd74b6b01
c07a244ceef0d0833f61f2efa227bc1c65371c9c
refs/heads/master
2020-12-11T06:08:52.141843
2017-10-20T11:55:15
2017-10-20T12:56:55
54,023,228
3
4
null
2016-09-06T21:01:15
2016-03-16T10:39:23
HTML
UTF-8
Python
false
false
3,428
py
#META: timeout=long import pytest from webdriver import error from conftest import product, flatten @pytest.mark.parametrize("value", [None, 1, "{}", []]) def test_invalid_capabilites(new_session, value): with pytest.raises(error.InvalidArgumentException): new_session({"capabilities": value}) @pytest.mark.parametrize("value", [None, 1, "{}", []]) def test_invalid_always_match(new_session, value): with pytest.raises(error.InvalidArgumentException): new_session({"capabilities": {"alwaysMatch": value}}) @pytest.mark.parametrize("value", [None, 1, "[]", {}]) def test_invalid_first_match(new_session, value): with pytest.raises(error.InvalidArgumentException): new_session({"capabilities": {"firstMatch": value}}) invalid_data = [ ("acceptInsecureCerts", [1, [], {}, "false"]), ("browserName", [1, [], {}, False]), ("browserVersion", [1, [], {}, False]), ("platformName", [1, [], {}, False]), ("pageLoadStrategy", [1, [], {}, False, "invalid", "NONE", "Eager", "eagerblah", "interactive", " eager", "eager "]), ("proxy", [1, [], "{}", {"proxyType": "SYSTEM"}, {"proxyType": "systemSomething"}, {"proxy type": "pac"}, {"proxy-Type": "system"}, {"proxy_type": "system"}, {"proxytype": "system"}, {"PROXYTYPE": "system"}, {"proxyType": None}, {"proxyType": 1}, {"proxyType": []}, {"proxyType": {"value": "system"}}, {" proxyType": "system"}, {"proxyType ": "system"}, {"proxyType ": " system"}, {"proxyType": "system "}]), ("timeouts", [1, [], "{}", {}, False, {"pageLOAD": 10}, {"page load": 10}, {"page load": 10}, {"pageLoad": "10"}, {"pageLoad": {"value": 10}}, {"invalid": 10}, {"pageLoad": -1}, {"pageLoad": 2**64}, {"pageLoad": None}, {"pageLoad": 1.1}, {"pageLoad": 10, "invalid": 10}, {" pageLoad": 10}, {"pageLoad ": 10}]), ("unhandledPromptBehavior", [1, [], {}, False, "DISMISS", "dismissABC", "Accept", " dismiss", "dismiss "]) ] @pytest.mark.parametrize("body", [lambda key, value: {"alwaysMatch": {key: value}}, lambda key, value: {"firstMatch": [{key: value}]}]) @pytest.mark.parametrize("key,value", flatten(product(*item) for item in invalid_data)) def test_invalid_values(new_session, body, key, value): with pytest.raises(error.InvalidArgumentException): resp = new_session({"capabilities": body(key, value)}) invalid_extensions = [ "firefox", "firefox_binary", "firefoxOptions", "chromeOptions", "automaticInspection", "automaticProfiling", "platform", "version", "browser", "platformVersion", "javascriptEnabled", "nativeEvents", "seleniumProtocol", "profile", "trustAllSSLCertificates", "initialBrowserUrl", "requireWindowFocus", "logFile", "logLevel", "safari.options", "ensureCleanSession", ] @pytest.mark.parametrize("body", [lambda key, value: {"alwaysMatch": {key: value}}, lambda key, value: {"firstMatch": [{key: value}]}]) @pytest.mark.parametrize("key", invalid_extensions) def test_invalid_extensions(new_session, body, key): with pytest.raises(error.InvalidArgumentException): resp = new_session({"capabilities": body(key, {})})
[ "james@hoppipolla.co.uk" ]
james@hoppipolla.co.uk
ecc937959d6a50bec48eee0e0c39cad9bc0593a0
3ff9821b1984417a83a75c7d186da9228e13ead9
/2020_August_Leetcode_30_days_challenge/Week_2_Excel Sheet Column Number/by_recursion_and_base_conversion.py
8614066d3ca3b81874534ab1c3be1896d784e563
[ "MIT" ]
permissive
brianchiang-tw/leetcode
fd4df1917daef403c48cb5a3f5834579526ad0c2
6978acfb8cb767002cb953d02be68999845425f3
refs/heads/master
2023-06-11T00:44:01.423772
2023-06-01T03:52:00
2023-06-01T03:52:00
222,939,709
41
12
null
null
null
null
UTF-8
Python
false
false
1,450
py
''' Description: Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701 Constraints: 1 <= s.length <= 7 s consists only of uppercase English letters. s is between "A" and "FXSHRXW". ''' class Solution: def titleToNumber(self, s: str) -> int: if len(s) == 1: # base case return ord(s) - ord('A') + 1 else: # general case return 26*self.titleToNumber( s[:-1] ) + self.titleToNumber( s[-1] ) # n : the length of string, s ## Time Complexity: O( n ) # # The overhead in time is the cost of recusion depth, which is of O( n ). ## Space Comeplexity: O( n ) # # The overhead in space is the storage for recursion call stack, which is of O( n ). import unittest class Testing( unittest.TestCase ): def test_case_1( self ): result = Solution().titleToNumber( s='A' ) self.assertEqual(result, 1) def test_case_2( self ): result = Solution().titleToNumber( s='AB' ) self.assertEqual(result, 28) def test_case_3( self ): result = Solution().titleToNumber( s='ZY' ) self.assertEqual(result, 701) if __name__ == '__main__': unittest.main()
[ "brianchiang1988@icloud.com" ]
brianchiang1988@icloud.com
181242534741172deff30d1570b6c1e64b1d1641
6daaf3cecb19f95265188adc9afc97e640ede23c
/python_design/pythonprogram_design/Ch5/5-3-E60.py
cae23228ee53270139ad9d77e1371e78ac0da7f0
[]
no_license
guoweifeng216/python
723f1b29610d9f536a061243a64cf68e28a249be
658de396ba13f80d7cb3ebd3785d32dabe4b611d
refs/heads/master
2021-01-20T13:11:47.393514
2019-12-04T02:23:36
2019-12-04T02:23:36
90,457,862
0
0
null
null
null
null
UTF-8
Python
false
false
682
py
import pickle def main(): ## Display the large cities in a specified state. largeCities = createDictionaryFromBinaryFile("LargeCitiesDict.dat") state = input("Enter the name of a state: ") getCities(state, largeCities) def createDictionaryFromBinaryFile(fileName): # Assume pickle module has been imported. infile = open(fileName, 'rb') dictionaryName = pickle.load(infile) infile.close() return dictionaryName def getCities(state, dictionaryName): if dictionaryName[state] != []: print("Large cities:", " ".join(dictionaryName[state])) else: print("There are no large cities in", state + '.') main()
[ "weifeng.guo@cnexlabs.com" ]
weifeng.guo@cnexlabs.com
9f9de4a0ce359c148f01dc85de77fe73c15d295b
06a38963f22f8a74cc129033f8f1cac7f114cf5d
/problem_set_1/.history/src/p03d_poisson_20210517220103.py
6c67a7f7ecde98d6ae3463c6f27704f0d07843ae
[]
no_license
lulugai/CS229
47e59bcefe9dccbb83c6d903682eb6ddca3a24b5
4dd77b2895559689e875afe749360c3751a12cf1
refs/heads/main
2023-05-09T17:39:45.336695
2021-06-01T09:15:25
2021-06-01T09:15:25
372,768,960
0
0
null
null
null
null
UTF-8
Python
false
false
2,462
py
import numpy as np import util from linear_model import LinearModel def main(lr, train_path, eval_path, pred_path): """Problem 3(d): Poisson regression with gradient ascent. Args: lr: Learning rate for gradient ascent. train_path: Path to CSV file containing dataset for training. eval_path: Path to CSV file containing dataset for evaluation. pred_path: Path to save predictions. """ # Load training set x_train, y_train = util.load_dataset(train_path, add_intercept=True) # *** START CODE HERE *** # Fit a Poisson Regression model # Run on the validation set, and use np.savetxt to save outputs to pred_path x_val, y_val = util.load_dataset(eval_path, add_intercept=True) logreg = PoissonRegression() logreg.fit(x_train, y_train) print("Theta is: ", logreg.theta) print("The accuracy on training set is: ", np.mean(logreg.predict(x_train) == y_train)) print("The accuracy on valid set is: ", np.mean(logreg.predict(x_val) == y_val)) np.savetxt(pred_path, logreg.predict(x_val)) # *** END CODE HERE *** class PoissonRegression(LinearModel): """Poisson Regression. Example usage: > clf = PoissonRegression(step_size=lr) > clf.fit(x_train, y_train) > clf.predict(x_eval) """ def h(self, theta, x): return np.exp(x @ theta) def fit(self, x, y): """Run gradient ascent to maximize likelihood for Poisson regression. Args: x: Training example inputs. Shape (m, n). y: Training example labels. Shape (m,). """ # *** START CODE HERE *** m, n = x.shape if self.theta is None: self.theta = np.zeros(n) theta = self.theta next_theta = theta + self.step_size / m * x.T @ (y - self.h(theta, x)) print(next_theta) while np.linalg.norm(self.step_size / m * x.T @ (y - self.h(theta, x)), 1) >= self.eps: theta = next_theta next_theta = theta + self.step_size / m * x.T @ (y - self.h(theta, x)) self.theta = theta # *** END CODE HERE *** def predict(self, x): """Make a prediction given inputs x. Args: x: Inputs of shape (m, n). Returns: Floating-point prediction for each input, shape (m,). """ # *** START CODE HERE *** return self.h(self.theta, x) # *** END CODE HERE ***
[ "2927791087@qq.com" ]
2927791087@qq.com
acf5d4b77fd234775af80508e3a4688f0811f179
37e53bb1d47004e956119e7e7047b8194b3142f5
/grok/recursion_ver_3.py
1d12fa0694653459fa11a17525f97743ce815aa0
[]
no_license
fortredux/py_miscellaneous
eea82f900434ef23d98769f9057c87c97b278e45
7aee7c8bc0ddda1e137e4cb7e88eed78dbdb98d8
refs/heads/master
2020-12-21T21:03:28.897746
2020-04-05T20:44:55
2020-04-05T20:44:55
236,560,060
0
0
null
null
null
null
UTF-8
Python
false
false
278
py
def check(i): i = int(i) if i == 0: print('0') return False else: return True def countdown(num): x = check(num) while x is True: num = int(num) print(num) return countdown(num-1) countdown('15')
[ "fortunaredux@protonmail.com" ]
fortunaredux@protonmail.com
9092164cade33e786253089e178044d0156653f7
71d4fafdf7261a7da96404f294feed13f6c771a0
/mainwebsiteenv/lib/python2.7/site-packages/phonenumbers/shortdata/region_SK.py
fdc7ed9e7dd3d18546d0c1cdbe188f1eb3101d50
[]
no_license
avravikiran/mainwebsite
53f80108caf6fb536ba598967d417395aa2d9604
65bb5e85618aed89bfc1ee2719bd86d0ba0c8acd
refs/heads/master
2021-09-17T02:26:09.689217
2018-06-26T16:09:57
2018-06-26T16:09:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
756
py
"""Auto-generated file, do not edit by hand. SK metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_SK = PhoneMetadata(id='SK', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}', possible_length=(3, 4, 5, 6)), toll_free=PhoneNumberDesc(national_number_pattern='116\\d{3}', example_number='116000', possible_length=(6,)), emergency=PhoneNumberDesc(national_number_pattern='1(?:12|5[058])', example_number='112', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='1(?:1(?:2|6(?:000|111)|8[0-8])|[24]\\d{3}|5[0589]|8\\d{3})', example_number='112', possible_length=(3, 4, 5, 6)), short_data=True)
[ "me15btech11039@iith.ac.in.com" ]
me15btech11039@iith.ac.in.com
e3ccc17dad2cce4bc4775644166167b2526d35eb
6c5ce1e621e0bd140d127527bf13be2093f4a016
/ex044/exercicio044.py
290134b8ab1da627fa43d612670b1700cc3f8065
[ "MIT" ]
permissive
ArthurAlesi/Python-Exercicios-CursoEmVideo
124e2ee82c3476a5a49baafed657788591a232c1
ed0f0086ddbc0092df9d16ec2d8fdbabcb480cdd
refs/heads/master
2022-12-31T13:21:30.001538
2020-09-24T02:09:23
2020-09-24T02:09:23
268,917,509
0
0
null
null
null
null
UTF-8
Python
false
false
796
py
# Elabore um programa que calcule o valor a ser pago por um produto # considerando o preço normal e condição de pagamento # a vista dinheiro 10% de desconto # a vista cartao 5% de desconto # 2x cartao preço normal # 3x ou mais compra = float(input("Informe o preço das compras")) print("Escolha a forma de pagamento") print("1 - vista dinheiro/cheque") print("2 - vista cartao") print("3 - 2x cartao") print("4 - 3x ou + cartao") entrada = int(input()) if entrada == 1: total = compra * 0.9 print("Voce pagara ", total) elif entrada == 2: total = compra * 0.95 print("Voce pagara ", total) elif entrada == 3: parcela = compra / 2 print("2 parcelas de ", parcela) elif entrada ==4: total = compra * 1.2 parcela = total / 3 print("3 parcelas de ", parcela)
[ "54421573+ArthurAlesi@users.noreply.github.com" ]
54421573+ArthurAlesi@users.noreply.github.com
a2669f6f3cf2be4424ef7db7edfd60b48effbd05
187a6558f3c7cb6234164677a2bda2e73c26eaaf
/jdcloud_sdk/services/logs/apis/TestMetricTaskRequest.py
8e2bba6c9cb8119d77246c48816fc0632e6a8191
[ "Apache-2.0" ]
permissive
jdcloud-api/jdcloud-sdk-python
4d2db584acc2620b7a866af82d21658cdd7cc227
3d1c50ed9117304d3b77a21babe899f939ae91cd
refs/heads/master
2023-09-04T02:51:08.335168
2023-08-30T12:00:25
2023-08-30T12:00:25
126,276,169
18
36
Apache-2.0
2023-09-07T06:54:49
2018-03-22T03:47:02
Python
UTF-8
Python
false
false
3,730
py
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class TestMetricTaskRequest(JDCloudRequest): """ 日志测试,根据用户输入的日志筛选条件以及监控指标设置进行模拟监控统计 """ def __init__(self, parameters, header=None, version="v1"): super(TestMetricTaskRequest, self).__init__( '/regions/{regionId}/logsets/{logsetUID}/logtopics/{logtopicUID}/metrictaskTest', 'POST', header, version) self.parameters = parameters class TestMetricTaskParameters(object): def __init__(self, regionId,logsetUID,logtopicUID,content, ): """ :param regionId: 地域 Id :param logsetUID: 日志集 UID :param logtopicUID: 日志主题 UID :param content: 测试内容 """ self.regionId = regionId self.logsetUID = logsetUID self.logtopicUID = logtopicUID self.aggregate = None self.content = content self.dataField = None self.filterContent = None self.filterOpen = None self.filterType = None self.metric = None self.settingType = None self.sqlSpec = None def setAggregate(self, aggregate): """ :param aggregate: (Optional) 聚合函数,支持 count sum max min avg; 配置方式(SettingType) 为 空或visual 时,必填; """ self.aggregate = aggregate def setDataField(self, dataField): """ :param dataField: (Optional) 查询字段,支持 英文字母 数字 下划线 中划线 点(中文日志原文和各产品线的key); 配置方式(SettingType) 为 空或visual 时,必填; """ self.dataField = dataField def setFilterContent(self, filterContent): """ :param filterContent: (Optional) 过滤语法,可以为空 """ self.filterContent = filterContent def setFilterOpen(self, filterOpen): """ :param filterOpen: (Optional) 是否打开过滤; 配置方式(SettingType) 为 空或visual 时,必填; """ self.filterOpen = filterOpen def setFilterType(self, filterType): """ :param filterType: (Optional) 过滤类型,只能是fulltext和 advance; 配置方式(SettingType) 为 空或visual 时,必填; """ self.filterType = filterType def setMetric(self, metric): """ :param metric: (Optional) 监控项 , 支持大小写英文字母 下划线 数字 点,且不超过255byte(不支持中划线); 配置方式(SettingType) 为 空或visual 时,必填; """ self.metric = metric def setSettingType(self, settingType): """ :param settingType: (Optional) 配置方式: 可选参数;枚举值 visual,sql;分别代表可视化配置及sql配置方式,传空表示可视化配置; """ self.settingType = settingType def setSqlSpec(self, sqlSpec): """ :param sqlSpec: (Optional) """ self.sqlSpec = sqlSpec
[ "jdcloud-api@jd.com" ]
jdcloud-api@jd.com
5aa6d0190c71dff4c9372596cae52cfd9393b80b
08a93de4813e0efb5cf40ac490eb0502266ca8ba
/settings/urls.py
c64f4a4821b4b9656b8e0cfa43d8ede15897236c
[ "BSD-2-Clause" ]
permissive
hunglethanh9/modelchimp
eaf3a8c6c73a3ed4c942fa361d8b661bf5d92a87
cdb8162cdb554aa5ef00999f390138bd8325f472
refs/heads/master
2020-06-06T00:09:33.447383
2019-06-18T13:02:03
2019-06-18T13:02:03
192,582,892
1
0
null
2019-06-18T17:14:47
2019-06-18T17:14:47
null
UTF-8
Python
false
false
1,188
py
from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import ( PasswordResetView, PasswordResetConfirmView, PasswordResetDoneView, PasswordResetCompleteView, ) urlpatterns = [ url(r'^api/', include('settings.api_urls')), url(r'^api/v2/', include('settings.api_urls_v2')), url(r'^hq/', admin.site.urls), # Password reset views url(r'^password_reset/$', PasswordResetView.as_view(), name='password_reset'), url(r'^password_reset/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', PasswordResetCompleteView.as_view(),name='password_reset_complete'), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
[ "samir.madhavan@gmail.com" ]
samir.madhavan@gmail.com
d7c759cbcfcbf99821bb0d3e66eb3e9796632e2b
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_hires.py
55de384efb494e1deadbf5e334722a21e472f366
[ "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
224
py
from xai.brain.wordbase.nouns._hire import _HIRE #calss header class _HIRES(_HIRE, ): def __init__(self,): _HIRE.__init__(self) self.name = "HIRES" self.specie = 'nouns' self.basic = "hire" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
e3609abff0757e33f926d3770d5d1e1febb9b6ab
b007d88e6726452ffa8fe80300614f311ae5b318
/LeetCode/facebook/arrays_and_strings/merge_sorted_array.py
3713e9ba76233fd84aca0a38b42724a3074bffa4
[]
no_license
jinurajan/Datastructures
ec332b12b8395f42cb769e771da3642f25ba7e7f
647fea5d2c8122468a1c018c6829b1c08717d86a
refs/heads/master
2023-07-06T14:42:55.168795
2023-07-04T13:23:22
2023-07-04T13:23:22
76,943,162
0
0
null
null
null
null
UTF-8
Python
false
false
1,082
py
""" Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Constraints: nums1.length == m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -109 <= nums1[i], nums2[i] <= 109 """ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ while m-1 >=0 and n-1 >= 0: if nums1[m-1] > nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if m - 1 < 0: # nums 1 is empty nums1[:n] = nums2[:n]
[ "jinu.p.r@gmail.com" ]
jinu.p.r@gmail.com
9b97c3e7ea9e41ffbc45b8c498367f691295fa0e
58cd392c642ac9408349f03dc72927db6abcce55
/team2/src/Without_Doubt_Project/venv/lib/python3.6/site-packages/earlgrey/patterns/rpc/client_async.py
a94df1e4d861d470e4928d8f5d3ed96175e519b9
[]
no_license
icon-hackathons/201902-dapp-competition-bu
161226eb792425078351c790b8795a0fe5550735
f3898d31a20f0a85637f150d6187285514528d53
refs/heads/master
2020-04-24T07:48:18.891646
2019-04-18T01:47:21
2019-04-18T01:47:21
171,809,810
3
11
null
2019-04-18T01:47:23
2019-02-21T06:01:04
Python
UTF-8
Python
false
false
4,824
py
# Copyright 2017 theloop Inc. # # 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. # The original codes exist in aio_pika.patterns.rpc import asyncio import logging import time from concurrent import futures from aio_pika.exchange import ExchangeType from aio_pika.channel import Channel from aio_pika.exceptions import UnroutableError from aio_pika.message import Message, IncomingMessage, DeliveryMode, ReturnedMessage from aio_pika.tools import create_future from aio_pika.patterns.base import Base class ClientAsync(Base): DLX_NAME = 'rpc.dlx' def __init__(self, channel: Channel, queue_name): self.channel = channel self.queue_name = queue_name self.queue = None self.result_queue = None self.async_futures = {} self.concurrent_futures = {} self.func_names = {} self.routes = {} self.dlx_exchange = None @asyncio.coroutine def initialize_exchange(self): self.dlx_exchange = yield from self.channel.declare_exchange( self.DLX_NAME, type=ExchangeType.HEADERS, auto_delete=True, ) @asyncio.coroutine def initialize_queue(self, **kwargs): arguments = kwargs.pop('arguments', {}).update({ 'x-dead-letter-exchange': self.DLX_NAME, }) kwargs['arguments'] = arguments self.queue = yield from self.channel.declare_queue(name=self.queue_name, **kwargs) self.result_queue = yield from self.channel.declare_queue(None, exclusive=True, auto_delete=True) yield from self.result_queue.bind( self.dlx_exchange, "", arguments={ "From": self.result_queue.name, 'x-match': 'any', } ) yield from self.result_queue.consume( self._on_result_message, no_ack=True ) self.channel.add_on_return_callback(self._on_message_returned) def _on_message_returned(self, message: ReturnedMessage): correlation_id = int(message.correlation_id) if message.correlation_id else None future = self.async_futures.pop(correlation_id, None) or self.concurrent_futures.pop(correlation_id, None) if future and future.done(): logging.warning("Unknown message was returned: %r", message) else: future.set_exception(UnroutableError([message])) @asyncio.coroutine def _on_result_message(self, message: IncomingMessage): correlation_id = int(message.correlation_id) if message.correlation_id else None try: future = self.async_futures[correlation_id] # type: asyncio.Future except KeyError: pass else: payload = self.deserialize(message.body) if message.type == 'result': future.set_result(payload) elif message.type == 'error': future.set_exception(payload) elif message.type == 'call': future.set_exception(asyncio.TimeoutError("Message timed-out", message)) else: future.set_exception(RuntimeError("Unknown message type %r" % message.type)) @asyncio.coroutine def call(self, func_name, kwargs: dict=None, *, expiration: int=None, priority: int=128, delivery_mode: DeliveryMode=DeliveryMode.NOT_PERSISTENT): future = self._create_future() message = Message( body=self.serialize(kwargs or {}), type='call', timestamp=time.time(), expiration=expiration, priority=priority, correlation_id=id(future), delivery_mode=delivery_mode, reply_to=self.result_queue.name, headers={ 'From': self.result_queue.name, 'FuncName': func_name }, ) yield from self.channel.default_exchange.publish( message, routing_key=self.queue_name, mandatory=True ) return (yield from future) def _create_future(self) -> asyncio.Future: future = create_future(loop=self.channel.loop) future_id = id(future) self.async_futures[future_id] = future future.add_done_callback(lambda f: self.async_futures.pop(future_id, None)) return future
[ "41354736+sojinkim-icon@users.noreply.github.com" ]
41354736+sojinkim-icon@users.noreply.github.com
62cbc2bc1f0553ebc160c9187f62311a93b9fbf8
11ddf56093b5a821a080249f6fc2e50e34f8970d
/opennsa/backends/dud.py
ad776c4f171d702c54f71fa839ea79587c1479fa
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
igable/opennsa
067d0043d324e32cebb6967023fbcc0df9ec836c
5db943d50310345d18113dbfbe2251bb2a1a63f0
refs/heads/master
2021-01-15T08:36:33.998695
2014-02-11T11:49:53
2014-02-13T13:28:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,800
py
""" NRM backends which just logs actions performed. Author: Henrik Thostrup Jensen <htj@nordu.net> Copyright: NORDUnet (2011) """ import string import random from twisted.python import log from twisted.internet import defer from opennsa.backends.common import genericbackend def DUDNSIBackend(network_name, network_topology, parent_requester, port_map, configuration): name = 'DUD NRM %s' % network_name cm = DUDConnectionManager(name, port_map) return genericbackend.GenericBackend(network_name, network_topology, cm, parent_requester, name) class DUDConnectionManager: def __init__(self, log_system, port_map): self.log_system = log_system self.port_map = port_map def getResource(self, port, label_type, label_value): return self.port_map[port] def getTarget(self, port, label_type, label_value): return self.port_map[port] + '#' + label_value def createConnectionId(self, source_target, dest_target): return 'DUD-' + ''.join( [ random.choice(string.hexdigits[:16]) for _ in range(8) ] ) def canSwapLabel(self, label_type): #return True return False def setupLink(self, connection_id, source_target, dest_target, bandwidth): log.msg('Link %s -> %s up' % (source_target, dest_target), system=self.log_system) return defer.succeed(None) #from opennsa import error #return defer.fail(error.InternalNRMError('Link setup failed')) def teardownLink(self, connection_id, source_target, dest_target, bandwidth): log.msg('Link %s -> %s down' % (source_target, dest_target), system=self.log_system) return defer.succeed(None) #from opennsa import error #return defer.fail(error.InternalNRMError('Link teardown failed'))
[ "htj@nordu.net" ]
htj@nordu.net
1f2eeaf30554fc2b63cc3c041524f636236bf967
2e927b6e4fbb4347f1753f80e9d43c7d01b9cba5
/Section 20 - Lamba Functions/lambdas.py
2d5e9687c5496af858166dab6f7b8ab7af2a3de4
[]
no_license
tielushko/The-Modern-Python-3-Bootcamp
ec3d60d1f2e887d693efec1385a6dbcec4aa8b9a
17b3156f256275fdba204d514d914731f7038ea5
refs/heads/master
2023-01-22T01:04:31.918693
2020-12-04T02:41:29
2020-12-04T02:41:29
262,424,068
0
0
null
null
null
null
UTF-8
Python
false
false
1,097
py
def square(num): return num*num #syntax - lambda parameter: code in one line without return - you usually don't store that in variable square2 = lambda num: num * num add = lambda num: num + num print(square2(3)) print(square2.__name__) #use case - passing in a function as a parameter into another function. short and sweet, single expression #map - accepts at least two arguments, a function and an "iterable" """ It runs the lambda for each value in the iterable and returns a map object that can be converted into a different data structure""" nums = [2,4,6,8,10] doubles = map(lambda x: x*2, nums) # returns map object people = ["Darcy", 'Anabel', 'Dana', 'Christina'] peeps = map(lambda name: name.upper(), people) print(list(peeps)) #Exercise 1: Decrement each element in list by one def decrement_list(l_for_list): return list(map(lambda x: x - 1, l_for_list)) #filter - there is a lambda for each value in the iterable """ returns filter object, contains only objects that return true to lambda """ l = [1,2,3,4] evens = list(filter(lambda x: x % 2 == 0, l)) print(evens)
[ "tielushko@mail.usf.edu" ]
tielushko@mail.usf.edu
575abf06c7f23652b3a2ac3b595778e90ab5e287
663c108dca9c4a30b7dfdc825a8f147ba873da52
/venv/functions/38GlobalKeywordDeclareAssignError.py
1dd186e5658999379d9e336cc39512ba1c6f8a73
[]
no_license
ksrntheja/08-Python-Core
54c5a1e6e42548c10914f747ef64e61335e5f428
b5fe25eead8a0fcbab0757b118d15eba09b891ba
refs/heads/master
2022-10-02T04:11:07.845269
2020-06-02T15:23:18
2020-06-02T15:23:18
261,644,116
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
def f01(): global a = 10 print(a) def f02(): print(a) f01() f02() # File "/Code/venv/functions/38GlobalKeywordDeclareAssignError", line <> # global a = 10 # ^ # SyntaxError: invalid syntax
[ "srntkolla@gmail.com" ]
srntkolla@gmail.com
6a89e67c4330943ffd882ccd41577f252a47d876
d4abaedd47e5a3ce3e8aa7893cb63faaa4064551
/spoj/bearseg.py
0e1ced7689b4dc52b995ffd978e630c5f46fadb7
[]
no_license
shiv125/Competetive_Programming
fc1a39be10c0588e0222efab8809b966430fe20f
9c949c6d6b5f83a35d6f5f6a169c493f677f4003
refs/heads/master
2020-03-15T19:47:12.944241
2018-05-06T08:18:11
2018-05-06T08:18:11
132,317,356
0
0
null
null
null
null
UTF-8
Python
false
false
424
py
t=input() MAX=10**5+1 lookup=[0]*MAX while t>0: t-=1 n,p=map(int,raw_input().split()) arr=map(int,raw_input().split()) lookup[0]=arr[0] for i in range(1,n): lookup[i]=lookup[i-1]+arr[i] count={} ma=-1 for i in range(n): for j in range(i,n): if i!=0: z=(lookup[j]-lookup[i-1]+p)%p else: z=lookup[j]%p ma=max(ma,z) if z not in count: count[z]=1 else: count[z]+=1 print ma,count[ma]
[ "shivdutt@shivdutt-Lenovo-G50-80" ]
shivdutt@shivdutt-Lenovo-G50-80
e57399c656326fe5aad20cd04948bccb429a51df
274eb3a3c4202c86a40e13d2de7c2d6f2a982fcb
/tests/unit/altimeter/aws/resource/ec2/test_vpc_endpoint_service.py
6823edb92f519c7b51b496fae25c2ff3d1253997
[ "MIT", "Python-2.0" ]
permissive
tableau/altimeter
6199b8827d193946bb0d0d1e29e462fc8749d3e4
eb7d5d18f3d177973c4105c21be9d251250ca8d6
refs/heads/master
2023-08-15T16:21:31.265590
2023-07-04T13:13:32
2023-07-04T13:13:32
212,153,766
75
25
MIT
2023-08-02T02:05:22
2019-10-01T17:10:16
Python
UTF-8
Python
false
false
2,670
py
import unittest from altimeter.aws.resource.ec2.vpc_endpoint_service import VpcEndpointServiceResourceSpec from altimeter.core.resource.resource import Resource from altimeter.core.graph.links import LinkCollection, SimpleLink, TagLink class TestVpcEndpointServiceResourceSpec(unittest.TestCase): maxDiff = None def test_schema_parse(self): resource_arn = "arn:aws:ec2:us-west-2:111122223333:vpc-endpoint-service/com.amazonaws.vpce.us-west-2.vpce-svc-01234abcd5678ef01" aws_resource_dict = { "ServiceType": [{"ServiceType": "Interface"}], "ServiceId": "vpce-svc-01234abcd5678ef01", "ServiceName": "com.amazonaws.vpce.us-west-2.vpce-svc-01234abcd5678ef01", "ServiceState": "Available", "AvailabilityZones": ["us-west-2a", "us-west-2b"], "AcceptanceRequired": True, "ManagesVpcEndpoints": False, "NetworkLoadBalancerArns": [ "arn:aws:elasticloadbalancing:us-west-2:111122223333:loadbalancer/net/splunk-hwf-lb/1a7ff9c18eeaaf9b" ], "BaseEndpointDnsNames": ["vpce-svc-01234abcd5678ef01.us-west-2.vpce.amazonaws.com"], "PrivateDnsNameConfiguration": {}, "Tags": [{"Key": "Name", "Value": "Splunk HEC"}], } link_collection = VpcEndpointServiceResourceSpec.schema.parse( data=aws_resource_dict, context={"account_id": "111122223333", "region": "us-west-2"} ) resource = Resource( resource_id=resource_arn, type=VpcEndpointServiceResourceSpec.type_name, link_collection=link_collection, ) expected_resource = Resource( resource_id="arn:aws:ec2:us-west-2:111122223333:vpc-endpoint-service/com.amazonaws.vpce.us-west-2.vpce-svc-01234abcd5678ef01", type="vpc-endpoint-service", link_collection=LinkCollection( simple_links=( SimpleLink(pred="service_type", obj="Interface"), SimpleLink( pred="service_name", obj="com.amazonaws.vpce.us-west-2.vpce-svc-01234abcd5678ef01", ), SimpleLink(pred="service_state", obj="Available"), SimpleLink(pred="acceptance_required", obj=True), SimpleLink(pred="availability_zones", obj="us-west-2a"), SimpleLink(pred="availability_zones", obj="us-west-2b"), ), tag_links=(TagLink(pred="Name", obj="Splunk HEC"),), ), ) self.assertEqual(resource, expected_resource)
[ "noreply@github.com" ]
tableau.noreply@github.com
9e73235485cb9b7abfd44cdb5134347f883ec5e0
c31d185fb65da94dc15e16869ef1fbaf0dabc736
/base/views.py
0ec041e02c0386a93c8196390322f023f393e73e
[]
no_license
Joacoco/nosotrosusamos
2777907b3df3b4022770f9ccef554d4c2b2c53c8
593d087c303f72136f6c425e908631357298c1eb
refs/heads/master
2020-12-26T05:01:28.674841
2013-12-02T13:37:49
2013-12-02T13:37:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
353
py
# -*- coding: utf-8 -*- """ This file contains some generic purpouse views """ from django.shortcuts import render_to_response from django.template import RequestContext def index(request): """ view that renders a default home""" return render_to_response('index.jade', context_instance=RequestContext(request))
[ "ignacio.munizaga.t@gmail.com" ]
ignacio.munizaga.t@gmail.com
a6084bfe94a88078593f1b6359db3a036eae22de
c6759b857e55991fea3ef0b465dbcee53fa38714
/tools/nntool/nntool/importer/tflite2/tflite_schema_head/PackOptions.py
80d5354a3e6d6c474f93bce81eb2b362de5ab65e
[ "AGPL-3.0-or-later", "AGPL-3.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
GreenWaves-Technologies/gap_sdk
1b343bba97b7a5ce62a24162bd72eef5cc67e269
3fea306d52ee33f923f2423c5a75d9eb1c07e904
refs/heads/master
2023-09-01T14:38:34.270427
2023-08-10T09:04:44
2023-08-10T09:04:44
133,324,605
145
96
Apache-2.0
2023-08-27T19:03:52
2018-05-14T07:50:29
C
UTF-8
Python
false
false
2,002
py
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite_schema_head import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class PackOptions(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = PackOptions() x.Init(buf, n + offset) return x @classmethod def GetRootAsPackOptions(cls, buf, offset=0): """This method is deprecated. Please switch to GetRootAs.""" return cls.GetRootAs(buf, offset) @classmethod def PackOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) # PackOptions def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # PackOptions def ValuesCount(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) return 0 # PackOptions def Axis(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) return 0 def PackOptionsStart(builder): builder.StartObject(2) def Start(builder): return PackOptionsStart(builder) def PackOptionsAddValuesCount(builder, valuesCount): builder.PrependInt32Slot(0, valuesCount, 0) def AddValuesCount(builder, valuesCount): return PackOptionsAddValuesCount(builder, valuesCount) def PackOptionsAddAxis(builder, axis): builder.PrependInt32Slot(1, axis, 0) def AddAxis(builder, axis): return PackOptionsAddAxis(builder, axis) def PackOptionsEnd(builder): return builder.EndObject() def End(builder): return PackOptionsEnd(builder)
[ "yao.zhang@greenwaves-technologies.com" ]
yao.zhang@greenwaves-technologies.com
6b2a348908d35fad77fed82f1775983dd9ffd7cf
cc096d321ab5c6abf54fdcea67f10e77cd02dfde
/flex-backend/pypy/translator/jvm/methods.py
582a5f04b0c2e370370a0d62c2866cc366e73d0a
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
limweb/flex-pypy
310bd8fcd6a9ddc01c0b14a92f0298d0ae3aabd2
05aeeda183babdac80f9c10fca41e3fb1a272ccb
refs/heads/master
2021-01-19T22:10:56.654997
2008-03-19T23:51:59
2008-03-19T23:51:59
32,463,309
0
0
null
null
null
null
UTF-8
Python
false
false
6,487
py
""" Special methods which we hand-generate, such as toString(), equals(), and hash(). These are generally added to methods listing of node.Class, and the only requirement is that they must have a render(self, gen) method. """ import pypy.translator.jvm.generator as jvmgen import pypy.translator.jvm.typesystem as jvmtype from pypy.rpython.ootypesystem import ootype, rclass class BaseDumpMethod(object): def __init__(self, db, OOCLASS, clsobj): self.db = db self.OOCLASS = OOCLASS self.clsobj = clsobj self.name = "toString" self.jargtypes = [clsobj] self.jrettype = jvmtype.jString def _print_field_value(self, fieldnm, FIELDOOTY): self.gen.emit(jvmgen.DUP) self.gen.load_this_ptr() fieldobj = self.clsobj.lookup_field(fieldnm) fieldobj.load(self.gen) dumpmethod = self.db.toString_method_for_ootype(FIELDOOTY) self.gen.emit(dumpmethod) self.gen.emit(jvmgen.PYPYAPPEND) def _print(self, str): self.gen.emit(jvmgen.DUP) self.gen.load_string(str) self.gen.emit(jvmgen.PYPYAPPEND) def render(self, gen): self.gen = gen gen.begin_function( self.name, (), self.jargtypes, self.jrettype, static=False) gen.new_with_jtype(jvmtype.jStringBuilder) self._render_guts(gen) gen.emit(jvmgen.OBJTOSTRING) gen.emit(jvmgen.RETURN.for_type(jvmtype.jString)) gen.end_function() self.gen = None class InstanceDumpMethod(BaseDumpMethod): def _render_guts(self, gen): clsobj = self.clsobj genprint = self._print # Start the dump genprint("InstanceWrapper(") genprint("'" + self.OOCLASS._name + "', ") genprint("{") for fieldnm, (FIELDOOTY, fielddef) in self.OOCLASS._fields.iteritems(): if FIELDOOTY is ootype.Void: continue genprint('"'+fieldnm+'":') print "fieldnm=%r fieldty=%r" % (fieldnm, FIELDOOTY) # Print the value of the field: self._print_field_value(fieldnm, FIELDOOTY) # Dump close genprint("})") class RecordDumpMethod(BaseDumpMethod): def _render_guts(self, gen): clsobj = self.clsobj genprint = self._print # We only render records that represent tuples: # In that case, the field names look like item0, item1, etc # Otherwise, we just do nothing... this is because we # never return records that do not represent tuples from # a testing function for f_name in self.OOCLASS._fields: if not f_name.startswith('item'): return # Start the dump genprint("StructTuple((") numfields = len(self.OOCLASS._fields) for i in range(numfields): f_name = 'item%d' % i FIELD_TYPE, f_default = self.OOCLASS._fields[f_name] if FIELD_TYPE is ootype.Void: continue # Print the value of the field: self._print_field_value(f_name, FIELD_TYPE) genprint(',') # Decrement indent and dump close genprint("))") class ConstantStringDumpMethod(BaseDumpMethod): """ Just prints out a string """ def __init__(self, clsobj, str): BaseDumpMethod.__init__(self, None, None, clsobj) self.constant_string = str def _render_guts(self, gen): genprint = self._print genprint("'" + self.constant_string + "'") class DeepEqualsMethod(object): def __init__(self, db, OOCLASS, clsobj): self.db = db self.OOCLASS = OOCLASS self.clsobj = clsobj self.name = "equals" self.jargtypes = [clsobj, jvmtype.jObject] self.jrettype = jvmtype.jBool def render(self, gen): self.gen = gen gen.begin_function( self.name, (), self.jargtypes, self.jrettype, static=False) # Label to branch to should the items prove to be unequal unequal_lbl = gen.unique_label('unequal') gen.add_comment('check that the argument is of the correct type') gen.load_jvm_var(self.clsobj, 1) gen.instanceof(self.OOCLASS) gen.goto_if_false(unequal_lbl) gen.add_comment('Cast it to the right type:') gen.load_jvm_var(self.clsobj, 1) gen.downcast(self.OOCLASS) gen.store_jvm_var(self.clsobj, 1) # If so, compare field by field for fieldnm, (FIELDOOTY, fielddef) in self.OOCLASS._fields.iteritems(): if FIELDOOTY is ootype.Void: continue fieldobj = self.clsobj.lookup_field(fieldnm) gen.add_comment('Compare field %s of type %s' % (fieldnm, FIELDOOTY)) # Load the field from both this and the argument: gen.load_jvm_var(self.clsobj, 0) gen.emit(fieldobj) gen.load_jvm_var(self.clsobj, 1) gen.emit(fieldobj) # And compare them: gen.compare_values(FIELDOOTY, unequal_lbl) # Return true or false as appropriate gen.push_primitive_constant(ootype.Bool, True) gen.return_val(jvmtype.jBool) gen.mark(unequal_lbl) gen.push_primitive_constant(ootype.Bool, False) gen.return_val(jvmtype.jBool) gen.end_function() class DeepHashMethod(object): def __init__(self, db, OOCLASS, clsobj): self.db = db self.OOCLASS = OOCLASS self.clsobj = clsobj self.name = "hashCode" self.jargtypes = [clsobj] self.jrettype = jvmtype.jInt def render(self, gen): self.gen = gen gen.begin_function( self.name, (), self.jargtypes, self.jrettype, static=False) # Initial hash: 0 gen.push_primitive_constant(ootype.Signed, 0) # Get hash of each field for fieldnm, (FIELDOOTY, fielddef) in self.OOCLASS._fields.iteritems(): if FIELDOOTY is ootype.Void: continue fieldobj = self.clsobj.lookup_field(fieldnm) gen.add_comment('Hash field %s of type %s' % (fieldnm, FIELDOOTY)) # Load the field and hash it: gen.load_jvm_var(self.clsobj, 0) gen.emit(fieldobj) gen.hash_value(FIELDOOTY) # XOR that with the main hash gen.emit(jvmgen.IXOR) # Return the final hash gen.return_val(jvmtype.jInt) gen.end_function()
[ "lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d" ]
lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d
72caef93226a4cb05201677c911b3789efdba9fd
d400c32010a414a2f536c5c0a3490c8b8e2e9d5a
/modules/m16e/ods_doc.py
75ba3b1fea0134d2c04d2e55576de59bd5e2f548
[ "LicenseRef-scancode-public-domain" ]
permissive
CarlosCorreiaM16e/chirico_cms
3e521eae8f38b732497a2b808950c6a534e69d4f
73897cbddb230630e13f22333b9094d0a047acb3
refs/heads/master
2020-12-30T07:59:04.100330
2020-05-02T12:26:58
2020-05-02T12:26:58
238,917,321
2
0
null
null
null
null
UTF-8
Python
false
false
1,946
py
# -*- coding: utf-8 -*- import sys import traceback from m16e.kommon import KDT_CHAR, KDT_INT, KDT_DEC, KDT_PERCENT from m16e.odslib import odslib #---------------------------------------------------------------------- class OdsDoc( object ): #---------------------------------------------------------------------- def __init__(self): self.doc = odslib.ODS() #---------------------------------------------------------------------- def set_cell( self, row, col, value, val_type=KDT_CHAR, row_span=1, col_span=1, font_size=None, font_bold=False, h_align=None, v_align=None ): # term.printDebug( 'row: %d, col: %d' % (row, col) ) for i in range( 6 ): try: cell = self.doc.content.getCell( col, row ) if val_type in (KDT_INT, KDT_DEC, KDT_PERCENT): cell.floatValue( value ) else: cell.stringValue( str( value ) ) if font_size: cell.setFontSize( "%dpt" % font_size ) if font_bold: cell.setBold( True ) if v_align: cell.setAlignVertical( v_align ) if h_align: cell.setAlignHorizontal( h_align ) if row_span > 1 or col_span > 1: self.doc.content.mergeCells( col, row, col_span, row_span ) # if completed successfuly break except: t, v, tb = sys.exc_info() traceback.print_exception( t, v, tb ) #---------------------------------------------------------------------- def save( self, filename ): self.doc.save( filename )
[ "carlos@memoriapersistente.pt" ]
carlos@memoriapersistente.pt
e703967804eb0f8cb2843481d277c85bc8c71b2e
a9fc496e0724866093dbb9cba70a8fdce12b67a9
/scripts/field/cygnus_Summon.py
3881deea825b33318e178ca09b9972f8f7486987
[ "MIT" ]
permissive
ryantpayton/Swordie
b2cd6b605f7f08f725f5e35d23ba3c22ef2ae7c0
ca6f42dd43f63b1d2e6bb5cdc8fc051c277f326e
refs/heads/master
2022-12-01T09:46:47.138072
2020-03-24T10:32:20
2020-03-24T10:32:20
253,997,319
2
0
MIT
2022-11-24T08:17:54
2020-04-08T05:50:22
Java
UTF-8
Python
false
false
153
py
if sm.getFieldID() == 271040100: sm.spawnMob(8850111, -147, 115, False) elif sm.getFieldID() == 211070102: sm.spawnMob(8850111, -147, 115, False)
[ "thijsenellen@outlook.com" ]
thijsenellen@outlook.com
6e7da8d8db94998e492bafe969437e9b40e5a8f4
4d0f3e2d7455f80caea978e4e70621d50c6c7561
/MongoDB/CRUD/QueryingByObjectId.py
efc3f90c9e14317b40ca16aed85eda0d2c3df484
[]
no_license
mhdr/PythonSamples
66940ee2353872d2947c459e3865be42140329c6
1a9dccc05962033ea02b081a39cd67c1e7b29d0c
refs/heads/master
2020-04-14T01:10:13.033940
2016-05-28T15:33:52
2016-05-28T15:33:52
30,691,539
1
0
null
null
null
null
UTF-8
Python
false
false
1,060
py
__author__ = 'mahmood' from pymongo import MongoClient client=MongoClient() # drop last db client.drop_database("test-db") # database db=client["test-db"] # table people=db["People"] new_person1={"FirstName" : "Mahmood", "LastName" : "Ramzani", "Gender": "Male", "BirthDate" : {"Year" : 1985 , "Month" : 5 , "Day" : 22}} new_person2={"FirstName" : "Javad", "LastName" : "Najafi", "Gender": "Male", "BirthDate" : {"Year" : 1984 , "Month" : 7 , "Day" : 13}} new_person3={"FirstName" : "Mahmood", "LastName" : "Rohani", "Gender": "Male", "BirthDate" : {"Year" : 1985 , "Month" : 8 , "Day" : 8}} id1= people.insert(new_person1) id2= people.insert(new_person2) id3= people.insert(new_person3) print(id1) print(id2) print(id3) match1=people.find_one({"_id":id2}) print(match1) # if id is string we need to convert # for example if id comes from web from bson.objectid import ObjectId match2=people.find_one({"_id":ObjectId(id3)}) print(match2)
[ "ramzani.mahmood@gmail.com" ]
ramzani.mahmood@gmail.com
dbf7640a313af2358461941e02b18b6d1e7c1709
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/time/high_work_and_long_life/group/case/good_child_and_case.py
fdb05e9779fa6e59a4688c46e5b2f2dee289fb94
[]
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
215
py
#! /usr/bin/env python def long_world(str_arg): group(str_arg) print('little_hand_and_week') def group(str_arg): print(str_arg) if __name__ == '__main__': long_world('high_person_and_big_child')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
e5fc5b2e2f076a3deb4a132618a1ce25e94c26cc
e204cdd8a38a247aeac3d07f6cce6822472bdcc5
/.history/app_test_django/views_20201116131730.py
f28ad5d7088723c0254f3cead00c09213ae31ad9
[]
no_license
steven-halla/python-test
388ad8386662ad5ce5c1a0976d9f054499dc741b
0b760a47d154078002c0272ed1204a94721c802a
refs/heads/master
2023-04-08T03:40:00.453977
2021-04-09T19:12:29
2021-04-09T19:12:29
354,122,365
0
0
null
null
null
null
UTF-8
Python
false
false
2,095
py
from django.shortcuts import render, redirect from .models import * from django.contrib import messages def index(request): return render(request, "index.html") def register_new_user(request): errors = User.objects.user_registration_validator(request.POST) if len(errors) > 0: for key, value in errors.items(): error_msg = key + ' - ' + value messages.error(request, error_msg) return redirect("/") else: first_name_from_post = request.POST['first_name'] last_name_from_post = request.POST['last_name'] email_from_post = request.POST['email'] password_from_post = request.POST['password'] new_user = User.objects.create( first_name=first_name_from_post, last_name=last_name_from_post, email=email_from_post, password=password_from_post ) print(new_user.id) request.session['user_id'] = new_user.id return redirect('/dashboard') def login(request): # user did provide email/password, now lets check database email_from_post = request.POST['email'] password_from_post = request.POST['password'] # this will return all users that have the email_from_post # in future we should require email to be unique users = User.objects.filter(email=email_from_post) if len(users) == 0: messages.error(request, "email/password does not exist") return redirect("/") user = users[0] print(user) if (user.password != password_from_post): messages.error(request, "email/password does not exist") return redirect("/") request.session['user_id'] = user.id return redirect("/dashboard") def logout(request): request.session.clear() return redirect("/") def view_dashboard(request): if 'user_id' not in request.session: return redirect("/") this_user = User.objects.get(id=request.session['user_id']) context = { "user":this_user } return render(request, "dash_board.html", context)
[ "69405488+steven-halla@users.noreply.github.com" ]
69405488+steven-halla@users.noreply.github.com
b2087e7207c8d5906a761f9b5d0333fdf5fa7128
20f89f49400feb9d2885dc2daf3ea3ca189556e7
/day09/proctice/05 粘包问题解决/mod_struct.py
08c0855ed616bb6cfc08acaaf5767a5483a48750
[]
no_license
xiaobaiskill/python
201511b1b1bddec8c33c4efa7ca2cc4afed24a89
540693baad757369ff811fb622a949c99fb6b4ba
refs/heads/master
2021-04-12T03:43:30.308110
2018-07-13T01:41:19
2018-07-13T01:41:19
125,884,001
0
0
null
null
null
null
UTF-8
Python
false
false
138
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author Jmz import struct total = 16374 res = struct.pack('i',total) print(len(res))
[ "1125378902@qq.com" ]
1125378902@qq.com
f16a18a60451d63b0c3e3ea9dfd47962690ed967
eb19175c18053e5d414b4f6442bdfd0f9f97e24d
/tests/starwars_django/test_connections.py
9992f0f3809a991f64dc9a760a689072066a1616
[ "MIT" ]
permissive
jhgg/graphene
6c4c5a64b7b0f39c8f6b32d17f62e1c31ca03825
67904e8329de3d69fec8c82ba8c3b4fe598afa8e
refs/heads/master
2020-12-25T21:23:22.556227
2015-10-15T19:56:40
2015-10-15T19:56:40
43,073,008
1
0
null
2015-09-24T14:47:19
2015-09-24T14:47:19
null
UTF-8
Python
false
false
987
py
import pytest from graphql.core import graphql from .models import * from .schema import schema from .data import initialize pytestmark = pytest.mark.django_db def test_correct_fetch_first_ship_rebels(): initialize() query = ''' query RebelsShipsQuery { rebels { name, hero { name } ships(first: 1) { edges { node { name } } } } } ''' expected = { 'rebels': { 'name': 'Alliance to Restore the Republic', 'hero': { 'name': 'Human' }, 'ships': { 'edges': [ { 'node': { 'name': 'X-Wing' } } ] } } } result = schema.execute(query) assert not result.errors assert result.data == expected
[ "me@syrusakbary.com" ]
me@syrusakbary.com
a5cfd192a6bdd36268a411986e5257ad3f206711
a2e638cd0c124254e67963bda62c21351881ee75
/Python modules/HP_2021_01_04_XTP_Trades.py
4313930c4f2639f99725c878fd6a2d0aae8b3bfc
[]
no_license
webclinic017/fa-absa-py3
1ffa98f2bd72d541166fdaac421d3c84147a4e01
5e7cc7de3495145501ca53deb9efee2233ab7e1c
refs/heads/main
2023-04-19T10:41:21.273030
2021-05-10T08:50:05
2021-05-10T08:50:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
878
py
import acm import csv with open( 'C:\\Temp\\1\\CA_Stock Input.csv', mode='r') as csv_file: readCSV = csv.DictReader(csv_file) print 'trade number', "|", 'instrument', "|", 'trade price', "|", 'Portfolio' for row in readCSV: trade=acm.FTrade() trade.Instrument(row['Instrument']) trade.Quantity(row['Quantity']) trade.Price(row['Price']) trade.Acquirer(row['Acquirer']) trade.Portfolio(row['Portfolio']) trade.Counterparty("JSE") trade.Status('Simulated') trade.Currency('ZAR') trade.TradeTime('2021-01-04') trade.ValueDay('2021-01-07') trade.Commit() premium=trade.Quantity() *-1*trade.Price()/100 trade.Premium(premium) trade.AcquireDay(trade.ValueDay()) trade.Commit() print trade.Name(), "|", trade.Instrument().Name(), "|", trade.Price(), "|", trade.Portfolio().Name()
[ "nencho.georogiev@absa.africa" ]
nencho.georogiev@absa.africa
5a8b2cdde3908ffa52271f85cdfd0d8883b5c8db
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/young_government/want_thing.py
fe79d6bc7b16f04663bb72a76609bd5cc5bbb80f
[]
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
206
py
#! /usr/bin/env python def group(str_arg): small_work(str_arg) print('old_work_and_young_company') def small_work(str_arg): print(str_arg) if __name__ == '__main__': group('have_thing')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
956ef7f9bbda19c259de876c23f18bfa189bc407
2b167e29ba07e9f577c20c54cb943861d0ccfa69
/numerical_analysis_backup/large-scale-multiobj2/core-arch4-guard2-beta0-hebbe/pareto0.py
0000998404917886a9c21b69d9c51c32cf41c0cc
[]
no_license
LiYan1988/kthOld_OFC
17aeeed21e195d1a9a3262ec2e67d6b1d3f9ff0f
b1237577ea68ad735a65981bf29584ebd889132b
refs/heads/master
2021-01-11T17:27:25.574431
2017-01-23T05:32:35
2017-01-23T05:32:35
79,773,237
0
0
null
null
null
null
UTF-8
Python
false
false
2,399
py
# -*- coding: utf-8 -*- """ Created on Thu Aug 4 15:15:10 2016 @author: li optimize both throughput and connections """ #import sys #sys.path.insert(0, '/home/li/Dropbox/KTH/numerical_analysis/ILPs') import csv from gurobipy import * import numpy as np from arch4_decomposition_new import Arch4_decompose np.random.seed(2010) num_cores=10 num_slots=320 i = 0 time_limit_routing = 3600 time_limit_sa = 10800 filename = 'traffic_matrix_pod250_load50_'+str(i)+'.csv' tm = [] with open(filename) as f: reader = csv.reader(f) for idx, row in enumerate(reader): row = [float(u) for u in row] tm.append(row) tm = np.array(tm) #%% arch2 corev = np.array([1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) #corev = np.array([1, 2]) connection_ub = [] throughput_ub = [] obj_ub = [] connection_lb = [] throughput_lb = [] obj_lb = [] connection_he = [] throughput_he = [] obj_he = [] for c in corev: m = Arch4_decompose(tm, num_slots=num_slots, num_cores=c, alpha=1,beta=0, num_guard_slot=2) m.create_model_routing(mipfocus=1,timelimit=7200,mipgap=0.01, method=2) connection_ub.append(m.connection_ub_) throughput_ub.append(m.throughput_ub_) obj_ub.append(m.obj_ub_) # m.create_model_sa(mipfocus=1,timelimit=10800,mipgap=0.01, method=2, # SubMIPNodes=2000, heuristics=0.8) # connection_lb.append(m.connection_lb_) # throughput_lb.append(m.throughput_lb_) # obj_lb.append(m.obj_lb_) # m.write_result_csv('cnklist_lb_%d_%d.csv'%(i,c), m.cnklist_lb) connection_lb.append(0) throughput_lb.append(0) obj_lb.append(0) m.heuristic() connection_he.append(m.obj_heuristic_connection_) throughput_he.append(m.obj_heuristic_throughput_) obj_he.append(m.obj_heuristic_) m.write_result_csv('cnklist_heuristic_arch4_i%d_c%d.csv'%(i,c), m.cnklist_heuristic_) result = np.array([corev, connection_ub,throughput_ub,obj_ub, connection_lb,throughput_lb,obj_lb, connection_he,throughput_he,obj_he]).T file_name = "result_pareto_arch4_old_pod100_i{}.csv".format(i) with open(file_name, 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(['#cores', 'connection_ub', 'throughput_ub', 'obj_ub', 'connection_lb', 'throughput_lb', 'obj_lb', 'connection_he', 'throughput_he', 'obj_he']) writer.writerows(result)
[ "li.yan.ly414@gmail.com" ]
li.yan.ly414@gmail.com
d29f5685c461da483a731f28490384ef6e074cab
a0cf59e79154d6062c2dccfb2ff8b61aa9681486
/10.py
9f90c64b92e30c225325d27221e01584d6676600
[]
no_license
PetraVidnerova/AdventOfCode
a211d77210ac1c43a9b2c0f546250f6d7c1d183c
5b0e8017fcd8f71576a312b6c7b5bd3602be6e89
refs/heads/master
2021-01-10T16:07:03.336632
2016-02-28T14:02:54
2016-02-28T14:02:54
52,216,197
0
0
null
2016-02-21T17:17:37
2016-02-21T16:39:51
null
UTF-8
Python
false
false
471
py
def read(input): # one iteration of read input = input + "x" # last char is ignored result = "" lastchar = None count = 0 for ch in input: if ch == lastchar: count += 1 continue if lastchar: result = result + str(count) + str(lastchar) count = 1 lastchar = ch return result input = "3113322113" for x in range(50): print(x) input = read(input) print(len(input))
[ "petra.vidnerova@gmail.com" ]
petra.vidnerova@gmail.com
ce468ff5a9ed3402454e645b2be13c4a473020ea
e10a6d844a286db26ef56469e31dc8488a8c6f0e
/gaternet/main.py
c4692b2cd0fdba89e13d15c53467b6b2f916be48
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
Jimmy-INL/google-research
54ad5551f97977f01297abddbfc8a99a7900b791
5573d9c5822f4e866b6692769963ae819cb3f10d
refs/heads/master
2023-04-07T19:43:54.483068
2023-03-24T16:27:28
2023-03-24T16:32:17
282,682,170
1
0
Apache-2.0
2020-07-26T15:50:32
2020-07-26T15:50:31
null
UTF-8
Python
false
false
5,362
py
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loads a GaterNet checkpoint and tests on Cifar-10 test set.""" import argparse import io import os from backbone_resnet import Network as Backbone from gater_resnet import Gater import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets from torchvision import transforms def load_from_state(state_dict, model): """Loads the state dict of a checkpoint into model.""" tem_dict = dict() for k in state_dict.keys(): tem_dict[k.replace('module.', '')] = state_dict[k] state_dict = tem_dict ckpt_key = set(state_dict.keys()) model_key = set(model.state_dict().keys()) print('Keys not in current model: {}\n'.format(ckpt_key - model_key)) print('Keys not in checkpoint: {}\n'.format(model_key - ckpt_key)) model.load_state_dict(state_dict, strict=True) print('Successfully reload from state.') return model def test(backbone, gater, device, test_loader): """Tests the model on a test set.""" backbone.eval() gater.eval() loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) gate = gater(data) output = backbone(data, gate) loss += F.cross_entropy(output, target, size_average=False).item() pred = output.max(1, keepdim=True)[1] correct += pred.eq(target.view_as(pred)).sum().item() loss /= len(test_loader.dataset) acy = 100. * correct / len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)\n'.format( loss, correct, len(test_loader.dataset), acy)) return acy def run(args, device, test_loader): """Loads checkpoint into GaterNet and runs test on the test data.""" with open(args.checkpoint_file, 'rb') as fin: inbuffer = io.BytesIO(fin.read()) state_dict = torch.load(inbuffer, map_location='cpu') print('Successfully load checkpoint file.\n') backbone = Backbone(depth=args.backbone_depth, num_classes=10) print('Loading checkpoint weights into backbone.') backbone = load_from_state(state_dict['backbone_state_dict'], backbone) backbone = nn.DataParallel(backbone).to(device) print('Backbone is ready after loading checkpoint and moving to device:') print(backbone) n_params_b = sum( [param.view(-1).size()[0] for param in backbone.parameters()]) print('Number of parameters in backbone: {}\n'.format(n_params_b)) gater = Gater(depth=20, bottleneck_size=8, gate_size=backbone.module.gate_size) print('Loading checkpoint weights into gater.') gater = load_from_state(state_dict['gater_state_dict'], gater) gater = nn.DataParallel(gater).to(device) print('Gater is ready after loading checkpoint and moving to device:') print(gater) n_params_g = sum( [param.view(-1).size()[0] for param in gater.parameters()]) print('Number of parameters in gater: {}'.format(n_params_g)) print('Total number of parameters: {}\n'.format(n_params_b + n_params_g)) print('Running test on test data.') test(backbone, gater, device, test_loader) def parse_flags(): """Parses input arguments.""" parser = argparse.ArgumentParser(description='GaterNet') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--backbone-depth', type=int, default=20, help='resnet depth of the backbone subnetwork') parser.add_argument('--checkpoint-file', type=str, default=None, help='checkpoint file to run test') parser.add_argument('--data-dir', type=str, default=None, help='the directory for storing data') args = parser.parse_args() return args def main(args): print('Input arguments:\n{}\n'.format(args)) use_cuda = not args.no_cuda and torch.cuda.is_available() print('use_cuda: {}'.format(use_cuda)) device = torch.device('cuda' if use_cuda else 'cpu') torch.backends.cudnn.benchmark = True print('device: {}'.format(device)) if not os.path.isdir(args.data_dir): os.mkdir(args.data_dir) kwargs = {'num_workers': 8, 'pin_memory': True} if use_cuda else {} normalize_mean = [0.4914, 0.4822, 0.4465] normalize_std = [0.2470, 0.2435, 0.2616] test_loader = torch.utils.data.DataLoader( datasets.CIFAR10( args.data_dir, train=False, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize(normalize_mean, normalize_std)]) ), batch_size=1000, shuffle=False, drop_last=False, **kwargs) print('Successfully get data loader.') run(args, device, test_loader) if __name__ == '__main__': main(parse_flags())
[ "copybara-worker@google.com" ]
copybara-worker@google.com
d3e688e2e0724426f98735db7408e549f3245eda
717f7d68e5f36c1d30d223cb201407b0f9c11f9c
/statistical data analysis/02_variance_measure.py
dc22125bd55674bad964315424d4951b43a8ed47
[]
no_license
raunakshakya/PythonPractice
7f54508f9adb8541a9cedc7a58e3629bcfb9b6f5
3643e9f526401d31ca706f036af0cdae3da04984
refs/heads/master
2020-03-22T18:01:54.357735
2019-06-05T03:32:07
2019-06-05T03:32:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,160
py
# https://www.tutorialspoint.com/python/python_measuring_variance.htm """ Variance is a measure of how far a value in a data set lies from the mean value. In other words, it indicates how dispersed the values are. It is measured by using standard deviation. The other method commonly used is skewness. """ import pandas as pd # Create a Dictionary of series d = {'Name': pd.Series(['Tom', 'James', 'Ricky', 'Vin', 'Steve', 'Smith', 'Jack', 'Lee', 'Chanchal', 'Gasper', 'Naviya', 'Andres']), 'Age': pd.Series([25, 26, 25, 23, 30, 25, 23, 34, 40, 30, 25, 46]), 'Rating': pd.Series([4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65])} # Create a DataFrame df = pd.DataFrame(d) """ Standard deviation is square root of variance. """ # Calculate the standard deviation print(df.std()) print() """ Skewness is used to determine whether the data is symmetric or skewed. If the index is between -1 and 1, then the distribution is symmetric. If the index is no more than -1 then it is skewed to the left and if it is at least 1, then it is skewed to the right. """ # Calculate the skewness print(df.skew())
[ "rkshakya99@gmail.com" ]
rkshakya99@gmail.com
d6271117a9193e0facb6f43251e36bccbc847ba1
9bb01fa882e713aa59345051fec07f4e3d3478b0
/tests/cysparse_/sparse/common_attributes/test_common_attributes_matrices_likes_ConjugatedSparseMatrix_INT32_t_FLOAT32_t.py
17904df851dbc456f945b9e24ed309bc76956c00
[]
no_license
syarra/cysparse
f1169c496b54d61761fdecbde716328fd0fb131b
7654f7267ab139d0564d3aa3b21c75b364bcfe72
refs/heads/master
2020-05-25T16:15:38.160443
2017-03-14T21:17:39
2017-03-14T21:17:39
84,944,993
0
0
null
2017-03-14T12:11:48
2017-03-14T12:11:48
null
UTF-8
Python
false
false
7,395
py
#!/usr/bin/env python """ This file tests basic common attributes for **all** matrix like objects. Proxies are only tested for a :class:`LLSparseMatrix` object. See file ``sparse_matrix_coherence_test_functions``. """ from sparse_matrix_like_common_attributes import common_matrix_like_attributes import unittest from cysparse.sparse.ll_mat import * from cysparse.common_types.cysparse_types import * ######################################################################################################################## # Tests ######################################################################################################################## ################################## # Case Non Symmetric, Non Zero ################################## class CySparseCommonAttributesMatrices_ConjugatedSparseMatrix_INT32_t_FLOAT32_t_TestCase(unittest.TestCase): def setUp(self): self.nrow = 10 self.ncol = 14 self.nnz = self.nrow * self.ncol self.A = LinearFillLLSparseMatrix(nrow=self.nrow, ncol=self.ncol, dtype=FLOAT32_T, itype=INT32_T) self.C = self.A.conj self.nargin = self.ncol self.nargout = self.nrow self.base_type_str = self.A.base_type_str def test_common_attributes(self): is_OK, attribute = common_matrix_like_attributes(self.C) self.assertTrue(is_OK, msg="Attribute '%s' is missing" % attribute) def test_nrow_attribute(self): self.assertTrue(self.C.nrow == self.nrow) def test_ncol_attribute(self): self.assertTrue(self.C.ncol == self.ncol) def test_nnz_attribute(self): self.assertTrue(self.C.nnz == self.nnz) def test_symmetric_storage_attribute(self): self.assertTrue(not self.C.store_symmetric) def test_zero_storage_attribute(self): self.assertTrue(not self.C.store_zero) def test_is_mutable_attribute(self): self.assertTrue(self.C.is_mutable) def test_base_type_str(self): self.assertTrue(self.C.base_type_str == self.base_type_str, "'%s' is not '%s'" % (self.C.base_type_str, self.base_type_str)) def test_is_symmetric(self): self.assertTrue(not self.C.is_symmetric) def test_nargin(self): self.assertTrue(self.nargin == self.C.nargin) def test_nargout(self): self.assertTrue(self.nargout == self.C.nargout) ################################## # Case Symmetric, Non Zero ################################## class CySparseCommonAttributesSymmetricMatrices_ConjugatedSparseMatrix_INT32_t_FLOAT32_t_TestCase(unittest.TestCase): def setUp(self): self.size = 14 self.nnz = ((self.size + 1) * self.size) / 2 self.nargin = self.size self.nargout = self.size self.A = LinearFillLLSparseMatrix(size=self.size, dtype=FLOAT32_T, itype=INT32_T, store_symmetric=True) self.C = self.A.conj self.base_type_str = self.A.base_type_str def test_common_attributes(self): is_OK, attribute = common_matrix_like_attributes(self.C) self.assertTrue(is_OK, msg="Attribute '%s' is missing" % attribute) def test_nrow_attribute(self): self.assertTrue(self.C.nrow == self.size) def test_ncol_attribute(self): self.assertTrue(self.C.ncol == self.size) def test_nnz_attribute(self): self.assertTrue(self.C.nnz == self.nnz, '%d is not %d' % (self.C.nnz, self.nnz)) def test_symmetric_storage_attribute(self): self.assertTrue(self.C.store_symmetric) def test_zero_storage_attribute(self): self.assertTrue(not self.C.store_zero) def test_is_mutable_attribute(self): self.assertTrue(self.C.is_mutable) def test_base_type_str(self): self.assertTrue(self.C.base_type_str == self.base_type_str) def test_is_symmetric(self): self.assertTrue(self.C.is_symmetric) def test_nargin(self): self.assertTrue(self.nargin == self.C.nargin) def test_nargout(self): self.assertTrue(self.nargout == self.C.nargout) ################################## # Case Non Symmetric, Zero ################################## class CySparseCommonAttributesWithZeroMatrices_ConjugatedSparseMatrix_INT32_t_FLOAT32_t_TestCase(unittest.TestCase): def setUp(self): self.nrow = 10 self.ncol = 14 self.nnz = self.nrow * self.ncol self.A = LinearFillLLSparseMatrix(nrow=self.nrow, ncol=self.ncol, dtype=FLOAT32_T, itype=INT32_T, store_zero=True) self.C = self.A.conj self.nargin = self.ncol self.nargout = self.nrow self.base_type_str = self.A.base_type_str def test_common_attributes(self): is_OK, attribute = common_matrix_like_attributes(self.C) self.assertTrue(is_OK, msg="Attribute '%s' is missing" % attribute) def test_nrow_attribute(self): self.assertTrue(self.C.nrow == self.nrow) def test_ncol_attribute(self): self.assertTrue(self.C.ncol == self.ncol) def test_nnz_attribute(self): self.assertTrue(self.C.nnz == self.nnz) def test_symmetric_storage_attribute(self): self.assertTrue(not self.C.store_symmetric) def test_zero_storage_attribute(self): self.assertTrue(self.C.store_zero) def test_is_mutable_attribute(self): self.assertTrue(self.C.is_mutable) def test_base_type_str(self): self.assertTrue(self.C.base_type_str == self.base_type_str) def test_is_symmetric(self): self.assertTrue(not self.C.is_symmetric) def test_nargin(self): self.assertTrue(self.nargin == self.C.nargin) def test_nargout(self): self.assertTrue(self.nargout == self.C.nargout) ################################## # Case Symmetric, Zero ################################## class CySparseCommonAttributesSymmetricWithZeroMatrices_ConjugatedSparseMatrix_INT32_t_FLOAT32_t_TestCase(unittest.TestCase): def setUp(self): self.size = 14 self.nnz = ((self.size + 1) * self.size) / 2 self.A = LinearFillLLSparseMatrix(size=self.size, dtype=FLOAT32_T, itype=INT32_T, store_symmetric=True, store_zero=True) self.nargin = self.size self.nargout = self.size self.C = self.A.conj self.base_type_str = self.A.base_type_str def test_common_attributes(self): is_OK, attribute = common_matrix_like_attributes(self.C) self.assertTrue(is_OK, msg="Attribute '%s' is missing" % attribute) def test_nrow_attribute(self): self.assertTrue(self.C.nrow == self.size) def test_ncol_attribute(self): self.assertTrue(self.C.ncol == self.size) def test_nnz_attribute(self): self.assertTrue(self.C.nnz, self.nnz) def test_symmetric_storage_attribute(self): self.assertTrue(self.C.store_symmetric) def test_zero_storage_attribute(self): self.assertTrue(self.C.store_zero) def test_is_mutable_attribute(self): self.assertTrue(self.C.is_mutable) def test_base_type_str(self): self.assertTrue(self.C.base_type_str == self.base_type_str) def test_is_symmetric(self): self.assertTrue(self.C.is_symmetric) def test_nargin(self): self.assertTrue(self.nargin == self.C.nargin) def test_nargout(self): self.assertTrue(self.nargout == self.C.nargout) if __name__ == '__main__': unittest.main()
[ "sylvain.arreckx@gmail.com" ]
sylvain.arreckx@gmail.com
8e5530438c97d0e7a5e092c7bb90b4885627ccac
bb150497a05203a718fb3630941231be9e3b6a32
/framework/e2e/jit/test_Conv1DTranspose_7.py
38603397c5765f6c7bc79e052c30df74cd538a9e
[]
no_license
PaddlePaddle/PaddleTest
4fb3dec677f0f13f7f1003fd30df748bf0b5940d
bd3790ce72a2a26611b5eda3901651b5a809348f
refs/heads/develop
2023-09-06T04:23:39.181903
2023-09-04T11:17:50
2023-09-04T11:17:50
383,138,186
42
312
null
2023-09-13T11:13:35
2021-07-05T12:44:59
Python
UTF-8
Python
false
false
635
py
#!/bin/env python # -*- coding: utf-8 -*- # encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python """ test jit cases """ import os import sys sys.path.append(os.path.abspath(os.path.dirname(os.getcwd()))) sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), "utils")) from utils.yaml_loader import YamlLoader from jittrans import JitTrans yaml_path = os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), "yaml", "nn.yml") yml = YamlLoader(yaml_path) def test_Conv1DTranspose_7(): """test Conv1DTranspose_7""" jit_case = JitTrans(case=yml.get_case_info("Conv1DTranspose_7")) jit_case.jit_run()
[ "825276847@qq.com" ]
825276847@qq.com
8761eaff518d705e57ceb09085af5d4088e080fb
71047c4c45e97f474b45e0989202d8d88b0e4895
/sparse_dot/sparse_dot.py
3e82d3d8e3094bf5d04af57799a660e9c4e6e47a
[ "Apache-2.0" ]
permissive
pluralsight/sparse_dot
bd86e676e323ef84f51b2b5ae7b453ba7fa66916
271131a3a28f12d7dcca0fbeca8591e9d052c98a
refs/heads/master
2023-04-01T06:03:51.845211
2016-12-13T19:33:30
2016-12-13T19:33:30
72,578,014
3
1
Apache-2.0
2023-03-27T18:25:07
2016-11-01T21:24:52
Python
UTF-8
Python
false
false
2,459
py
'''The main script''' # To update with any Cython changes, just run: # python setup.py build_ext --inplace import numpy as np import cy_sparse_dot def to_saf(arr1d): arr1d = np.asanyarray(arr1d) locs = np.nonzero(arr1d) return {'locs': locs[0].astype(np.uint32), 'array': arr1d[locs].astype(np.float32)} def to_saf_list(arr2d): return map(to_saf, arr2d) def validate_saf(saf, verbose=True): '''True if the locs (indices) in a saf are ordered AND the data types of the arrays are uint32 and float32 respectively''' def vpr(x): if verbose: print x if not ('locs' in saf and 'array' in saf): vpr('missing members') return False if not (hasattr(saf['locs'], 'dtype') and hasattr(saf['array'], 'dtype')): vpr('members not arrays') return False if not (saf['locs'].dtype == np.uint32 and saf['array'].dtype == np.float32): vpr('bad dtype') return False if not np.all(saf['locs'][1:] > saf['locs'][:-1]): vpr('locs not ordered') return False return True def sparse_dot_full(saf_list, validate=True, verbose=True): '''Takes a list of arrays in locs/array dict form and ''' if validate: assert all(validate_saf(saf, verbose=verbose) for saf in saf_list) return cy_sparse_dot.cy_sparse_dot_full(saf_list) def dot_full_using_sparse(arr): '''Takes a 2d array and runs dot products against every combination of rows''' return sparse_dot_full(to_saf_list(arr), validate=False) def sparse_cos_similarity(saf_list, validate=True, verbose=True): norms = np.array([np.linalg.norm(saf['array']) for saf in saf_list]) dots = sparse_dot_full(saf_list, validate=validate, verbose=verbose) norm_i, norm_j = norms[(dots['i'],)], norms[(dots['j'],)] dots['sparse_result'] /= norm_i * norm_j return dots def sparse_cos_distance(saf_list, validate=True, verbose=True): dots = sparse_cos_similarity(saf_list, validate=validate, verbose=verbose) dots['sparse_result'] *= -1 dots['sparse_result'] += 1 return dots def cos_similarity_using_sparse(arr): return sparse_cos_similarity(to_saf_list(arr)) def cos_distance_using_sparse(arr): return sparse_cos_distance(to_saf_list(arr)) if __name__ == '__main__': r = dot_full_using_sparse([[1, 0, 0, 1, 3, 1], [2, 0, 0, 0, 1, 5]]) print r
[ "david.n.mashburn@gmail.com" ]
david.n.mashburn@gmail.com
9a8cac4b3e32f6a077d7eb78d0f5051c0512f4a2
936dc2666f27de7a7d1428c7ad2ded62a722b8fa
/src/aids/migrations/0176_alter_aid_subvention_comment.py
9b1d57c10296955b4148ac4b92dc72f523a577cb
[ "ISC" ]
permissive
MTES-MCT/aides-territoires
03451a32bdeaab3812b8593bfe3a27c1b1d9a182
af9f6e6e8b1918363793fbf291f3518ef1454169
refs/heads/master
2023-09-04T22:15:17.819264
2023-08-25T13:19:17
2023-08-25T13:19:17
124,301,398
21
11
NOASSERTION
2023-09-12T13:46:49
2018-03-07T22:19:11
Python
UTF-8
Python
false
false
553
py
# Generated by Django 4.1.7 on 2023-04-25 12:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("aids", "0175_aid_ds_id_aid_ds_mapping_aid_ds_schema_exists"), ] operations = [ migrations.AlterField( model_name="aid", name="subvention_comment", field=models.CharField( blank=True, max_length=255, verbose_name="Taux de subvention (commentaire optionnel)", ), ), ]
[ "noreply@github.com" ]
MTES-MCT.noreply@github.com
54ca12d67db93ad73a903f15cd006cccfdefb7b9
38b8bceafb4d80afc7c77196eb9ee99694191bcf
/scrapy/study/w3school/w3school/pipelines.py
f7b1b2c843306a1645d8a3cfe490cb83fe27c0f5
[]
no_license
tangc1986/PythonStudy
f6c5b384874e82fbf0b5f51cfb7a7a89a48ec0ff
1ed1956758e971647426e7096ac2e8cbcca585b4
refs/heads/master
2021-01-23T20:39:23.930754
2017-10-08T07:40:32
2017-10-08T07:42:38
42,122,267
0
0
null
null
null
null
UTF-8
Python
false
false
542
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import codecs class W3SchoolPipeline(object): def __init__(self): self.file = codecs.open('w3school_data_utf8.json', 'wb', encoding='utf-8') def process_item(self, item, spider): line = json.dumps(dict(item)) + '\n' # print line self.file.write(line.decode("unicode_escape")) return item
[ "tangc1986@gmail.com" ]
tangc1986@gmail.com
bc84b1d032b1997b9821ff3ddf33c6d2c324154e
a6f9b3b1503fc08e7d77161bb2b5beac3b89480d
/app/main/views.py
d9d53ba612eb73e52f381e20e54f8542edc6833b
[]
no_license
AugustineOchieng/newsFeed
e779d7e4cf91c6769947cb5e140d417001ecf7c2
b08720540c31453f895f395524177edb489add97
refs/heads/master
2020-05-09T14:53:23.346539
2019-04-16T10:04:09
2019-04-16T10:04:09
181,212,503
0
0
null
null
null
null
UTF-8
Python
false
false
1,064
py
from flask import render_template,request,redirect,url_for from . import main from flask import render_template,request,redirect,url_for from ..request import get_source,article_source,get_category,get_headlines #our views @main.route('/') def index(): ''' Root function returning index/home page with data ''' source= get_source() headlines = get_headlines() return render_template('index.html',sources=source, headlines = headlines) @main.route('/article/<id>') def article(id): ''' View article page function that returns the various article details page and its data ''' # title= 'Articles' articles = article_source(id) return render_template('article.html',articles= articles,id=id ) @main.route('/categories/<cat_name>') def category(cat_name): ''' function to return the categories.html page and its content ''' category = get_category(cat_name) title = f'{cat_name}' cat = cat_name return render_template('categories.html',title = title,category = category, cat= cat_name)
[ "gusochieng@gmail.com" ]
gusochieng@gmail.com
ec7f623c696363ec82e593a0d6aac0e53ec677b5
26d450ba94d06ce9ff2ced9e41c2daf6ea011118
/demo/demo3.py
49f164c4895737804908e1e03a4f0aff2eb7e256
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
Correct-Syntax/ui-style-lang
d0a9ac478dc9c7572d0d663b48eea0c07dd48705
5c6dc9f1cd50de35c5745082dd02dc572f794ccc
refs/heads/master
2023-04-28T20:01:03.866809
2021-05-14T14:38:49
2021-05-14T14:38:49
267,696,517
12
0
null
null
null
null
UTF-8
Python
false
false
3,331
py
# Demo for UI Style Lang # ====================== # This demo file (demo3.py) is MIT licensed - (C) 2020 Noah Rahm, Correct Syntax # Usage: # It's a custom button...click it! # This demo is up-to-date import wx from uistylelang import UIStylePDC, UIStyleApp, UIStyleFrame class MainApplication(UIStyleFrame): def __init__(self): UIStyleFrame.__init__(self, None, title="UI Style Lang Demo", pos=(0, 0), size=(1000, 800), name="main-frame") # Create the DC self._pdc = UIStylePDC( self, './custom-widget-demo.uiss' ) self.DrawDrawing(self._pdc) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.Bind(wx.EVT_MOTION, self.OnMotion) def OnPaint(self, event): dc = wx.BufferedPaintDC(self) dc = wx.GCDC(dc) # We need to clear the dc BEFORE calling PrepareDC. dc.Clear() # Draw to the dc using the calculated clipping rect. self._pdc.DrawToDCClipped( dc, wx.Rect(0, 0, self.Size[0], self.Size[1]) ) def OnMotion(self, event): pnt = event.GetPosition() elem_rect = self._pdc.GetWxRect('button') mouse_pnt = wx.Rect(pnt[0], pnt[1], 1, 1) if mouse_pnt.Intersects(elem_rect) == True: self._pdc.UpdateElem('button:hover') else: self._pdc.UpdateElem('button') self.RefreshDemo() def OnLeftDown(self, event): pnt = event.GetPosition() elem_rect = self._pdc.GetWxRect('button') # Create a 1x1 rect for the mouse pointer mouse_pnt = wx.Rect(pnt[0], pnt[1], 1, 1) if mouse_pnt.Intersects(elem_rect) == True: self._pdc.UpdateElem('button:press') self._pdc.UpdateElem('button-text:hover') self.RefreshDemo() def OnLeftUp(self, event): pnt = event.GetPosition() elem_rect = self._pdc.GetWxRect('button') # Create a 1x1 rect for the mouse pointer mouse_pnt = wx.Rect(pnt[0], pnt[1], 1, 1) if mouse_pnt.Intersects(elem_rect) == True: self._pdc.UpdateElem('button') self._pdc.UpdateElem('button-text') self.ButtonCallback() self.RefreshDemo() def DrawDrawing(self, dc): # Initial dc.InitElem('button') dc.InitElem('button-text', "TEXT", "UI Style Lang Demo") dc.InitElem('text', "TEXT", "UI Style Lang Demo") def RefreshDemo(self): rect = wx.Rect(0, 0, self.Size[0], self.Size[1]) self.RefreshRect(rect, False) self.Refresh() def ButtonCallback(self): notify = wx.adv.NotificationMessage( title="Button Clicked", message="You clicked the UI Style Lang custom button", parent=None, flags=wx.ICON_INFORMATION) notify.Show(timeout=2) # 1 for short timeout, 100 for long timeout if __name__ == '__main__': # Create the app and startup app = UIStyleApp(file='./custom-widget-demo.uiss', redirect=False) frame = MainApplication() frame.Show() app.SetTopWindow(frame) app.MainLoop()
[ "correctsyntax@yahoo.com" ]
correctsyntax@yahoo.com