hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
68b74c13aa2276f42386e385f34a0bbb9009ebfe
210
py
Python
trampolino/__init__.py
matteomancini/trampolino
af904844404f97c49e0452527b01fd9f415677ba
[ "MIT" ]
3
2020-06-17T09:25:22.000Z
2021-06-22T23:16:53.000Z
trampolino/__init__.py
matteomancini/trampolino
af904844404f97c49e0452527b01fd9f415677ba
[ "MIT" ]
1
2020-06-26T08:47:01.000Z
2020-07-21T14:02:40.000Z
trampolino/__init__.py
matteomancini/trampolino
af904844404f97c49e0452527b01fd9f415677ba
[ "MIT" ]
3
2020-06-16T11:55:50.000Z
2020-11-25T01:37:17.000Z
# -*- coding: utf-8 -*- """Top-level package for Tractography Meta-Pipeline Command Line Tool (TRAMPOLINO).""" __author__ = """Matteo Mancini""" __email__ = 'ingmatteomancini@gmail.com' __version__ = '0.1.9'
26.25
86
0.7
25
210
5.4
1
0
0
0
0
0
0
0
0
0
0
0.021739
0.12381
210
7
87
30
0.711957
0.490476
0
0
0
0
0.445545
0.257426
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
68bd351718db1fa4aa791850b81f6102d0eaa5af
242
py
Python
welut_demo/app/admin.py
agusmakmun/welut
ee176b51d4637691a616a17eb0491c933211799a
[ "MIT" ]
6
2017-11-17T10:34:27.000Z
2022-01-06T14:17:23.000Z
welut_demo/app/admin.py
agusmakmun/welut
ee176b51d4637691a616a17eb0491c933211799a
[ "MIT" ]
2
2017-12-06T14:40:31.000Z
2020-08-15T10:41:11.000Z
welut_demo/app/admin.py
agusmakmun/welut
ee176b51d4637691a616a17eb0491c933211799a
[ "MIT" ]
7
2017-11-13T20:47:05.000Z
2020-06-04T03:20:13.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from app.models import EBook class EbookAdmin(admin.ModelAdmin): raw_id_fields = ['ebook_file'] admin.site.register(EBook, EbookAdmin)
17.285714
39
0.756198
32
242
5.46875
0.71875
0
0
0
0
0
0
0
0
0
0
0.004808
0.140496
242
13
40
18.615385
0.836538
0.086777
0
0
0
0
0.045662
0
0
0
0
0
0
1
0
false
0
0.5
0
0.833333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
68bdc4c0b6f174517fe0db4eaa6dd654aa09ddfc
209
py
Python
dm2bn/__init__.py
DCOD-OpenSource/django-messages-to-bootstrap-notify
8d9f60dc1111961984bc33f1ec0efc3265c5c7a8
[ "MIT" ]
11
2017-05-16T15:22:13.000Z
2019-02-13T21:43:13.000Z
dm2bn/__init__.py
DCOD-OpenSource/django-messages-to-bootstrap-notify
8d9f60dc1111961984bc33f1ec0efc3265c5c7a8
[ "MIT" ]
null
null
null
dm2bn/__init__.py
DCOD-OpenSource/django-messages-to-bootstrap-notify
8d9f60dc1111961984bc33f1ec0efc3265c5c7a8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # django-messages-to-bootstrap-notify # dm2bn/__init__.py from __future__ import unicode_literals __all__ = [ "default_app_config", ] default_app_config = "dm2bn.apps.Config"
13.933333
40
0.717703
26
209
5.115385
0.807692
0.150376
0.240602
0
0
0
0
0
0
0
0
0.016854
0.148325
209
14
41
14.928571
0.730337
0.358852
0
0
0
0
0.269231
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0
1
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
68d66d2618332f95369f465a3be1e10a223c535f
1,556
py
Python
ProjectApplication/project_core/filters.py
code-review-doctor/project-application
d85b40b69572efbcda24ce9c40803f76d8ffd192
[ "MIT" ]
null
null
null
ProjectApplication/project_core/filters.py
code-review-doctor/project-application
d85b40b69572efbcda24ce9c40803f76d8ffd192
[ "MIT" ]
null
null
null
ProjectApplication/project_core/filters.py
code-review-doctor/project-application
d85b40b69572efbcda24ce9c40803f76d8ffd192
[ "MIT" ]
null
null
null
from functools import reduce from operator import or_ from django.db.models import Q from django_filters.rest_framework import CharFilter, FilterSet from project_core.models import Project class ProjectFilterSet(FilterSet): key_any = CharFilter(method='filter_any', label="Key, Title, Keyword, PI, Lay summary or Organisation") geographical_areas = CharFilter(method='filter_geographical_areas') funding_instrument = CharFilter(method='filter_funding_instrument') start_date = CharFilter(method='filter_start_date') def filter_any(self, queryset, name, value): fields = [ "key", "title", "keywords__name", "principal_investigator__person__first_name", "principal_investigator__person__surname", "laysummary__text", "principal_investigator__organisation_names__name" ] q_field = reduce(or_, (Q(**{f"{field}__icontains": word}) for word in value.split() for field in fields)) return queryset.filter(q_field).distinct() def filter_geographical_areas(self, queryset, name, value): return queryset.filter(geographical_areas__name=value) def filter_funding_instrument(self, queryset, name, value): return queryset.filter(funding_instrument__long_name=value) def filter_start_date(self, queryset, name, value): return queryset.filter(start_date__year__lte=value, end_date__year__gte=value) class Meta: model = Project fields = ('key_any', 'geographical_areas', 'funding_instrument', 'start_date')
39.897436
113
0.732648
184
1,556
5.820652
0.36413
0.05042
0.082166
0.078431
0.114846
0.114846
0.114846
0
0
0
0
0
0.17545
1,556
38
114
40.947368
0.834762
0
0
0
0
0
0.235861
0.115039
0
0
0
0
0
1
0.142857
false
0
0.178571
0.107143
0.678571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
68dceef9e17ce3214519730ed94a8ee6e47a04f0
2,335
py
Python
quote_bot/settings.py
civsocit/quote-bot
88d8161e93a8b855f984931c412f70bac12f2286
[ "MIT" ]
1
2021-09-27T05:11:37.000Z
2021-09-27T05:11:37.000Z
quote_bot/settings.py
civsocit/quote-bot
88d8161e93a8b855f984931c412f70bac12f2286
[ "MIT" ]
null
null
null
quote_bot/settings.py
civsocit/quote-bot
88d8161e93a8b855f984931c412f70bac12f2286
[ "MIT" ]
null
null
null
import os from os.path import abspath, dirname, join from typing import Tuple from dotenv import load_dotenv load_dotenv() class BotSettings: @classmethod def token(cls) -> str: token = os.getenv("TOKEN") if not token: raise ValueError("Token must be specified (missing .env file or TOKEN environment variable?)") return token @classmethod def access_chat_id(cls) -> int: chat = os.getenv("CHAT") if not chat: raise ValueError("Access chat ID must be specified (missing .env file or CHAT environment variable?)") return int(chat) @classmethod def access_cache_ttl(cls) -> int: return 60 # in seconds @classmethod def dynamo_region(cls) -> str: return "us-east-1" class DesignerSettings: @classmethod def path_to_font(cls) -> str: return join(abspath(dirname(__file__)), "designer", "Montserrat-SemiBold.ttf") @classmethod def path_to_caption_font(cls) -> str: return join(abspath(dirname(__file__)), "designer", "Montserrat-ExtraBold.ttf") @classmethod def caption_fixed_font_size(cls) -> int: return 65 @classmethod def text_color_light(cls) -> Tuple[int, int, int]: return 0xE1, 0xE6, 0xEB @classmethod def text_color_dark(cls) -> Tuple[int, int, int]: return 0x19, 0x2D, 0x44 @classmethod def background_color_dark(cls) -> Tuple[int, int, int]: return 0x00, 0x00, 0x00 @classmethod def background_color_light(cls) -> Tuple[int, int, int]: return 0xE1, 0xE6, 0xEB @classmethod def text_position(cls) -> Tuple[float, float, float, float]: # Relative position x0, y0, x1, y1 return 0.09375, 0.25555, 0.90625, 0.66666 @classmethod def caption_text_position(cls) -> Tuple[float, float, float, float]: return 0.5 / 16, 0.4 / 9, 6 / 16, 1 / 9 @classmethod def default_width(cls) -> int: # A3 size 16.54 inh with 200 DPI # Warning: Pillow uses discrete scale factor, so, 150 or 170 DPI may be equal return int(16.54 * 200.0) @classmethod def default_preview_width(cls) -> int: # A7 size 4.13 inh with 150 DPI return 620 @classmethod def max_font_size(cls) -> int: return 150
27.151163
114
0.634261
310
2,335
4.651613
0.36129
0.15534
0.030513
0.038835
0.332871
0.305132
0.305132
0.262136
0.165049
0.165049
0
0.062354
0.265096
2,335
85
115
27.470588
0.777972
0.077088
0
0.295082
0
0
0.110284
0.021871
0
0
0.022336
0
0
1
0.262295
false
0
0.065574
0.229508
0.622951
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
68e1a458c31e0c524390fe908d2955573ee29cfe
78,246
py
Python
cfdi/cfdi/doctype/cfdi/cfdi.py
dacosta2213/cfdi
d383940cb1b333207fce9c2e70d55907dd441ca1
[ "MIT" ]
null
null
null
cfdi/cfdi/doctype/cfdi/cfdi.py
dacosta2213/cfdi
d383940cb1b333207fce9c2e70d55907dd441ca1
[ "MIT" ]
null
null
null
cfdi/cfdi/doctype/cfdi/cfdi.py
dacosta2213/cfdi
d383940cb1b333207fce9c2e70d55907dd441ca1
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2015, C0D1G0 B1NAR10 and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.file_manager import save_url from frappe.model.mapper import get_mapped_doc from frappe.utils import cint, flt import shutil import os import sys import time import base64 from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import threading from xml.dom import minidom import requests from datetime import datetime import collections import random import string from datetime import date from datetime import * import re class CFDI(Document): pass @frappe.whitelist() def ticket(source_name, target_doc=None): doclist = get_mapped_doc("Sales Invoice", source_name, { "Sales Invoice": { "doctype": "CFDI", "field_map": { "name": "ticket", } }, "Sales Invoice Item": { "doctype": "CFDI Item", "field_map": { "rate": "precio_de_venta", "net_rate": "precio_unitario_neto", "amount": "monto", "parent": "fuente", "net_amount": "precio_neto", # "impuesto": "tax", } } }, target_doc) return doclist # RG - Inicia SmarterWEb @frappe.whitelist() def validar_rfc(url, token, rfc): headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("GET", url + "/lrfc/" + rfc, headers=headers) frappe.errprint(response.text) return response.text @frappe.whitelist() def cancel_by_uuid(url, token,docname, rfc, uuid): # frappe.errprint(rfc) c = frappe.get_doc("CFDI", docname) headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("POST", url + "/cfdi33/cancel/" + rfc + "/" + uuid, headers=headers) if response.json().get('status') == 'error': frappe.msgprint((response.json().get('message')), "ERROR ENCONTRADO AL TIMBRAR") else: for d in c.items: frappe.db.set_value("Sales Invoice",d.fuente , 'cfdi_status', 'Sin Timbrar') return response.text @frappe.whitelist() def cancel_by_uuid_pago(docname): c = frappe.get_doc("Payment Entry", docname) uuid = c.uuid_pago d = frappe.get_doc("Configuracion CFDI", c.company) url = 'http://' + d.url token = d.token rfc = d.rfc_emisor headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("POST", url + "/cfdi33/cancel/" + rfc + "/" + uuid, headers=headers) if response.json().get('status') == 'error': frappe.msgprint((response.json().get('message')), "ERROR ENCONTRADO AL TIMBRAR") else: frappe.db.set_value("Payment Entry",c.name, 'cfdi_status', 'Cancelado') frappe.msgprint(str(c.name) + " Cancelada exitosamente " ) return response.text @frappe.whitelist() def cancel_by_uuid_egreso(url, token,docname, rfc, uuid): c = frappe.get_doc("CFDI Nota de Credito", docname) headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("POST", url + "/cfdi33/cancel/" + rfc + "/" + uuid, headers=headers) if response.json().get('status') == 'error': frappe.msgprint((response.json().get('message')), "ERROR ENCONTRADO AL CANCELAR") else: frappe.db.set_value("CFDI Nota de Credito",c.name, 'cfdi_status', 'Cancelado') frappe.msgprint(str(c.name) + " Cancelada exitosamente " ) return response.text # RG - Timbrado de CFDI @frappe.whitelist() def issue(url, token, docname, version, b64=False): # RG - POST request al server de swarterweb xml = genera_xml(docname) boundary = "----=_Part_11_11939969.1490230712432" #RG- declararlo como en issue_pago payload = "--" + boundary + "\r\nContent-Type: text/xml\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: " \ "form-data; name=\"xml\"; filename=\"xml\"\r\n\r\n" + str(xml) + "\r\n--" + boundary + "-- " headers = { 'Authorization': "bearer " + token, 'Content-Type': "multipart/form-data; boundary=\"" + boundary + "\"" } response = requests.request("POST", url + "/cfdi33/issue/" + version + "/" , data=payload.encode('utf-8'), headers=headers) liga = url + "/cfdi33/issue/" + version + "/" frappe.errprint(response.json()) #RG - para ver la respuesta en la consola frappe.errprint(payload) frappe.errprint(headers) frappe.errprint(liga) if response.json().get('status') == 'error': #RG - Ver si podemos manejar con una funcion separada el error if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: # RG- Recuperar el response y manejar la info pa grabar los archivos/datos en el CFDI c = frappe.get_doc("CFDI", docname) fechaxml = str(c.creation) # webfolder = c.folder uuid = response.json().get('data').get('uuid') # generar xml cfdi_recibido = response.json().get('data').get('cfdi') dest = '/home/frappe/frappe-bench/sites/' + frappe.local.site + '/public/files/' + c.name + "_" + fechaxml[0:10] f = open( dest + '.xml',"w+") f.write(cfdi_recibido) f.close() save_url( "/files/" + '/public/files/' + c.name + "_" + fechaxml[0:10] + ".xml" , c.name + "_" + fechaxml[0:10] + ".xml" , "CFDI" , c.name , "Home/Attachments" , 0) # EscribirPNG qr = response.json().get('data').get('qrCode') png = open( dest + ".png", "wb") png.write(base64.b64decode(qr)) png.close() frappe.db.set_value("CFDI",c.name, 'qr', "/files/" + c.name + "_" + fechaxml[0:10] + ".png") # escribir todos los demas campos frappe.db.set_value("CFDI",c.name, 'cfdi_status', 'Timbrado') for d in c.items: frappe.db.set_value("Sales Invoice", d.fuente , 'cfdi_status', 'Timbrado') frappe.db.set_value("CFDI",c.name, 'SelloCFD', response.json().get('data').get('selloCFDI')) frappe.db.set_value("CFDI",c.name, 'cadenaOriginalSAT', response.json().get('data').get('cadenaOriginalSAT')) frappe.db.set_value("CFDI",c.name, 'FechaTimbrado', response.json().get('data').get('fechaTimbrado') ) frappe.db.set_value("CFDI",c.name, 'uuid', uuid) frappe.db.set_value("CFDI",c.name, 'NoCertificadoSAT', response.json().get('data').get('noCertificadoSAT') ) frappe.db.set_value("CFDI",c.name, 'SelloSAT', response.json().get('data').get('selloSAT') ) # frappe.msgprint(str(c.name) + " Timbrada exitosamente " ) mensaje = str(c.name)+" TIMBRADO EXITOSO . <a class= 'alert-info' href='https://" + frappe.local.site + "/files/" + c.name + "_" + fechaxml[0:10] + ".xml' download> Descarga XML </a>" frappe.msgprint(mensaje) return response.json() def genera_xml(docname): tieneiva = 0 notieneiva = 0 c = frappe.get_doc("CFDI", docname) cant = len(c.items) mytime = datetime.strptime('0800','%H%M').time() #fecha_actual = datetime.combine(c.posting_date,mytime).isoformat()[0:19] #dacosta - para hacer que se timbre con la fecha de posting_date fecha_actual = (datetime.now()- timedelta(minutes=480)).isoformat()[0:19] # fecha_actual = (datetime.now()- timedelta(minutes=360)).isoformat()[0:19] # fecha_obj = datetime.strptime(c.creation, "%Y-%m-%d %H:%M:%S.%f") # fecha_actual = fecha_obj.isoformat()[0:19] serie = c.naming_series.replace('-','') folio = c.name.replace(serie,'') FormaPago = c.forma_de_pago SubTotal = 0 # Falta descuento Total = '%.2f' % c.total TipoDeComprobante = c.tipo_de_comprobante MetodoPago = c.metodo_pago LugarExpedicion = c.lugar_expedicion NoCertificado = c.no_certificado rfc_emisor = c.rfc_emisor nombre_emisor = c.nombre_emisor regimen_fiscal = c.regimen_fiscal tax_id = c.tax_id.replace('&','&amp;') # nombre_receptor = c.customer_name.encode('ascii', 'ignore').decode('ascii') # nombre_receptor = c.customer_name.encode('UTF-8', 'ignore') # nombre_receptor = c.customer_name.decode('UTF-8') nombre_receptor = c.customer_name.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ñ','N').replace('ñ','n').replace('Ü', 'U') tipo = [] tasa = [] cantidad = [] cfdi_items = "" cfdi_traslados = "" for d in c.items: NoIdentificacion = d.item_code.replace('"','') ClaveProdServ = d.clave_producto ClaveUnidad = d.clave_unidad Cantidad = d.qty Unidad = d.stock_uom ValorUnitario = '%.2f' % d.precio_unitario_neto Importe = '%.2f' % d.precio_neto idx = d.idx Descripcion = d.item_name SubTotal = round(SubTotal + float(d.precio_neto), 2) if d.tipo_de_impuesto == "IVA": TrasladosBase = '%.2f' % d.precio_neto Impuesto = "002" TasaOCuota = .01 * float(d.tax) ImpuestosTrasladosTasaOCuota='%.6f' % TasaOCuota Importetax = '%.2f' % (TasaOCuota * float(d.precio_neto)) tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) elif d.tipo_de_impuesto == "IEPS": TrasladosBase = '%.2f' % d.precio_neto Impuesto="003" TasaOCuota = .01 * float(d.tax) ImpuestosTrasladosTasaOCuota='%.6f' % TasaOCuota Importetax = '%.2f' % (TasaOCuota * float(d.precio_neto)) tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) else: notieneiva = 1 TrasladosBase= '%.2f' % d.precio_neto Impuesto="002" TasaOCuota="0.000000" Importetax= "0.00" cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="0.00"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="Tasa" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) uso_cfdi = c.uso_cfdi cTipo = collections.Counter(tipo) cTasa = collections.Counter(tasa) total_impuesto = 0 TotalImpuestosTrasladados = 0.0 for w, val1 in cTipo.items(): for y, val2 in cTasa.items(): suma = 0.0 for z in range(0,cant): if (tasa[z] == y) and (tipo[z] == w): suma = suma+float(cantidad[z]) b = y t = w total_impuesto = total_impuesto + suma TotalImpuestosTrasladados = round(suma,2) # total_impuesto = '%.2f' % total_impuesto1 if(suma>0): cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="Tasa" TasaOCuota="{b}" Importe="{TotalImpuestosTrasladados}"/>""".format(**locals()) else: cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="Tasa" TasaOCuota="{b}" Importe="{suma}"/>""".format(**locals()) Total = round(SubTotal + TotalImpuestosTrasladados, 2) cfdi = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" FormaPago="{FormaPago}" NoCertificado="" Certificado="" CondicionesDePago="CONTADO" SubTotal="{SubTotal}" Descuento="0.00" Moneda="MXN" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" MetodoPago="{MetodoPago}" LugarExpedicion="{LugarExpedicion}"> <cfdi:Emisor Rfc="{rfc_emisor}" Nombre="{nombre_emisor}" RegimenFiscal="{regimen_fiscal}"/> <cfdi:Receptor Rfc="{tax_id}" Nombre="{nombre_receptor}" UsoCFDI="{uso_cfdi}"/> <cfdi:Conceptos>""".format(**locals()) cfdi += cfdi_items cfdi_conceptos = """ </cfdi:Conceptos> <cfdi:Impuestos TotalImpuestosTrasladados="{TotalImpuestosTrasladados}"> <cfdi:Traslados> """.format(**locals()) cfdi += cfdi_conceptos cfdi += cfdi_traslados cfdi += """ </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Comprobante> """.format(**locals()) frappe.errprint(cfdi) return cfdi # RG- Para los complementos de pago (REP) @frappe.whitelist() def issue_pago(url, token, docname, version,user_id,user_password,folder,nombre_emisor,no_certificado, b64=False): # RG - POST request al server de swarterweb xml = genera_xml_pago(docname,url,user_id,user_password,folder,nombre_emisor,no_certificado) frappe.errprint(xml) # boundary = "----=_Part_11_11939969.1490230712432" lst = [random.choice(string.ascii_letters + string.digits) for n in range(30)] boundary = "".join(lst) payload = "--" + boundary + "\r\nContent-Type: text/xml\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: form-data; name=\"xml\"; filename=\"xml\"\r\n\r\n" + str(xml) + "\r\n--" + boundary + "-- " headers = { 'Authorization': "bearer " + token, 'Content-Type': "multipart/form-data; boundary=\"" + boundary + "\"" } response = requests.request("POST", url + "/cfdi33/issue/" + version + "/" , data=payload.encode('utf-8'), headers=headers, timeout=300) liga = url + "/cfdi33/issue/" + version + "/" if response.json().get('status') == 'error': if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: c = frappe.get_doc("Payment Entry", docname) # webfolder = c.folder uuid = response.json().get('data').get('uuid') fechaxml = str(c.creation) # generar xml cfdi_recibido = response.json().get('data').get('cfdi') dest = '/home/frappe/frappe-bench/sites/' + frappe.local.site + '/public/files/' + c.name + "_" + fechaxml[0:10] f = open( dest + '.xml',"w+") f.write(cfdi_recibido) f.close() save_url( "/files/" + c.name + "_" + fechaxml[0:10] + ".xml" , c.name + "_" + fechaxml[0:10] + ".xml" , "Payment Entry" , c.name , "Home/Attachments" , 0) # EscribirPNG qr = response.json().get('data').get('qrCode') png = open( dest + ".png", "wb") png.write(base64.b64decode(qr)) png.close() frappe.db.set_value("Payment Entry",c.name, 'qr', "/files/" + c.name + "_" + fechaxml[0:10] + ".png") # escribir todos los demas campos frappe.db.set_value("Payment Entry",c.name, 'cfdi_status', 'Timbrado') frappe.db.set_value("Payment Entry",c.name, 'SelloCFD', response.json().get('data').get('selloCFDI')) frappe.db.set_value("Payment Entry",c.name, 'cadenaOriginalSAT', response.json().get('data').get('cadenaOriginalSAT')) frappe.db.set_value("Payment Entry",c.name, 'FechaTimbrado', response.json().get('data').get('fechaTimbrado') ) frappe.db.set_value("Payment Entry",c.name, 'uuid_pago', uuid) frappe.db.set_value("Payment Entry",c.name, 'NoCertificadoSAT', response.json().get('data').get('noCertificadoSAT') ) frappe.db.set_value("Payment Entry",c.name, 'SelloSAT', response.json().get('data').get('selloSAT') ) frappe.msgprint(str(c.name) + " Timbrada exitosamente " ) return response.json() def genera_xml_pago(docname, url,user_id,user_password,folder,nombre_emisor,no_certificado): Fecha = (datetime.now()- timedelta(minutes=480)).isoformat()[0:19] c = frappe.get_doc("Payment Entry", docname) cliente = frappe.get_doc("Customer", c.party_name) # if frappe.local.site == "demo.totall.mx": Fecha = c.fecha.isoformat()[0:19] if c.fecha else (datetime.now()- timedelta(minutes=480)).isoformat()[0:19] #si = frappe.get_doc(tipo, invoice) #SerieCFDI = si.naming_series #FolioCFDI = si.name url_timbrado = url user_id = user_id user_password = user_password webfolder =folder RegimenFiscal = c.regimen_fiscal if c.es_factoraje == 1: b = frappe.get_doc("Bank", c.banco) RfcReceptor = b.tax_id.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ü', 'U') else: RfcReceptor = cliente.tax_id.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ü', 'U') #########+++++++++++++++++SE COMENTARON LOS .replace DE LAS LINEAS 382 Y 214 if c.es_factoraje == 1: NombreReceptor = c.banco else: NombreReceptor = c.party_name.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ü', 'U') LugarExpedicion = c.lugar_expedicion mytime = datetime.strptime('1200','%H%M').time() FechaContabilizacion = datetime.combine(c.posting_date,mytime).isoformat()[0:19] Serie = c.naming_series.replace('-','') Folio = c.name.replace(Serie,'') rfc_emisor = c.rfc_emisor nombre_emisor = nombre_emisor NoCertificado = no_certificado FormaDePagoP = c.forma_de_pago Monto = '%.2f' % c.received_amount IdDocumento = c.documento_relacionado # Currency = c.paid_from_account_currency #TipoCambio = 1 if c.currency == "MXN" else '%2f' % c.source_enchange_rate MetodoDePagoDR = c.metodo_pago_cfdi NumOperacion = c.reference_no # ImpSaldoAnt = '%.2f' % c.references[0].outstanding_amount ImpSaldoAnt = '%.2f' % c.impsaldoanterior # ImpSaldoInsoluto = '%.2f' % (c.references[0].outstanding_amount - c.received_amount ) ImpSaldoInsoluto = '%.2f' % (c.impsaldoanterior - c.received_amount ) cfdi_pago= """<?xml version="1.0" encoding="utf-8" ?> <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:pago10="http://www.sat.gob.mx/Pagos" xsi:schemaLocation=" http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/Pagos http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd" Version="3.3" Serie="{Serie}" Folio="{Folio}" Fecha="{Fecha}" Sello="" NoCertificado="{NoCertificado}" Certificado="" SubTotal="0" Moneda="XXX" Total="0" TipoDeComprobante="P" LugarExpedicion="{LugarExpedicion}"> <cfdi:Emisor Rfc="{rfc_emisor}" Nombre="{nombre_emisor}" RegimenFiscal="{RegimenFiscal}"/> <cfdi:Receptor Rfc="{RfcReceptor}" Nombre="{NombreReceptor}" UsoCFDI="P01"/> <cfdi:Conceptos> <cfdi:Concepto ClaveProdServ="84111506" Cantidad="1" ClaveUnidad="ACT" Descripcion="Pago" ValorUnitario="0" Importe="0"> </cfdi:Concepto> </cfdi:Conceptos> <cfdi:Complemento> <pago10:Pagos Version="1.0">""".format(**locals()) # MonedaP= c.moneda TipoCambioP = c.target_exchange_rate MonedaP = c.paid_to_account_currency if MonedaP != 'MXN': # Si el Pago es diferente a MXN cfdi_pago+=""" <pago10:Pago FechaPago="{FechaContabilizacion}" FormaDePagoP="{FormaDePagoP}" TipoCambioP ="{TipoCambioP}" MonedaP="{MonedaP}" Monto="{Monto}" NumOperacion="{NumOperacion}">""".format(**locals()) else: cfdi_pago+=""" <pago10:Pago FechaPago="{FechaContabilizacion}" FormaDePagoP="{FormaDePagoP}" MonedaP="MXN" Monto="{Monto}" NumOperacion="{NumOperacion}">""".format(**locals()) for x in c.references: si = frappe.get_doc('Sales Invoice', x.reference_name) MonedaDR = si.currency # if MonedaDR != MonedaP: # frappe.throw('Las moneda del documento original es diferente a la moneda de pago. Documento Original: ' + str(si.name)) TipoCambioDR = None if si.currency == "MXN" else ('%2f' % si.conversion_rate) # TipoCambioDR = None IdDocumento = x.uuid SerieCFDI = si.naming_series FolioCFDI = si.name.replace(SerieCFDI,'') MetodoPago = si.metodo_pago ImpSaldoAnt = '%.2f' % x.monto_pendiente ImpPagado = '%.2f' % x.pagado parc = 0 frappe.errprint(x.reference_name) parcialidades = frappe.db.sql("""SELECT * from `tabPayment Entry Reference` WHERE reference_name = %s AND docstatus = 1""",(x.reference_name),as_dict=1) for conteo in parcialidades: parc += 1 ImpSaldoInsoluto= '%.2f' % (float(ImpSaldoAnt) - float(ImpPagado)) frappe.db.set_value("Sales Invoice",si.name, 'monto_pendiente', ImpSaldoInsoluto) frappe.errprint(IdDocumento) cfdi_pago+=""" <pago10:DoctoRelacionado IdDocumento="{IdDocumento}" Serie="{SerieCFDI}" Folio="{FolioCFDI}" """.format(**locals()) #if frappe.local.site == "demo.totall.mx": # Remover if y bloque else completo una ves comprovado el correcto funcionamiento del if - AG - 18/01/21 if TipoCambioDR: #Solo si Factura diferente a MXN #frappe.msgprint('En transacciones de moneda extranjera, solo puede existir 1 factura relacionada en Referencias del Pago (Payment Reference) ') ImpSaldoAnt = '%.2f' % ( flt(x.outstanding_amount) / flt(TipoCambioDR) ) if si.monto_pendiente > 1: ImpSaldoAnt = '%.2f' % ( si.monto_pendiente ) # ImpPagado = '%.2f' % flt(Monto) # ImpSaldoInsoluto= '%.2f' % (float(ImpSaldoAnt) - float(ImpPagado)) if MonedaP == MonedaDR:# Si Moneda de Pago igual a Moneda de Factura - Factura y Pago USD ImpSaldoAnt = '%.2f' % (x.monto_pendiente) ImpPagado = '%.2f' % (flt(x.pagado) / flt(c.tipo_cambio)) ImpSaldoInsoluto = '%.2f' % (float(ImpSaldoAnt) - float(ImpPagado)) frappe.errprint("Saldo Anterior: " + ImpSaldoAnt + "Pago: " + ImpPagado + "Saldo Nuevo: " + ImpSaldoInsoluto) if float(ImpSaldoInsoluto) < 0 and float(ImpPagado) > float(ImpSaldoAnt): ImpSaldoInsoluto = '%.2f' % 0 ImpPagado = '%.2f' % flt(ImpSaldoAnt) frappe.errprint("Saldo Anterior: " + ImpSaldoAnt + "Pago: " + ImpPagado + "Saldo Nuevo: " + ImpSaldoInsoluto) frappe.db.set_value("Sales Invoice",si.name, 'monto_pendiente', ImpSaldoInsoluto) cfdi_pago+="""MonedaDR="{MonedaDR}" MetodoDePagoDR="{MetodoPago}" NumParcialidad="{parc}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> """.format(**locals()) else: #Si la Moneda de Pago es Diferente a la Moneda de Factura - Factura USD - Pago MXN tipocambio = round(c.tipo_cambio, 4) ImpPagado = round(x.pagado / tipocambio, 2) ImpSaldoAnt = '%.2f' % (x.monto_pendiente) ImpSaldoInsoluto = '%.2f' % (float(ImpSaldoAnt) - float(ImpPagado)) if float(ImpSaldoInsoluto) < 0 and float(ImpPagado) > float(ImpSaldoAnt): ImpSaldoInsoluto = '%.2f' % 0 ImpPagado = '%.2f' % flt(ImpSaldoAnt) frappe.errprint("Saldo Anterior: " + ImpSaldoAnt + "Pago: " + ImpPagado + "Saldo Nuevo: " + ImpSaldoInsoluto) frappe.db.set_value("Sales Invoice",si.name, 'monto_pendiente', ImpSaldoInsoluto) cfdi_pago+="""TipoCambioDR="{tipocambio}" MonedaDR="{MonedaDR}" MetodoDePagoDR="{MetodoPago}" NumParcialidad="{parc}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> """.format(**locals()) else: # Si la Factura es en MXN if MonedaP != "MXN": #Si el Pago es Diferente de MXN cfdi_pago+="""TipoCambioDR="{TipoCambioP}" MonedaDR="{MonedaDR}" MetodoDePagoDR="{MetodoPago}" NumParcialidad="{parc}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> """.format(**locals()) else: cfdi_pago+="""MonedaDR="{MonedaDR}" MetodoDePagoDR="{MetodoPago}" NumParcialidad="{parc}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> """.format(**locals()) # else: # if TipoCambioDR: # ImpSaldoAnt = '%.2f' % x.total_moneda_original # ImpPagado = '%.2f' % x.total_moneda_original # ImpSaldoInsoluto= '%.2f' % (float(ImpSaldoAnt) - float(ImpPagado)) # cfdi_pago+="""MonedaDR="{MonedaDR}" MetodoDePagoDR="PPD" NumParcialidad="{no_parcialidad}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> # """.format(**locals()) # else: # cfdi_pago+="""MonedaDR="{MonedaDR}" MetodoDePagoDR="PPD" NumParcialidad="{no_parcialidad}" ImpSaldoAnt="{ImpSaldoAnt}" ImpPagado="{ImpPagado}" ImpSaldoInsoluto="{ImpSaldoInsoluto}"/> # """.format(**locals()) if c.es_factoraje == 1: pagado_imp = round(c.total_allocated_amount -c.base_received_amount, 2) parc = parc + 1 cfdi_pago+="""</pago10:Pago> <pago10:Pago Monto="{pagado_imp}" MonedaP="{MonedaP}" FormaDePagoP="17" FechaPago="{FechaContabilizacion}"> <pago10:DoctoRelacionado Serie="{SerieCFDI}" Folio="{FolioCFDI}" NumParcialidad="{parc}" MonedaDR="{MonedaP}" MetodoDePagoDR="PUE" ImpSaldoInsoluto="0.00" ImpSaldoAnt="{pagado_imp}" ImpPagado="{pagado_imp}" IdDocumento="{IdDocumento}"/> """.format(**locals()) cfdi_pago+="""</pago10:Pago> </pago10:Pagos> </cfdi:Complemento> </cfdi:Comprobante>""".format(**locals()) return cfdi_pago @frappe.whitelist() def parcialidades_pe(doc,method=None): # if frappe.local.site == "demo.totall.mx": for item in doc.references: parc = 1 # Obtiene todos los Pagos del Sinv en la lina actual parcialidades = frappe.get_list('Payment Entry Reference', filters={'reference_name':item.reference_name}, fields=['parent']) for parcialidad in parcialidades: pe_rel = frappe.get_doc('Payment Entry',parcialidad.parent) if pe_rel.fecha: pago = frappe.db.get_value('Payment Entry',{'name':parcialidad.parent,'fecha':['<',doc.fecha],'docstatus':['=',1]},'posting_date') else: pago = frappe.db.get_value('Payment Entry',{'name':parcialidad.parent,'creation':['<',doc.creation],'docstatus':['=',1]},'posting_date') if pago: parc = parc + 1 item.no_parcialidad = parc return # MAPA DE complementos # Num_Operacion = c.name # FormaDePago = c.forma_de_pago # # PAGO10 - Iterar sobre reference # id documento=uuid_pago # serie y folio = reference_name # met pago = 'PPD' # ImpSaldoAnt=total_moneda_original # ImpPagado=alocated_amount # ImpSaldoInsoluto=ImpSaldoAnt - ImpPagado # RG-Para las notas de credito CFDI @frappe.whitelist() def issue_egreso(url, token, docname, version, b64=False): # RG - POST request al server de swarterweb xml = genera_xml_egreso(docname) boundary = "----=_Part_11_11939969.1490230712432" payload = "--" + boundary + "\r\nContent-Type: text/xml\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: " \ "form-data; name=\"xml\"; filename=\"xml\"\r\n\r\n" + str(xml) + "\r\n--" + boundary + "-- " headers = { 'Authorization': "bearer " + token, 'Content-Type': "multipart/form-data; boundary=\"" + boundary + "\"" } response = requests.request("POST", url + "/cfdi33/issue/" + version + "/" , data=payload.encode('utf-8'), headers=headers) liga = url + "/cfdi33/issue/" + version + "/" frappe.errprint(response.json()) frappe.errprint(payload) frappe.errprint(headers) frappe.errprint(liga) if response.json().get('status') == 'error': frappe.msgprint((response.json().get('message')), "ERROR ENCONTRADO AL TIMBRAR") else: # RG- Recuperar el response y manejar la info pa grabar los archivos/datos en el CFDI c = frappe.get_doc("CFDI Nota de Credito", docname) # webfolder = c.folder uuid = response.json().get('data').get('uuid') fechaxml = str(c.creation) # generar xml cfdi_recibido = response.json().get('data').get('cfdi') dest = '/home/frappe/frappe-bench/sites/' + frappe.local.site + '/public/files/' + c.name + "_" + fechaxml[0:10] f = open( dest + '.xml',"w+") f.write(cfdi_recibido) f.close() save_url( "/files/" + c.name + "_" + fechaxml[0:10] + ".xml" , c.name + "_" + fechaxml[0:10] + ".xml" , "CFDI Nota de Credito" , c.name , "Home/Attachments" , 0) # EscribirPNG qr = response.json().get('data').get('qrCode') png = open( dest + ".png", "wb") png.write(base64.b64decode(qr)) png.close() frappe.db.set_value("CFDI Nota de Credito",c.name, 'qr', "/files/" + c.name + "_" + fechaxml[0:10] + ".png") # escribir todos los demas campos frappe.db.set_value("CFDI Nota de Credito",c.name, 'cfdi_status', 'Timbrado') frappe.db.set_value("CFDI Nota de Credito",c.name, 'sellocfd', response.json().get('data').get('selloCFDI')) frappe.db.set_value("CFDI Nota de Credito",c.name, 'cadenaoriginalsat', response.json().get('data').get('cadenaOriginalSAT')) frappe.db.set_value("CFDI Nota de Credito",c.name, 'fechatimbrado', response.json().get('data').get('fechaTimbrado') ) frappe.db.set_value("CFDI Nota de Credito",c.name, 'uuid', uuid) frappe.db.set_value("CFDI Nota de Credito",c.name, 'nocertificadosat', response.json().get('data').get('noCertificadoSAT') ) frappe.db.set_value("CFDI Nota de Credito",c.name, 'sellosat', response.json().get('data').get('selloSAT') ) frappe.msgprint(str(c.name) + " Timbrada exitosamente " ) return response.json() def genera_xml_egreso(docname): tieneiva = 0 notieneiva = 0 c = frappe.get_doc("CFDI Nota de Credito", docname) mytime = datetime.strptime('0800','%H%M').time() #fecha_actual = datetime.combine(c.posting_date,mytime).isoformat()[0:19] #dacosta - para hacer que se timbre con la fecha de posting_date mytime = datetime.strptime('0800','%H%M').time() fecha_actual = datetime.combine(c.posting_date,mytime).isoformat()[0:19] #dacosta - para hacer que se timbre con la fecha de posting_date serie = c.naming_series.replace('-','') folio = c.name.replace(serie,'') FormaPago = c.forma_de_pago SubTotal = float(c.total_neto) # Falta descuento Total = '%.2f' % (c.total) TipoDeComprobante = "E" MetodoPago = c.metodo_pago LugarExpedicion = c.lugar_expedicion NoCertificado = c.no_certificado rfc_emisor = c.rfc_emisor nombre_emisor = c.nombre_emisor.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') regimen_fiscal = c.regimen_fiscal tax_id = c.tax_id.replace('&','&amp;') nombre_receptor = c.customer_name.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') uso_cfdi = c.uso_cfdi # fac_rel = frappe.get_doc(c.tipo_documento,c.factura_fuente) tipo_rel = c.tipo_de_relacion # uuid_rel = fac_rel.uuid Currency = c.currency if Currency == 'MXN': TipoCambio = 1 else: TipoCambio = '%.4f' % float(c.conversion_rate) cfdi = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" FormaPago="{FormaPago}" NoCertificado="" Certificado="" CondicionesDePago="CONTADO" SubTotal="{SubTotal}" Moneda="{Currency}" TipoCambio = "{TipoCambio}" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" MetodoPago="{MetodoPago}" LugarExpedicion="{LugarExpedicion}">""".format(**locals()) site = frappe.local.site # if site == "demo.totall.mx": cfdi+= """ <cfdi:CfdiRelacionados TipoRelacion="{tipo_rel}">""".format(**locals()) for d in c.si_sustitucion: cfdi+=""" <cfdi:CfdiRelacionado UUID="{d.uuid}"/>""".format(**locals()) cfdi+=""" </cfdi:CfdiRelacionados>""".format(**locals()) cfdi+=""" <cfdi:Emisor Rfc="{rfc_emisor}" Nombre="{nombre_emisor}" RegimenFiscal="{regimen_fiscal}"/> <cfdi:Receptor Rfc="{tax_id}" Nombre="{nombre_receptor}" UsoCFDI="{uso_cfdi}"/> <cfdi:Conceptos>""".format(**locals()) for d in c.items: NoIdentificacion = d.item_code ClaveProdServ = d.clave_producto ClaveUnidad = d.clave_unidad Cantidad = d.qty Unidad = d.stock_uom ValorUnitario = '%.2f' % d.precio_unitario_neto Importe = '%.2f' % d.precio_neto idx =d.idx Descripcion = d.item_name if d.tax == 16: tieneiva = 1 TrasladosBase = '%.2f' % d.precio_neto Impuesto = "002" TasaOCuota = "0.160000" Importetax = '%.2f' % d.impuestos_totales else: notieneiva = 1 TrasladosBase= '%.2f' % d.precio_neto Impuesto="002" TasaOCuota="0.000000" Importetax= "0.00" cfdi += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="Tasa" TasaOCuota="{TasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) TotalImpuestosTrasladados='%.2f' % c.total_impuestos TotalIva = '%.2f' % c.total_iva frappe.errprint(TotalIva) TotalIeps = '%.2f' % c.total_ieps cfdi += """ </cfdi:Conceptos> <cfdi:Impuestos TotalImpuestosTrasladados="{TotalImpuestosTrasladados}"> <cfdi:Traslados> """.format(**locals()) if notieneiva == 1: cfdi += """ <cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.000000" Importe="0.00"/>""".format(**locals()) else: cfdi += """ <cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="{TotalIva}"/>""".format(**locals()) cfdi += """ </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Comprobante> """.format(**locals()) frappe.errprint(cfdi) return cfdi # Dev-Aaron Timbrado Sales Invoice @frappe.whitelist() def sales_invoice_timbrado(url, token, docname, version, b64=False): # RG - POST request al server de swarterweb xml = sales_invoice_timbrado_xml(docname) frappe.errprint(xml) lst = [random.choice(string.ascii_letters + string.digits) for n in range(30)] boundary = "".join(lst) payload = "--" + boundary + "\r\nContent-Type: text/xml\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: " \ "form-data; name=\"xml\"; filename=\"xml\"\r\n\r\n" + str(xml) + "\r\n--" + boundary + "-- " headers = { 'Authorization': "bearer " + token, 'Content-Type': "multipart/form-data; boundary=\"" + boundary + "\"" } response = requests.request("POST", url + "/cfdi33/issue/" + version + "/" , data=payload.encode('utf-8'), headers=headers) liga = url + "/cfdi33/issue/" + version + "/" frappe.errprint(response.json()) if response.json().get('status') == 'error': if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: # RG- Recuperar el response y manejar la info pa grabar los archivos/datos en el CFDI c = frappe.get_doc("Sales Invoice", docname) uuid = response.json().get('data').get('uuid') cfdi_recibido = response.json().get('data').get('cfdi') fechaxml = str(c.creation) dest = '/home/frappe/frappe-bench/sites/' + frappe.local.site + '/public/files/' + c.name + "_" + fechaxml[0:10] f = open( dest + '.xml',"w+") f.write(cfdi_recibido) f.close() save_url( "/files/" + c.name + "_" + fechaxml[0:10] + ".xml" , c.name + "_" + fechaxml[0:10] + ".xml" , "Sales Invoice" , c.name , "Home/Attachments" , 0) qr = response.json().get('data').get('qrCode') png = open( dest + ".png", "wb") png.write(base64.b64decode(qr)) png.close() frappe.db.set_value("Sales Invoice",c.name, 'qr', "/files/" + c.name + "_" + fechaxml[0:10] + ".png") frappe.db.set_value("Sales Invoice",c.name, 'cfdi_status', 'Timbrado') frappe.db.set_value("Sales Invoice",c.name, 'sellocfd', response.json().get('data').get('selloCFDI')) frappe.db.set_value("Sales Invoice",c.name, 'cadenaoriginalsat', response.json().get('data').get('cadenaOriginalSAT')) frappe.db.set_value("Sales Invoice",c.name, 'fechatimbrado', response.json().get('data').get('fechaTimbrado') ) frappe.db.set_value("Sales Invoice",c.name, 'uuid', uuid) frappe.db.set_value("Sales Invoice",c.name, 'nocertificadosat', response.json().get('data').get('noCertificadoSAT') ) frappe.db.set_value("Sales Invoice",c.name, 'sellosat', response.json().get('data').get('selloSAT') ) mensaje = "TIMBRADO EXITOSO . <a class= 'alert-info' href='https://" + frappe.local.site + "/files/" + c.name + "_" + fechaxml[0:10] + ".xml' download> Descarga XML </a>" frappe.msgprint(mensaje) return ["TIMBRADO EXITOSO!",mensaje,uuid,xml] def sales_invoice_timbrado_xml(docname): c = frappe.get_doc("Sales Invoice", docname) cliente = frappe.get_doc("Customer", c.customer) cant = len(c.items) company = frappe.get_doc("Configuracion CFDI", c.company) # horaminuto = c.posting_time # frappe.errprint(h oraminuto) # mytime = horaminuto.strftime("%H:%M:%S") # frappe.errprint(horaminuto) # return #fecha_actual = datetime.combine(c.posting_date,mytime).isoformat()[0:19] #dacosta - para hacer que se timbre con la fecha de posting_date descuento = round(c.discount_amount, 2) fecha_actual = (c.creation).isoformat()[0:19] serie = c.naming_series.replace('-','') folio = c.name.replace(serie,'') # frappe.errprint(c.name.replace(serie,'')) FormaPago = c.forma_de_pago #SubTotal = '%.2f' % c.net_total SubTotal = 0 Total = '%.2f' % (c.grand_total) # Total = 3509.40 TipoDeComprobante = 'I' # TipoCambio = 1 if c.currency = "MXN" else '%2f' % c.conversion_rate MetodoPago = c.metodo_pago LugarExpedicion = company.lugar_expedicion Currency = c.currency if Currency == 'MXN': TipoCambio = 1 else: TipoCambio = '%.4f' % c.conversion_rate rfc_emisor = company.rfc_emisor nombre_emisor = company.nombre_emisor.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') regimen_fiscal = company.regimen_fiscal tax_id = cliente.tax_id.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ü', 'U') nombre_receptor = c.customer_name.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') uso_cfdi = c.uso_cfdi tipo = [] tasa = [] cantidad = [] cfdi_items = "" cfdi_traslados = "" cfdi_mercancias = "" if c.comercio_exterior == 1: cfdi_mercancias = """ <cce11:Mercancias> """.format(**locals()) for x in c.items: i = frappe.get_doc("Item", x.item_code) if c.comercio_exterior == 1: arancelaria = frappe.get_doc("Fraccion Arancelaria", i.fraccion_arancelaria) UMT = arancelaria.umt else: arancelaria = "" UMT = "" NoIdentificacion = x.item_code.replace('"','').replace('&','&amp;') ClaveProdServ = i.clave_producto ClaveUnidad = i.clave_unidad Cantidad = x.qty Unidad = x.stock_uom ValorUnitario = '%.2f' % x.rate Importe = '%.2f' % x.amount idx = x.idx Descripcion = x.description.replace('"','').replace('&','&amp;').replace('<div class="ql-editor read-mode"><p>','').replace('<div><p>','').replace('</p></div>','').replace('<br>','').replace('<p>','').replace('</p>','').replace('<div class=ql-editor read-mode>','').replace('@','&commat;').replace('<strong>','').replace('</strong>','') des = round(x.descuento*x.qty, 2) TrasladosBase= '%.2f' % (float(x.amount) - float(des)) SubTotal = round(SubTotal + float(x.amount), 2) TasaOCuota = .01 * float(x.tasa) ImpuestosTrasladosTasaOCuota='%.6f' % TasaOCuota Importetax= '%.2f' % (TasaOCuota * (float(x.amount) - des)) Tasa = 'Tasa' FraccionArancelaria = i.fraccion_arancelaria UnidadAduana = i.unidad_aduana TipoImpuesto = x.tipo_de_impuesto if c.comercio_exterior == 1: NoIdentificacion_exterior = str(NoIdentificacion) + " " + str(x.idx) cfdi_mercancias += """ <cce11:Mercancia NoIdentificacion="{NoIdentificacion_exterior}" FraccionArancelaria="{FraccionArancelaria}" CantidadAduana="{Cantidad}" UnidadAduana="{UMT}" ValorUnitarioAduana="{ValorUnitario}" ValorDolares="{Importe}"/> """.format(**locals()) TipoImpuesto = "EXTERIOR" if TipoImpuesto == 'IVA': Impuesto = '002' tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif TipoImpuesto == "SIN IVA": Impuesto="002" tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif TipoImpuesto == "IEPS": Impuesto="003" tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif TipoImpuesto == "EXENTO": TrasladosBase1= x.net_amount TrasladosBase= '%.2f' % (TrasladosBase1) Impuesto="002" ImpuestosTrasladosTasaOCuota="0.000000" Importetax= "0.00" Tasa = 'Exento' tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif TipoImpuesto == "EXTERIOR": NoIdentificacion_exterior = str(NoIdentificacion) + " " + str(x.idx) cfdi_items += """ <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion_exterior}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> </cfdi:Concepto>""".format(**locals()) # tipo.append(Impuesto) # tasa.append(ImpuestosTrasladosTasaOCuota) # cantidad.append(Importetax) # frappe.errprint(Importetax) # cfdi_items += """ # <cfdi:Concepto ClaveProdServ="{ClaveProdServ}" NoIdentificacion="{NoIdentificacion}" Cantidad="{Cantidad}" ClaveUnidad="{ClaveUnidad}" Unidad="{Unidad}" Descripcion="{Descripcion}" ValorUnitario="{ValorUnitario}" Importe="{Importe}" Descuento="{des}"> # <cfdi:Impuestos> # <cfdi:Traslados> # <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> # </cfdi:Traslados> # </cfdi:Impuestos> # </cfdi:Concepto>""".format(**locals()) # # TotalImpuestosTrasladados= 4558.38 cTipo = collections.Counter(tipo) cTasa = collections.Counter(tasa) total_impuesto = 0 TotalImpuestosTrasladados = 0.00 for w, val1 in cTipo.items(): for y, val2 in cTasa.items(): if c.comercio_exterior == 1: suma = "EXTERIOR" else: suma =0 for z in range(0,cant): if (tasa[z] == y) and (tipo[z] == w): suma1 = suma+float(cantidad[z]) suma = round(suma1, 2) b = y t = w total_impuesto = total_impuesto+suma TotalImpuestosTrasladados = suma if(suma>0): cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="{Tasa}" TasaOCuota="{b}" Importe="{suma}"/>""".format(**locals()) elif(suma==0): cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="{Tasa}" TasaOCuota="{b}" Importe="{suma}"/>""".format(**locals()) elif(suma=="EXTERIOR"): cfdi_traslados += "" Total = round(SubTotal - descuento + TotalImpuestosTrasladados, 2) cfdi = "" if c.comercio_exterior == 1: Totalant = round(SubTotal - descuento + TotalImpuestosTrasladados, 2) Total = '%.2f' % (Totalant) cfdi_comprobante = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:cce11="http://www.sat.gob.mx/ComercioExterior11" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/ComercioExterior11 http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior11/ComercioExterior11.xsd" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" FormaPago="{FormaPago}" NoCertificado="" Certificado="" CondicionesDePago="CONTADO" SubTotal="{SubTotal}" Descuento="{descuento}" Moneda="{Currency}" TipoCambio = "{TipoCambio}" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" MetodoPago="{MetodoPago}" LugarExpedicion="{LugarExpedicion}">""".format(**locals()) else: cfdi_comprobante = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" FormaPago="{FormaPago}" NoCertificado="" Certificado="" CondicionesDePago="CONTADO" SubTotal="{SubTotal}" Descuento="{descuento}" Moneda="{Currency}" TipoCambio = "{TipoCambio}" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" MetodoPago="{MetodoPago}" LugarExpedicion="{LugarExpedicion}">""".format(**locals()) cfdi += cfdi_comprobante # #es_sustitucion = frappe.get_value('Sales Invoice', docname,'sustituidos') # try: #site = frappe.local.site # if site == "demo.totall.mx": if c.cfdi_sustitucion == 1: relacion = c.relacion cfdi += """ <cfdi:CfdiRelacionados TipoRelacion="{relacion}">""".format(**locals()) for d in c.si_sustitucion: cfdi+=""" <cfdi:CfdiRelacionado UUID="{d.uuid}"/>""".format(**locals()) cfdi+=""" </cfdi:CfdiRelacionados>""".format(**locals()) # if es_sustitucion: # if c.sustituidos == 1: # frappe.errprint('si existe') # else: # frappe.errprint('no existe') cfdi+= """ <cfdi:Emisor Rfc="{rfc_emisor}" Nombre="{nombre_emisor}" RegimenFiscal="{regimen_fiscal}"/> <cfdi:Receptor Rfc="{tax_id}" Nombre="{nombre_receptor}" UsoCFDI="{uso_cfdi}"/> <cfdi:Conceptos>""".format(**locals()) cfdi += cfdi_items if c.comercio_exterior == 1: tax_id = "XAXX010101000" cfdi_conceptos = """ </cfdi:Conceptos>""".format(**locals()) else: cfdi_conceptos = """ </cfdi:Conceptos> <cfdi:Impuestos TotalImpuestosTrasladados="{TotalImpuestosTrasladados}"> <cfdi:Traslados>""".format(**locals()) cfdi += cfdi_conceptos cfdi += cfdi_traslados cfdi_complemento = "" cfdi_emisor = "" cfdi_receptor = "" cfdi_header = """ </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Comprobante> """.format(**locals()) if c.comercio_exterior == 1: EDireccion = frappe.get_doc("Address", c.customer_address) ECalle = re.findall("[^0-9]+", EDireccion.address_line1)[0].replace('#', '') ENumeroExterior = re.findall("\d+", EDireccion.address_line1)[0] EColonia = EDireccion.county EEstado = EDireccion.clave_estado ECp = EDireccion.pincode ######################################### #Letras del pais UNIDECODE Origen pais = frappe.get_doc("CFDI Clave Estado", EDireccion.clave_estado) EPais = pais.pais if c.comercio_exterior == 1: cfdi_complemento = """ <cfdi:Complemento> <cce11:ComercioExterior Version="1.1" TipoOperacion="2" ClaveDePedimento="{c.clave_pedimento}" CertificadoOrigen="0" Incoterm="{c.incoterm}" Subdivision="0" TipoCambioUSD="{TipoCambio}" TotalUSD="{Total}" xmlns:cce11="http://www.sat.gob.mx/ComercioExterior11" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/ComercioExterior11 http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior11/ComercioExterior11.xsd">""".format(**locals()) cfdi_emisor = """ <cce11:Emisor> <cce11:Domicilio Calle="López Cotilla" NumeroExterior="13" Localidad="12" Municipio="101" Estado="JAL" Pais="MEX" CodigoPostal="{company.lugar_expedicion}"/> </cce11:Emisor> """.format(**locals()) cfdi_receptor = """ <cce11:Receptor> <cce11:Domicilio Calle="{ECalle}" NumeroExterior="{ENumeroExterior}" Colonia="{EColonia}" Estado="{EEstado}" Pais="{EPais}" CodigoPostal="{ECp}"/> </cce11:Receptor> """.format(**locals()) cfdi_header = """ </cce11:Mercancias> </cce11:ComercioExterior> </cfdi:Complemento> </cfdi:Comprobante> """.format(**locals()) cfdi += cfdi_complemento cfdi += cfdi_emisor cfdi += cfdi_receptor cfdi += cfdi_mercancias cfdi += cfdi_header frappe.errprint(cfdi) return cfdi @frappe.whitelist() def cancel_by_uuid_sales_invoice(url, token,uuid,docname, rfc): c = frappe.get_doc("Sales Invoice", docname) headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("POST", url + "/cfdi33/cancel/" + rfc + "/" + uuid, headers=headers) if response.json().get('status') == 'error': if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: frappe.db.set_value("Sales Invoice", c.name, 'cfdi_status','Cancelado') frappe.msgprint(str(c.name)+ " Cancelada Exitosamente") return response.text ############################################# #Comienza Carta Porte @frappe.whitelist() def carta_porte_timbrado(url, token, docname, version, b64=False): # RG - POST request al server de swarterweb xml = carta_porte_timbrado_xml(docname) frappe.errprint(xml) lst = [random.choice(string.ascii_letters + string.digits) for n in range(30)] boundary = "".join(lst) payload = "--" + boundary + "\r\nContent-Type: text/xml\r\nContent-Transfer-Encoding: binary\r\nContent-Disposition: " \ "form-data; name=\"xml\"; filename=\"xml\"\r\n\r\n" + str(xml) + "\r\n--" + boundary + "-- " headers = { 'Authorization': "bearer " + token, 'Content-Type': "multipart/form-data; boundary=\"" + boundary + "\"" } response = requests.request("POST", url + "/cfdi33/issue/" + version + "/" , data=payload.encode('utf-8'), headers=headers) liga = url + "/cfdi33/issue/" + version + "/" frappe.errprint(response.json()) if response.json().get('status') == 'error': if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: # RG- Recuperar el response y manejar la info pa grabar los archivos/datos en el CFDI c = frappe.get_doc("Delivery Trip", docname) uuid = response.json().get('data').get('uuid') cfdi_recibido = response.json().get('data').get('cfdi') fechaxml = str(c.creation) dest = '/home/frappe/frappe-bench/sites/' + frappe.local.site + '/public/files/' + c.name + "_" + fechaxml[0:10] f = open( dest + '.xml',"w+") f.write(cfdi_recibido) f.close() save_url( "/files/" + c.name + "_" + fechaxml[0:10] + ".xml" , c.name + "_" + fechaxml[0:10] + ".xml" , "Delivery Trip" , c.name , "Home/Attachments" , 0) qr = response.json().get('data').get('qrCode') png = open( dest + ".png", "wb") png.write(base64.b64decode(qr)) png.close() frappe.db.set_value("Delivery Trip",c.name, 'qr', "/files/" + c.name + "_" + fechaxml[0:10] + ".png") frappe.db.set_value("Delivery Trip",c.name, 'cfdi_status', 'Timbrado') frappe.db.set_value("Delivery Trip",c.name, 'sellocfd', response.json().get('data').get('selloCFDI')) frappe.db.set_value("Delivery Trip",c.name, 'cadenaoriginalsat', response.json().get('data').get('cadenaOriginalSAT')) frappe.db.set_value("Delivery Trip",c.name, 'fechatimbrado', response.json().get('data').get('fechaTimbrado') ) frappe.db.set_value("Delivery Trip",c.name, 'uuid', uuid) frappe.db.set_value("Delivery Trip",c.name, 'nocertificadosat', response.json().get('data').get('noCertificadoSAT') ) frappe.db.set_value("Delivery Trip",c.name, 'sellosat', response.json().get('data').get('selloSAT') ) mensaje = "TIMBRADO EXITOSO . <a class= 'alert-info' href='https://" + frappe.local.site + "/files/" + uuid + ".xml' download> Descarga XML </a>" frappe.msgprint(mensaje) return ["TIMBRADO EXITOSO!",mensaje,uuid,xml] def carta_porte_timbrado_xml(docname): c = frappe.get_doc("Delivery Trip", docname) TranspInternac = "" if c.transporte_internacional == 1: TranspInternac = 'Si' else: TranspInternac = 'No' company = frappe.get_doc("Configuracion CFDI", c.company) fecha_actual = (c.creation).isoformat()[0:19] fecha_salida = (c.departure_time).isoformat()[0:19] serie = c.naming_series.replace('-','') folio = c.name.replace(serie,'') FormaPago = c.forma_de_pago if c.tipo_de_comprobante == "I": SubTotal = '%.2f' % c.precio_traslado Total = round(c.precio_traslado * 1.16, 2) else: SubTotal = 0 Total = 0 TipoDeComprobante = c.tipo_de_comprobante MetodoPago = c.metodo_de_pago LugarExpedicion = company.lugar_expedicion Currency = c.currency if Currency == 'MXN': TipoCambio = 1 else: TipoCambio = '%.4f' % c.conversion_rate rfc_emisor = company.rfc_emisor nombre_emisor = company.nombre_emisor.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') regimen_fiscal = company.regimen_fiscal uso_cfdi = c.uso_cfdi ########################################## #Datos de Direccion de Origen ODireccion = frappe.get_doc("Address", c.driver_address) OCalle = re.findall("[^0-9]+", ODireccion.address_line1)[0].replace('#', '') ONumeroExterior = re.findall("\d+", ODireccion.address_line1)[0] ######################################### #Letras del pais UNIDECODE Origen OClave_estado = ODireccion.clave_estado InfOClave_estado = frappe.get_doc("CFDI Clave Estado", OClave_estado) OPais = InfOClave_estado.pais articulo_claveDT = c.unidad_pesocp suma_distancia = 0 ########################################## #Datos de Direccion de destinatario for dest in c.delivery_stops: UCliente = dest.customer cliente = frappe.get_doc("Customer", UCliente) nombre_receptor = UCliente.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ') tax_id = cliente.tax_id.replace('&','&amp;').replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u').replace('À','a').replace('É','e').replace('Í','i').replace('Ó','o').replace('Ú','u').replace('@',' ').replace('Ü', 'U') rfc_receptor = cliente.tax_id Fecha_llegada = (dest.estimated_arrival).isoformat()[0:19] UDireccion = frappe.get_doc("Address", dest.address) UCalle = re.findall("[^0-9]+", UDireccion.address_line1)[0].replace('#', '') UNumeroExterior = re.findall("\d+", UDireccion.address_line1)[0] ######################################### #Letras del pais UNIDECODE Origen UClave_estado = UDireccion.clave_estado InfUClave_estado = frappe.get_doc("CFDI Clave Estado", UClave_estado) UPais = InfUClave_estado.pais UCodigo_postal = UDireccion.pincode ########################################## distancia = round(dest.distance, 2) suma_distancia += round(distancia, 2) ########################################## #Obtener informacion de Notra de Entrega DN = frappe.get_doc("Delivery Note", dest.delivery_note) cant = len(DN.items) PesoBrutoTotal = DN.total_net_weight cfdi_ubicacion_destino = """ <cartaporte20:Ubicacion TipoUbicacion="Destino" RFCRemitenteDestinatario="{rfc_receptor}" FechaHoraSalidaLlegada="{Fecha_llegada}" DistanciaRecorrida="{distancia}"> <cartaporte20:Domicilio Calle="{UCalle}" NumeroExterior="{UNumeroExterior}" Estado="{UClave_estado}" Pais="{UPais}" CodigoPostal="{UCodigo_postal}" /> </cartaporte20:Ubicacion> """.format(**locals()) ########################################## #Obtener informacion de articulos en Notra de Entrega tipo = [] tasa = [] cantidad = [] cfdi_items = "" cfdi_traslados = "" for articulos_nota in DN.items: articulo_qty = articulos_nota.qty articulo_peso = articulos_nota.total_weight row = str(articulos_nota.idx) NumTotalMercancias = len(row) ########################################## #Obtener informacion del articulo en general informacion_articulo = frappe.get_doc("Item", articulos_nota.item_code) articulo_cps = informacion_articulo.clave_producto articulo_cu = informacion_articulo.clave_unidad articulo_claveUP = informacion_articulo.unidad_pesocp material_peligroso = informacion_articulo.material_peligroso articulo_descripcion = informacion_articulo.description articulos_mercancias_header = """ </cartaporte20:Ubicaciones> <cartaporte20:Mercancias PesoBrutoTotal="{PesoBrutoTotal}" UnidadPeso="{articulo_claveDT}" NumTotalMercancias="{NumTotalMercancias}" >""".format(**locals()) articulos_mercancias = """ <cartaporte20:Mercancia BienesTransp="{articulo_cps}" Descripcion="{articulo_descripcion}" Cantidad="{articulo_qty}" ClaveUnidad="{articulo_claveUP}" PesoEnKg="{articulo_peso}"> </cartaporte20:Mercancia>""".format(**locals()) NoIdentificacion = articulos_nota.item_code.replace('"','').replace('&','&amp;') ClaveProdServ = informacion_articulo.clave_producto ClaveUnidad = informacion_articulo.clave_unidad Cantidad = articulos_nota.qty Unidad = articulos_nota.stock_uom ValorUnitario = '%.2f' % c.precio_traslado Importe = '%.2f' % c.precio_traslado idx = articulos_nota.idx Descripcion = articulos_nota.item_name.replace('"','').replace('&','&amp;') TrasladosBase= '%.2f' % c.precio_traslado TasaOCuota = .01 * float(informacion_articulo.tasa) ImpuestosTrasladosTasaOCuota='%.6f' % TasaOCuota Importetax= '%.2f' % (TasaOCuota * (float(c.precio_traslado))) Tasa = 'Tasa' if informacion_articulo.tipo_de_impuesto == 'IVA': Impuesto = '002' tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="78101800" NoIdentificacion="01" Cantidad="1" ClaveUnidad="E48" Unidad="SERVICIO" Descripcion="FLETE" ValorUnitario="{ValorUnitario}" Importe="{Importe}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif informacion_articulo.tipo_de_impuesto == "SIN IVA": Impuesto="002" tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="78101800" NoIdentificacion="01" Cantidad="1" ClaveUnidad="E48" Unidad="SERVICIO" Descripcion="FLETE" ValorUnitario="{ValorUnitario}" Importe="{Importe}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif informacion_articulo.tipo_de_impuesto == "IEPS": Impuesto="003" tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="78101800" NoIdentificacion="01" Cantidad="1" ClaveUnidad="E48" Unidad="SERVICIO" Descripcion="FLETE" ValorUnitario="{ValorUnitario}" Importe="{Importe}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}" TasaOCuota="{ImpuestosTrasladosTasaOCuota}" Importe="{Importetax}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) elif informacion_articulo.tipo_de_impuesto == "EXENTO": TrasladosBase1= articulos_nota.net_amount TrasladosBase= '%.2f' % (TrasladosBase1) Impuesto="002" ImpuestosTrasladosTasaOCuota="0.000000" Importetax= "0.00" Tasa = 'Exento' tipo.append(Impuesto) tasa.append(ImpuestosTrasladosTasaOCuota) cantidad.append(Importetax) frappe.errprint(Importetax) cfdi_items += """ <cfdi:Concepto ClaveProdServ="78101800" NoIdentificacion="01" Cantidad="1" ClaveUnidad="E48" Unidad="SERVICIO" Descripcion="FLETE" ValorUnitario="{ValorUnitario}" Importe="{Importe}"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="{TrasladosBase}" Impuesto="{Impuesto}" TipoFactor="{Tasa}"/> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto>""".format(**locals()) cTipo = collections.Counter(tipo) cTasa = collections.Counter(tasa) total_impuesto = 0 TotalImpuestosTrasladados = 0.00 for w, val1 in cTipo.items(): for y, val2 in cTasa.items(): suma =0 for z in range(0,cant): if (tasa[z] == y) and (tipo[z] == w): suma1 = suma+float(cantidad[z]) suma = round(suma1, 2) b = y t = w total_impuesto = total_impuesto+suma TotalImpuestosTrasladados = suma if(suma>0): cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="{Tasa}" TasaOCuota="{b}" Importe="{suma}"/>""".format(**locals()) else: cfdi_traslados += """ <cfdi:Traslado Impuesto="{t}" TipoFactor="{Tasa}" TasaOCuota="{b}" Importe="{suma}"/>""".format(**locals()) # Total = round(SubTotal + TotalImpuestosTrasladados, 2) ########################################## #Si es auto transporte AutotransporteFederal if c.via == '01': #Obtener datos de Vehiculo vehicle = frappe.get_doc("Vehicle", c.vehicle) PermSCT = vehicle.tipo_permiso NumPermisoSCT = vehicle.numero_permiso NombreAseg = vehicle.insurance_company NumPolizaSeguro = vehicle.policy_no ConfigVehicular = vehicle.configuracion_vehicular AnioModeloVM = vehicle.model PlacaVM = c.vehicle.replace("-","") ########################################## #Obtener datos de Operador operador = frappe.get_doc("Driver", c.driver) RFCOperador = operador.rfc NumLicencia = operador.license_number NombreOperador = operador.full_name #Obtener datos de Direccion de Operador DO = frappe.get_doc("Address", c.driver_address) DOCalle = re.findall("[^0-9]+", DO.address_line1)[0].replace('#', '') DONumeroExterior = re.findall("\d+", DO.address_line1)[0] ######################################### #Letras del pais UNIDECODE Origen InfDOClave_estado = frappe.get_doc("CFDI Clave Estado", UClave_estado) DOPais = InfDOClave_estado.pais DOClave_estado = DO.clave_estado DOCodigo_postal = DO.pincode if c.tipo_de_comprobante == "I": cfdi = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/CartaPorte20 http://www.sat.gob.mx/sitio_internet/cfd/CartaPorte/CartaPorte20.xsd" xmlns:cartaporte20="http://www.sat.gob.mx/CartaPorte20" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" FormaPago="{FormaPago}" NoCertificado="" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Certificado="" CondicionesDePago="CONTADO" SubTotal="{SubTotal}" Moneda="{Currency}" TipoCambio = "{TipoCambio}" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" MetodoPago="{MetodoPago}" LugarExpedicion="{LugarExpedicion}">""".format(**locals()) else: cfdi = """<?xml version="1.0" encoding="UTF-8"?> <cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/CartaPorte20 http://www.sat.gob.mx/sitio_internet/cfd/CartaPorte/CartaPorte20.xsd" xmlns:cartaporte20="http://www.sat.gob.mx/CartaPorte20" Version="3.3" Serie="{serie}" Folio="{folio}" Fecha="{fecha_actual}" Sello="" NoCertificado="" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Certificado="" SubTotal="{SubTotal}" Moneda="XXX" Total="{Total}" TipoDeComprobante="{TipoDeComprobante}" LugarExpedicion="{LugarExpedicion}">""".format(**locals()) cfdi+= """ <cfdi:Emisor Rfc="{rfc_emisor}" Nombre="{nombre_emisor}" RegimenFiscal="{regimen_fiscal}"/> <cfdi:Receptor Rfc="{tax_id}" Nombre="{nombre_receptor}" UsoCFDI="{uso_cfdi}"/> <cfdi:Conceptos>""".format(**locals()) if c.tipo_de_comprobante == "I": cfdi += cfdi_items else: cfdi += """ <cfdi:Concepto ClaveProdServ="78101800" NoIdentificacion="01" Cantidad="1" ClaveUnidad="E48" Unidad="SERVICIO" Descripcion="FLETE" ValorUnitario="{ValorUnitario}" Importe="{Importe}" /> </cfdi:Conceptos> """.format(**locals()) cfdi_conceptos = """ </cfdi:Conceptos> <cfdi:Impuestos TotalImpuestosTrasladados="{TotalImpuestosTrasladados}"> <cfdi:Traslados>""".format(**locals()) if c.tipo_de_comprobante == "I": cfdi += cfdi_conceptos cfdi += cfdi_traslados cfdi += """ </cfdi:Traslados> </cfdi:Impuestos> """.format(**locals()) cfdi_carta_porte = """<cfdi:Complemento> <cartaporte20:CartaPorte Version="2.0" TranspInternac="{TranspInternac}" TotalDistRec="{suma_distancia}"> <cartaporte20:Ubicaciones>""".format(**locals()) cfdi_ubicacion_origen = """ <cartaporte20:Ubicacion TipoUbicacion="Origen" RFCRemitenteDestinatario="{rfc_emisor}" FechaHoraSalidaLlegada="{fecha_salida}"> <cartaporte20:Domicilio Calle="{DOCalle}" NumeroExterior="{DONumeroExterior}" Estado="{DOClave_estado}" Pais="MEX" CodigoPostal="{DOCodigo_postal}" /> </cartaporte20:Ubicacion>""".format(**locals()) cfdi_autotransporte = """ <cartaporte20:Autotransporte PermSCT="{PermSCT}" NumPermisoSCT="{NumPermisoSCT}"> <cartaporte20:IdentificacionVehicular ConfigVehicular="{ConfigVehicular}" PlacaVM="{PlacaVM}" AnioModeloVM="{AnioModeloVM}" /> <cartaporte20:Seguros AseguraRespCivil="{NombreAseg}" PolizaRespCivil="{NumPolizaSeguro}"/> </cartaporte20:Autotransporte> </cartaporte20:Mercancias> """.format(**locals()) cfdi_figura_transporte = """ <cartaporte20:FiguraTransporte> <cartaporte20:TiposFigura TipoFigura="01" RFCFigura="VAAM130719H60" NumLicencia="a234567890"> </cartaporte20:TiposFigura> </cartaporte20:FiguraTransporte> </cartaporte20:CartaPorte> </cfdi:Complemento> </cfdi:Comprobante>""".format(**locals()) cfdi += cfdi_carta_porte cfdi += cfdi_ubicacion_origen cfdi += cfdi_ubicacion_destino cfdi += articulos_mercancias_header cfdi += articulos_mercancias cfdi += cfdi_autotransporte cfdi += cfdi_figura_transporte frappe.errprint(cfdi) return cfdi @frappe.whitelist() def cancel_by_uuid_carta_porte(url, token,uuid,docname, rfc): c = frappe.get_doc("Delivery Trip", docname) headers = { 'Authorization': "bearer " + token, 'Content-Type': "application/json" } response = requests.request("POST", url + "/cfdi33/cancel/" + rfc + "/" + uuid, headers=headers) if response.json().get('status') == 'error': if response.json().get('messageDetail'): frappe.msgprint((response.json().get('message')) + ". <b>Detalle del Error: </b>" + (response.json().get('messageDetail')), "ERROR DE SERVIDOR (PAC) ") else: frappe.msgprint((response.json().get('message')) , "ERROR DE SERVIDOR") else: frappe.db.set_value("Delivery Trip", c.name, 'cfdi_status','Cancelado') frappe.msgprint(str(c.name)+ " Cancelada Exitosamente") return response.text
52.62004
490
0.60867
8,445
78,246
5.546004
0.088336
0.009181
0.024981
0.016739
0.735908
0.715774
0.697348
0.672794
0.63701
0.616748
0
0.016867
0.216535
78,246
1,486
491
52.655451
0.747141
0.082624
0
0.609091
0
0.052066
0.381515
0.122358
0
0
0
0.000673
0
1
0.014876
false
0.004132
0.069421
0
0.1
0.047107
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
68f14d10051a68fe80a35af7b3706b88c9b1de8b
538
py
Python
analysis/parallel/__init__.py
lconaboy/seren3
5a2ec80adf0d69664d2ee874f5ba12cc02d6c337
[ "CNRI-Python" ]
1
2017-09-21T14:58:23.000Z
2017-09-21T14:58:23.000Z
analysis/parallel/__init__.py
lconaboy/seren3
5a2ec80adf0d69664d2ee874f5ba12cc02d6c337
[ "CNRI-Python" ]
1
2020-09-09T08:52:43.000Z
2020-09-09T08:52:43.000Z
analysis/parallel/__init__.py
lconaboy/seren3
5a2ec80adf0d69664d2ee874f5ba12cc02d6c337
[ "CNRI-Python" ]
1
2019-01-21T10:57:41.000Z
2019-01-21T10:57:41.000Z
class Result(object): ''' Simple wrapper object to contain result of single iteration MPI computation ''' def __init__(self, rank, idx): self.rank = rank self.idx = idx self.result = None def __repr__(self): return "rank: %d idx: %s result: %s" % (self.rank, self.idx, self.result) def __eq__(self, other): return self.result == other.result def __ne__(self, other): return self.result != other.result def __hash__(self): return hash(self.result)
26.9
81
0.607807
69
538
4.449275
0.376812
0.162866
0.071661
0.123779
0.254072
0.254072
0.254072
0.254072
0
0
0
0
0.27881
538
20
82
26.9
0.791237
0.139405
0
0
0
0
0.060268
0
0
0
0
0
0
1
0.384615
false
0
0
0.307692
0.769231
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
68f45ae803ebba062da6775e6b5c1f8ffa99fc56
5,020
py
Python
yrest/auth.py
Garito/python-yrest
e31b5e02a2e460db738cc0a21e09255c0a71e40f
[ "MIT" ]
null
null
null
yrest/auth.py
Garito/python-yrest
e31b5e02a2e460db738cc0a21e09255c0a71e40f
[ "MIT" ]
null
null
null
yrest/auth.py
Garito/python-yrest
e31b5e02a2e460db738cc0a21e09255c0a71e40f
[ "MIT" ]
null
null
null
from os import urandom from binascii import hexlify from hashlib import pbkdf2_hmac from secrets import compare_digest from typing import Any, List, Tuple, Dict, Union from datetime import datetime, timedelta from dataclasses import dataclass, field from uuid import UUID, uuid4 from bson import ObjectId import jwt from sanic.request import Request from sanic.exceptions import Unauthorized from dataclasses_jsonschema import JsonSchemaMixin, JsonSchemaMeta from yrest.tree import Tree, Email, Password from yrest.mongo import Mongo from yrest.utils import Ok, ErrorMessage def generate_password_hash(password: str, salt = None, iterations: int = 50000) -> str: salt = hexlify(urandom(8)) if salt is None else str.encode(salt) password = str.encode(password) hex_hash = hexlify(pbkdf2_hmac("sha256", password, salt, iterations)) return f"pbkdf2:sha256:{iterations}${salt.decode('utf-8')}${hex_hash.decode('utf-8')}" def check_password_hash(hashed: str, password: str) -> bool: _, salt, _ = hashed.split("$") return compare_digest(generate_password_hash(password, salt), hashed) @dataclass class AuthToken(JsonSchemaMixin): access_token: str @classmethod def get(cls, headers, key: str = "Authorization", prefix: str = "Bearer") -> Dict[str, str]: return cls(headers[key].replace(f"{prefix} ", "") if key in headers else None) @classmethod def generate(cls, payload: Dict[str, Any], secret: str, exp: int = 30, algo: str = "HS256") -> str: if "exp" not in payload: payload["exp"] = datetime.utcnow() + timedelta(minutes = exp) return cls(jwt.encode(payload, secret, algo).decode()) def verify(self, secret: str, algos: List[str] = None) -> bool: try: return jwt.decode(self.access_token, secret, algorithms = algos or ["HS256"]) except (jwt.DecodeError, jwt.ExpiredSignatureError): return False async def get_actor(self, table, secret, user_class): payload = self.verify(secret) if payload: return await user_class.get(table, _id = ObjectId(payload["user_id"])) @dataclass class Auth(JsonSchemaMixin): """The authentication model""" email: Email = field(metadata = JsonSchemaMeta(title = "Enter your email", extensions = {'label': 'Email', 'placeholder': 'email@example.com'})) password: Password = field(metadata = JsonSchemaMeta(title = "Enter your password. Click on the eye to reveal it (take care of not revealing it to others)", extensions = {'label': 'Password'})) @classmethod def secure(cls, password): return password if password.startswith('pbkdf2:sha256:') else generate_password_hash(password) async def authorize(self, table, secret, user_class): user = await user_class.get(table, email = self.email) if user and check_password_hash(user.password, self.password): return AuthToken.generate({"user_id": str(user._id)}, secret) @dataclass class ForgotPasswordRequest(JsonSchemaMixin): email: Email = field(metadata = JsonSchemaMeta(title = "Enter your email", extensions = {'label': 'Email', 'placeholder': 'email@example.com'})) @dataclass class NeedsEmail: email: Email @dataclass class PasswordResetToken(JsonSchemaMixin, Tree, Mongo, NeedsEmail): code: UUID = field(default_factory = uuid4) created_at: datetime = field(default_factory = datetime.utcnow) def __sluger__(self, values = None, fields: bool = False) -> Union[Tuple, str]: if fields: return ("email",) elif values: return values.get('email', self.email) else: return self.email @dataclass class ResetPassword(JsonSchemaMixin): code: UUID password: Password = field(metadata = JsonSchemaMeta(title = "Enter the new password. Click on the eye to reveal it (take care of not revealing it to others)", extensions = {'label': 'Password'})) class IsAuth: async def auth(self, request: Request, consume: Auth) -> AuthToken: """Authorizes email and password""" token = await consume.authorize(self._table, request.app.config["JWT_SECRET"], request.app._models.User) return token if token else ErrorMessage("The autentication has failed", 401) async def forgot_password(self, request: Request, consume: ForgotPasswordRequest) -> Ok: """Sends a password recovery mail to the specified mail""" from sanic.log import logger user = await request.app._models.User.get(self._table, email = consume.email) if not user: return ErrorMessage("Unregistered email", 404) prevToken = await PasswordResetToken.get(self._table, email = consume.email) if prevToken: return ErrorMessage("Already requested", 429) token = PasswordResetToken(consume.email, path = "/") token._table = self._table await token.create() await request.app.notify(request, 'forgot_password', actor = user, token = token) async def reset_password(self, request: Request, consume: ResetPassword) -> Ok: """Reset the password authenticating the actor the forgot password token""" from sanic.log import logger logger.info(consume)
38.615385
198
0.726693
641
5,020
5.616225
0.277691
0.023333
0.03
0.035556
0.209444
0.152222
0.151111
0.104444
0.104444
0.104444
0
0.009474
0.158964
5,020
129
199
38.914729
0.843202
0.004781
0
0.136842
0
0.031579
0.119245
0.015761
0
0
0
0
0
1
0.073684
false
0.2
0.189474
0.021053
0.589474
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
68fab79f7a6200663e48015d71df80c194f90e0b
261
py
Python
volume/config.py
Napam/apartmentscience
2724b94a9f00617c8f18994b07ee125c6d89d188
[ "Apache-2.0" ]
null
null
null
volume/config.py
Napam/apartmentscience
2724b94a9f00617c8f18994b07ee125c6d89d188
[ "Apache-2.0" ]
null
null
null
volume/config.py
Napam/apartmentscience
2724b94a9f00617c8f18994b07ee125c6d89d188
[ "Apache-2.0" ]
null
null
null
import pathlib import configparser _alembicConfig = configparser.ConfigParser() _alembicConfig.read("alembic.ini") SQL_ADDRESS = _alembicConfig["alembic"]["sqlalchemy.url"] TMP_DIR = pathlib.Path("data") / "tmp" FINN_URL = "https://www.finn.no/api/search-qf"
26.1
57
0.766284
32
261
6.0625
0.6875
0.257732
0
0
0
0
0
0
0
0
0
0
0.08046
261
9
58
29
0.808333
0
0
0
0
0
0.275862
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ec1d8e3dcc329b431051594eadc0219aca2fd48e
1,248
py
Python
dezirteer/const.py
dazdraperma/dezirteer
d46997b50c5e885e45950f65755147bdcbdb08f0
[ "MIT" ]
3
2021-07-18T19:25:37.000Z
2021-11-26T06:44:48.000Z
dezirteer/const.py
dazdraperma/dezirteer
d46997b50c5e885e45950f65755147bdcbdb08f0
[ "MIT" ]
1
2018-09-04T09:58:36.000Z
2018-09-04T09:58:36.000Z
dezirteer/const.py
dazdraperma/dezirteer
d46997b50c5e885e45950f65755147bdcbdb08f0
[ "MIT" ]
3
2018-08-27T05:55:34.000Z
2021-07-20T07:22:45.000Z
LAMBDA_232 = 4.934E-11#Amelin and Zaitsev, 2002. # LAMBDA_232 = 4.9475E-11 #old value, used in isoplot ERR_LAMBDA_232 = 0.015E-11#Amelin and Zaitsev, 2002. LAMBDA_235 = 9.8485E-10 #ERR_LAMBDA_235 = LAMBDA_238 = 1.55125E-10 #ERR_LAMBDA_238 = U238_U235 = 137.817 #https://doi.org/10.1016/j.gca.2018.06.014 # U238_U235 = 137.88 #old value, used in isoplot ERR_U238_U235 = 0.031 ##https://doi.org/10.1016/j.gca.2018.06.014 lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232] isotope_ratios = ["U238_Pb206", "U235_Pb207", "Th232_Pb208", "Pb206_Pb207"] minerals = ["zircon", "baddeleyite", "perovskite", "monazite", "apatite"] EarthAge = 4600 sqrt2pi = 2.506628274631 listColumnNames = ['Th232/Pb208', 'err.Th232/Pb208', '206Pb/207Pb', 'err.206Pb/207Pb', '235U/207Pb', 'err.235U/207Pb', '238U/206Pb', 'err.238U/206Pb', 'corr.', 'Age_232Th/208Pb', 'err.Age_232Th/208Pb', 'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb', 'Age_238U/206Pb', 'err.Age_238U/206Pb', 'Age_235U/207Pb', 'err.Age_235U/207Pb', '%disc.67-86', '%disc.86-57', 'is grain good?']
32.842105
75
0.591346
170
1,248
4.164706
0.435294
0.050847
0.028249
0.050847
0.231638
0.231638
0.084746
0.084746
0.084746
0.084746
0
0.301179
0.252404
1,248
37
76
33.72973
0.457663
0.209135
0
0
0
0
0.366154
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ec369abeb37de118e09d34e4d3793bbe34def6d9
253
py
Python
setup.py
jaycedowell/mnc_python
bc378ccc9a6cfaf76691122f072366b13e6ef092
[ "BSD-3-Clause" ]
2
2021-08-12T18:18:11.000Z
2021-12-02T07:58:51.000Z
setup.py
jaycedowell/mnc_python
bc378ccc9a6cfaf76691122f072366b13e6ef092
[ "BSD-3-Clause" ]
1
2021-12-15T18:51:14.000Z
2021-12-15T18:51:14.000Z
setup.py
jaycedowell/mnc_python
bc378ccc9a6cfaf76691122f072366b13e6ef092
[ "BSD-3-Clause" ]
1
2021-12-03T15:05:00.000Z
2021-12-03T15:05:00.000Z
from setuptools import setup from version import get_git_version setup(name='mnc-python', version=get_git_version(), url='http://github.com/ovro-lwa/mnc-python', requirements=['astropy'], packages=['mnc'], zip_safe=False)
25.3
50
0.679842
33
253
5.060606
0.666667
0.071856
0.155689
0
0
0
0
0
0
0
0
0
0.177866
253
9
51
28.111111
0.802885
0
0
0
0
0
0.225296
0
0
0
0
0
0
1
0
true
0
0.25
0
0.25
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
ec3a14c6144d721e7cea158c139c26dd612c2161
6,668
py
Python
src/franz/openrdf/model/value.py
franzinc/agraph-python
9186f19094af0be1daec273270888eadf9a68300
[ "MIT" ]
25
2015-11-05T03:43:30.000Z
2022-03-09T07:19:09.000Z
src/franz/openrdf/model/value.py
franzinc/agraph-python
9186f19094af0be1daec273270888eadf9a68300
[ "MIT" ]
14
2017-07-18T20:41:26.000Z
2021-10-13T04:57:36.000Z
src/franz/openrdf/model/value.py
franzinc/agraph-python
9186f19094af0be1daec273270888eadf9a68300
[ "MIT" ]
8
2016-12-09T02:38:45.000Z
2020-10-12T07:59:17.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable-msg=C0103 ################################################################################ # Copyright (c) 2006-2017 Franz Inc. # All rights reserved. This program and the accompanying materials are # made available under the terms of the MIT License which accompanies # this distribution, and is available at http://opensource.org/licenses/MIT ################################################################################ from __future__ import absolute_import from __future__ import unicode_literals import sys import builtins import weakref from six import python_2_unicode_compatible import six from ..util import uris, strings # Keys used to establish ordering between different types of terms LITERAL_CMP_KEY = 1 URI_CMP_KEY = 2 BNODE_CMP_KEY = 3 @python_2_unicode_compatible class Value(object): """ Top class in the org.openrdf.model interfaces. """ __slots__ = ('__weakref__',) def __str__(self): return self.toNTriples() def __repr__(self): result = self.toNTriples() # Return an ascii string on Python 2, otherwise pytest gets confused if sys.version_info < (3,): result = result.encode('unicode-escape') return result def get_cmp_key(self): """ Return a key that will be used to compare and hash this object. """ raise NotImplementedError() # Comparison methods rely on get_cmp_key. def __eq__(self, other): return self is other or (isinstance(other, Value) and self.get_cmp_key() == other.get_cmp_key()) def __ne__(self, other): return not self == other def __hash__(self): return hash(self.get_cmp_key()) def __lt__(self, other): return self.get_cmp_key() < other.get_cmp_key() def __gt__(self, other): return self.get_cmp_key() > other.get_cmp_key() def __le__(self, other): return not self > other def __ge__(self, other): return not self < other def toNTriples(self): """ Return an NTriples representation of an open rdf term """ raise NotImplementedError("Failed to implement 'toNTriples' on instance of type %s" % type(self).__name__) class Resource(Value): __slots__ = () pass class URI(Resource): """ Lightweight implementation of the class 'URI'. """ __slots__ = ('_uri', '_is_canonical') _instances = weakref.WeakValueDictionary() def __new__(cls, uri=None, namespace=None, localname=None, canonical=True): if isinstance(uri, URI): if not canonical or uri._is_canonical: return uri uri = uri.uri elif uri is None and namespace is not None: uri = namespace + (localname or '') if uri is None: raise ValueError('Either URI or namespace is required.') if canonical: result = URI._instances.get(uri) if result is not None: return result result = super(URI, cls).__new__(cls) if canonical: URI._instances[uri] = result return result def __init__(self, uri=None, namespace=None, localname=None, canonical=False): if isinstance(uri, URI): uri = uri.uri if uri is None and namespace is not None: uri = namespace + (localname or '') if uri and uri[0] == '<' and uri[len(uri) - 1] == '>': # be kind and trim the uri: uri = uri[1:-1] self._uri = uri self._is_canonical = canonical def get_cmp_key(self): return URI_CMP_KEY, self.uri def getURI(self): """ Return the URI (string) for 'self'. This method is typically overloaded by subclasses, which may use lazy evaluation to retrieve the string. """ return self._uri uri = property(getURI) def getValue(self): return self.getURI() value = property(getValue) def getLocalName(self): pos = uris.getLocalNameIndex(self.getURI()) return self.uri[pos:] localname = property(getLocalName) def getNamespace(self): pos = uris.getLocalNameIndex(self.getURI()) return self.uri[:pos] def split(self): """ Split into a namespace + local name pair. """ pos = uris.getLocalNameIndex(self.uri) return self.uri[:pos], self.uri[pos:] namespace = property(getNamespace) def toNTriples(self): """ Return an NTriples representation of a resource, in this case, wrap it in angle brackets. """ return strings.encode_ntriple_uri(self.uri) def to_json_ld_key(self): """ Converts to a string to be used as a JSON-LD key. """ return self.uri def to_json_ld(self): """ Converts to an object to be used as a JSON-LD value. """ return {"@id": self.uri} class BNode(Resource): """ A blank node. """ __slots__ = ('id',) def __init__(self, id=None): """ Create a blank node. :param id: Node identifier, if not supplied one will be generated. """ if id is None: id = 'b' + hex(builtins.id(self)) self.id = id def getId(self): """ Get the identifier of this blank node. """ return self.id getID = getId getValue = getID def get_cmp_key(self): return BNODE_CMP_KEY, self.getId() def toNTriples(self): return "_:%s" % self.getId() def to_json_ld_key(self): """ Converts to a string to be used as a JSON-LD key. """ return self.toNTriples() def to_json_ld(self): """ Converts to an object to be used as a JSON-LD value. """ return {"@id": self.toNTriples()} @python_2_unicode_compatible class Namespace(object): """ """ def __init__(self, prefix, name): self.setPrefix(prefix) self.setName(name) def getName(self): """ Gets the name of the current namespace (i.e. it's URI). """ return self.name def setName(self, name): self.name = name def getPrefix(self): """ Gets the prefix of the current namespace. """ return self.prefix def setPrefix(self, prefix): self.prefix = prefix def __str__(self): """ Return an odd name (that's what the RDF4J code does). """ return self.prefix + " :: " + self.name
26.14902
114
0.580834
815
6,668
4.554601
0.265031
0.025862
0.02667
0.016164
0.27236
0.256735
0.236261
0.190194
0.163793
0.155711
0
0.005554
0.29799
6,668
254
115
26.251969
0.787439
0.226455
0
0.226563
0
0
0.032688
0
0
0
0
0
0
1
0.265625
false
0.007813
0.0625
0.09375
0.679688
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
6b79a8d3d15995a2a48974a4be33fc7c2168a05d
616
py
Python
app/main/model/deal_investor.py
luke-truitt/room40-underground
174f57e0aa4b04bb7c983e10aaf4f4af6589d478
[ "MIT" ]
null
null
null
app/main/model/deal_investor.py
luke-truitt/room40-underground
174f57e0aa4b04bb7c983e10aaf4f4af6589d478
[ "MIT" ]
null
null
null
app/main/model/deal_investor.py
luke-truitt/room40-underground
174f57e0aa4b04bb7c983e10aaf4f4af6589d478
[ "MIT" ]
1
2021-07-21T13:36:13.000Z
2021-07-21T13:36:13.000Z
from .. import db, flask_bcrypt import datetime import jwt from app.main.model.blacklist import BlacklistToken from ..config import key class DealInvestor(db.Model): """ DealInvestor Model is used to link deals to their respective investors """ __tablename__ = "deal_investor" id = db.Column(db.Integer, primary_key=True, autoincrement=True) deal_id = db.Column(db.Integer, db.ForeignKey('deal.id')) investor_id = db.Column(db.Integer, db.ForeignKey('company.id')) amount = db.Column(db.Integer) investment_type = db.Column(db.String(255)) fund_invested = db.Column(db.String(255))
36.235294
82
0.733766
87
616
5.068966
0.482759
0.108844
0.136054
0.154195
0.306122
0.219955
0.14059
0
0
0
0
0.011429
0.147727
616
16
83
38.5
0.828571
0.113636
0
0
0
0
0.055762
0
0
0
0
0
0
1
0
false
0
0.384615
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
6b80b87f8ee4f931305c1464b4141765f243a780
642
py
Python
py-lesson/HW4/Q3.py
jessie-233/python-exercise
097f60978d316a7380e85686e0403cdf1ac482e9
[ "MIT" ]
null
null
null
py-lesson/HW4/Q3.py
jessie-233/python-exercise
097f60978d316a7380e85686e0403cdf1ac482e9
[ "MIT" ]
1
2020-10-01T13:52:54.000Z
2020-10-01T13:54:37.000Z
py-lesson/HW4/Q3.py
jessie-233/python-exercise
097f60978d316a7380e85686e0403cdf1ac482e9
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[1]: days_dict = {1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31,8:31, 9:30, 10:31, 11:30, 12:31} start_week = {1:3, 2:6, 3:0, 4:3, 5:5, 6:1, 7:3, 8:6, 9:2, 10:4, 11:0, 12:2} with open('Q3-output.txt', 'w') as f: for i in range(1,13): print('\n\n\t\t\t%d月'%i, file = f) print('日\t一\t二\t三\t四\t五\t六', file = f) for k in range(start_week[i]): print('\t', end = '', file = f) for j in range(1, days_dict[i]+1): print(j, '\t', end = '', file = f) if (start_week[i]+j) % 7 == 0: print('\n', file = f) # In[ ]:
23.777778
86
0.457944
134
642
2.156716
0.410448
0.086505
0.062284
0.062284
0
0
0
0
0
0
0
0.168142
0.29595
642
26
87
24.692308
0.471239
0.074766
0
0
0
0
0.088737
0
0
0
0
0
0
1
0
false
0
0
0
0
0.416667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
6b81d7df4138d109227c296d3f36cc5b8c75cc78
17,615
py
Python
tests/test_hvactemplatesystempackagedvav.py
marcelosalles/pyidf
c2f744211572b5e14e29522aac1421ba88addb0e
[ "Apache-2.0" ]
19
2015-12-08T23:33:51.000Z
2022-01-31T04:41:10.000Z
tests/test_hvactemplatesystempackagedvav.py
marcelosalles/pyidf
c2f744211572b5e14e29522aac1421ba88addb0e
[ "Apache-2.0" ]
2
2019-10-04T10:57:00.000Z
2021-10-01T06:46:17.000Z
tests/test_hvactemplatesystempackagedvav.py
marcelosalles/pyidf
c2f744211572b5e14e29522aac1421ba88addb0e
[ "Apache-2.0" ]
7
2015-11-04T02:25:01.000Z
2021-12-08T03:14:28.000Z
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.hvac_templates import HvactemplateSystemPackagedVav log = logging.getLogger(__name__) class TestHvactemplateSystemPackagedVav(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile.mkstemp() def tearDown(self): os.remove(self.path) def test_create_hvactemplatesystempackagedvav(self): pyidf.validation_level = ValidationLevel.error obj = HvactemplateSystemPackagedVav() # alpha var_name = "Name" obj.name = var_name # object-list var_system_availability_schedule_name = "object-list|System Availability Schedule Name" obj.system_availability_schedule_name = var_system_availability_schedule_name # real var_supply_fan_maximum_flow_rate = 0.0001 obj.supply_fan_maximum_flow_rate = var_supply_fan_maximum_flow_rate # real var_supply_fan_minimum_flow_rate = 0.0 obj.supply_fan_minimum_flow_rate = var_supply_fan_minimum_flow_rate # alpha var_supply_fan_placement = "DrawThrough" obj.supply_fan_placement = var_supply_fan_placement # real var_supply_fan_total_efficiency = 0.50005 obj.supply_fan_total_efficiency = var_supply_fan_total_efficiency # real var_supply_fan_delta_pressure = 0.0 obj.supply_fan_delta_pressure = var_supply_fan_delta_pressure # real var_supply_fan_motor_efficiency = 0.50005 obj.supply_fan_motor_efficiency = var_supply_fan_motor_efficiency # real var_supply_fan_motor_in_air_stream_fraction = 0.5 obj.supply_fan_motor_in_air_stream_fraction = var_supply_fan_motor_in_air_stream_fraction # alpha var_cooling_coil_type = "TwoSpeedDX" obj.cooling_coil_type = var_cooling_coil_type # object-list var_cooling_coil_availability_schedule_name = "object-list|Cooling Coil Availability Schedule Name" obj.cooling_coil_availability_schedule_name = var_cooling_coil_availability_schedule_name # object-list var_cooling_coil_setpoint_schedule_name = "object-list|Cooling Coil Setpoint Schedule Name" obj.cooling_coil_setpoint_schedule_name = var_cooling_coil_setpoint_schedule_name # real var_cooling_coil_design_setpoint = 13.13 obj.cooling_coil_design_setpoint = var_cooling_coil_design_setpoint # real var_cooling_coil_gross_rated_total_capacity = 14.14 obj.cooling_coil_gross_rated_total_capacity = var_cooling_coil_gross_rated_total_capacity # real var_cooling_coil_gross_rated_sensible_heat_ratio = 0.75 obj.cooling_coil_gross_rated_sensible_heat_ratio = var_cooling_coil_gross_rated_sensible_heat_ratio # real var_cooling_coil_gross_rated_cop = 0.0001 obj.cooling_coil_gross_rated_cop = var_cooling_coil_gross_rated_cop # alpha var_heating_coil_type = "HotWater" obj.heating_coil_type = var_heating_coil_type # object-list var_heating_coil_availability_schedule_name = "object-list|Heating Coil Availability Schedule Name" obj.heating_coil_availability_schedule_name = var_heating_coil_availability_schedule_name # object-list var_heating_coil_setpoint_schedule_name = "object-list|Heating Coil Setpoint Schedule Name" obj.heating_coil_setpoint_schedule_name = var_heating_coil_setpoint_schedule_name # real var_heating_coil_design_setpoint = 20.2 obj.heating_coil_design_setpoint = var_heating_coil_design_setpoint # real var_heating_coil_capacity = 21.21 obj.heating_coil_capacity = var_heating_coil_capacity # real var_gas_heating_coil_efficiency = 0.5 obj.gas_heating_coil_efficiency = var_gas_heating_coil_efficiency # real var_gas_heating_coil_parasitic_electric_load = 0.0 obj.gas_heating_coil_parasitic_electric_load = var_gas_heating_coil_parasitic_electric_load # real var_maximum_outdoor_air_flow_rate = 0.0 obj.maximum_outdoor_air_flow_rate = var_maximum_outdoor_air_flow_rate # real var_minimum_outdoor_air_flow_rate = 0.0 obj.minimum_outdoor_air_flow_rate = var_minimum_outdoor_air_flow_rate # alpha var_minimum_outdoor_air_control_type = "FixedMinimum" obj.minimum_outdoor_air_control_type = var_minimum_outdoor_air_control_type # object-list var_minimum_outdoor_air_schedule_name = "object-list|Minimum Outdoor Air Schedule Name" obj.minimum_outdoor_air_schedule_name = var_minimum_outdoor_air_schedule_name # alpha var_economizer_type = "FixedDryBulb" obj.economizer_type = var_economizer_type # alpha var_economizer_lockout = "NoLockout" obj.economizer_lockout = var_economizer_lockout # real var_economizer_maximum_limit_drybulb_temperature = 30.3 obj.economizer_maximum_limit_drybulb_temperature = var_economizer_maximum_limit_drybulb_temperature # real var_economizer_maximum_limit_enthalpy = 31.31 obj.economizer_maximum_limit_enthalpy = var_economizer_maximum_limit_enthalpy # real var_economizer_maximum_limit_dewpoint_temperature = 32.32 obj.economizer_maximum_limit_dewpoint_temperature = var_economizer_maximum_limit_dewpoint_temperature # real var_economizer_minimum_limit_drybulb_temperature = 33.33 obj.economizer_minimum_limit_drybulb_temperature = var_economizer_minimum_limit_drybulb_temperature # object-list var_supply_plenum_name = "object-list|Supply Plenum Name" obj.supply_plenum_name = var_supply_plenum_name # object-list var_return_plenum_name = "object-list|Return Plenum Name" obj.return_plenum_name = var_return_plenum_name # alpha var_supply_fan_partload_power_coefficients = "InletVaneDampers" obj.supply_fan_partload_power_coefficients = var_supply_fan_partload_power_coefficients # alpha var_night_cycle_control = "StayOff" obj.night_cycle_control = var_night_cycle_control # object-list var_night_cycle_control_zone_name = "object-list|Night Cycle Control Zone Name" obj.night_cycle_control_zone_name = var_night_cycle_control_zone_name # alpha var_heat_recovery_type = "None" obj.heat_recovery_type = var_heat_recovery_type # real var_sensible_heat_recovery_effectiveness = 0.5 obj.sensible_heat_recovery_effectiveness = var_sensible_heat_recovery_effectiveness # real var_latent_heat_recovery_effectiveness = 0.5 obj.latent_heat_recovery_effectiveness = var_latent_heat_recovery_effectiveness # alpha var_cooling_coil_setpoint_reset_type = "None" obj.cooling_coil_setpoint_reset_type = var_cooling_coil_setpoint_reset_type # alpha var_heating_coil_setpoint_reset_type = "None" obj.heating_coil_setpoint_reset_type = var_heating_coil_setpoint_reset_type # alpha var_dehumidification_control_type = "None" obj.dehumidification_control_type = var_dehumidification_control_type # object-list var_dehumidification_control_zone_name = "object-list|Dehumidification Control Zone Name" obj.dehumidification_control_zone_name = var_dehumidification_control_zone_name # real var_dehumidification_setpoint = 50.0 obj.dehumidification_setpoint = var_dehumidification_setpoint # alpha var_humidifier_type = "None" obj.humidifier_type = var_humidifier_type # object-list var_humidifier_availability_schedule_name = "object-list|Humidifier Availability Schedule Name" obj.humidifier_availability_schedule_name = var_humidifier_availability_schedule_name # real var_humidifier_rated_capacity = 0.0 obj.humidifier_rated_capacity = var_humidifier_rated_capacity # real var_humidifier_rated_electric_power = 0.0 obj.humidifier_rated_electric_power = var_humidifier_rated_electric_power # object-list var_humidifier_control_zone_name = "object-list|Humidifier Control Zone Name" obj.humidifier_control_zone_name = var_humidifier_control_zone_name # real var_humidifier_setpoint = 50.0 obj.humidifier_setpoint = var_humidifier_setpoint # alpha var_sizing_option = "Coincident" obj.sizing_option = var_sizing_option # alpha var_return_fan = "Yes" obj.return_fan = var_return_fan # real var_return_fan_total_efficiency = 0.50005 obj.return_fan_total_efficiency = var_return_fan_total_efficiency # real var_return_fan_delta_pressure = 0.0 obj.return_fan_delta_pressure = var_return_fan_delta_pressure # real var_return_fan_motor_efficiency = 0.50005 obj.return_fan_motor_efficiency = var_return_fan_motor_efficiency # real var_return_fan_motor_in_air_stream_fraction = 0.5 obj.return_fan_motor_in_air_stream_fraction = var_return_fan_motor_in_air_stream_fraction # alpha var_return_fan_partload_power_coefficients = "InletVaneDampers" obj.return_fan_partload_power_coefficients = var_return_fan_partload_power_coefficients idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debug(line.strip()) idf2 = IDF(self.path) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].name, var_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].system_availability_schedule_name, var_system_availability_schedule_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_maximum_flow_rate, var_supply_fan_maximum_flow_rate) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_minimum_flow_rate, var_supply_fan_minimum_flow_rate) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_placement, var_supply_fan_placement) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_total_efficiency, var_supply_fan_total_efficiency) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_delta_pressure, var_supply_fan_delta_pressure) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_motor_efficiency, var_supply_fan_motor_efficiency) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_motor_in_air_stream_fraction, var_supply_fan_motor_in_air_stream_fraction) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_type, var_cooling_coil_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_availability_schedule_name, var_cooling_coil_availability_schedule_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_setpoint_schedule_name, var_cooling_coil_setpoint_schedule_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_design_setpoint, var_cooling_coil_design_setpoint) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_gross_rated_total_capacity, var_cooling_coil_gross_rated_total_capacity) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_gross_rated_sensible_heat_ratio, var_cooling_coil_gross_rated_sensible_heat_ratio) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_gross_rated_cop, var_cooling_coil_gross_rated_cop) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_type, var_heating_coil_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_availability_schedule_name, var_heating_coil_availability_schedule_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_setpoint_schedule_name, var_heating_coil_setpoint_schedule_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_design_setpoint, var_heating_coil_design_setpoint) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_capacity, var_heating_coil_capacity) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].gas_heating_coil_efficiency, var_gas_heating_coil_efficiency) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].gas_heating_coil_parasitic_electric_load, var_gas_heating_coil_parasitic_electric_load) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].maximum_outdoor_air_flow_rate, var_maximum_outdoor_air_flow_rate) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].minimum_outdoor_air_flow_rate, var_minimum_outdoor_air_flow_rate) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].minimum_outdoor_air_control_type, var_minimum_outdoor_air_control_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].minimum_outdoor_air_schedule_name, var_minimum_outdoor_air_schedule_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_type, var_economizer_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_lockout, var_economizer_lockout) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_maximum_limit_drybulb_temperature, var_economizer_maximum_limit_drybulb_temperature) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_maximum_limit_enthalpy, var_economizer_maximum_limit_enthalpy) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_maximum_limit_dewpoint_temperature, var_economizer_maximum_limit_dewpoint_temperature) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].economizer_minimum_limit_drybulb_temperature, var_economizer_minimum_limit_drybulb_temperature) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].supply_plenum_name, var_supply_plenum_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].return_plenum_name, var_return_plenum_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].supply_fan_partload_power_coefficients, var_supply_fan_partload_power_coefficients) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].night_cycle_control, var_night_cycle_control) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].night_cycle_control_zone_name, var_night_cycle_control_zone_name) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].heat_recovery_type, var_heat_recovery_type) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].sensible_heat_recovery_effectiveness, var_sensible_heat_recovery_effectiveness) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].latent_heat_recovery_effectiveness, var_latent_heat_recovery_effectiveness) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].cooling_coil_setpoint_reset_type, var_cooling_coil_setpoint_reset_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].heating_coil_setpoint_reset_type, var_heating_coil_setpoint_reset_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].dehumidification_control_type, var_dehumidification_control_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].dehumidification_control_zone_name, var_dehumidification_control_zone_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].dehumidification_setpoint, var_dehumidification_setpoint) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_type, var_humidifier_type) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_availability_schedule_name, var_humidifier_availability_schedule_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_rated_capacity, var_humidifier_rated_capacity) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_rated_electric_power, var_humidifier_rated_electric_power) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_control_zone_name, var_humidifier_control_zone_name) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].humidifier_setpoint, var_humidifier_setpoint) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].sizing_option, var_sizing_option) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan, var_return_fan) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan_total_efficiency, var_return_fan_total_efficiency) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan_delta_pressure, var_return_fan_delta_pressure) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan_motor_efficiency, var_return_fan_motor_efficiency) self.assertAlmostEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan_motor_in_air_stream_fraction, var_return_fan_motor_in_air_stream_fraction) self.assertEqual(idf2.hvactemplatesystempackagedvavs[0].return_fan_partload_power_coefficients, var_return_fan_partload_power_coefficients)
65.240741
167
0.795572
2,052
17,615
6.295809
0.069688
0.155275
0.159842
0.127719
0.888304
0.786903
0.680161
0.55848
0.443533
0.252342
0
0.014618
0.153392
17,615
270
168
65.240741
0.851673
0.022424
0
0
0
0
0.038518
0.004196
0
0
0
0
0.293532
1
0.014925
false
0
0.039801
0
0.059701
0
0
0
0
null
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6b83d0d9417fbfeb8bd14b3ee42701ee5d08783b
43,043
py
Python
t01_final_story.py
fall-2018-csc-226/t04-master
cf62ad87451f4309c4c580767e9d725382b35d33
[ "MIT" ]
null
null
null
t01_final_story.py
fall-2018-csc-226/t04-master
cf62ad87451f4309c4c580767e9d725382b35d33
[ "MIT" ]
7
2018-09-19T15:37:58.000Z
2018-10-01T14:54:46.000Z
t01_final_story.py
fall-2018-csc-226/t04-master
cf62ad87451f4309c4c580767e9d725382b35d33
[ "MIT" ]
null
null
null
###################################################################### # Author: The Fall 2018 226 Class! # # Assignment: T01: Choose Your Own Adventure # # Purpose: To create a choose-your-own-adventure style game. # Each "twist" in the story is from a different group. The resulting story # will either be incoherently random, or entertainingly "Mad Lib" like. # Either way, it should be fun! ###################################################################### # Acknowledgements: # Original Author: Dr. Scott Heggen # # Inspired by https://www.cs.hmc.edu/twiki/bin/view/CS5/Week0ChoiceProblem ###################################################################### from time import sleep delay = 1.0 # change to 0.0 for testing/speed runs; larger for dramatic effect! dead = False # You start out not dead, which is good. injured = 0 # You start with 100% of your limbs! When this reaches two, you die! flashlight = 0 # You have no source of light! antisoftlock = 0 # For loops checkGlint = 0 # Tracking! checkPool = 0 # ^ # Asks the user to input their name. username = input("What do they call you, unworthy adversary? ") ######################################################################################################### # The following is the first part of the story. Don't change this section. print() print("Welcome,", username, ", to the labyrinth.") sleep(delay) print("Before you lies two paths. One path leads to treasures of unimaginable worth.") print("The other, certain death. Choose wisely.") print() sleep(delay * 2) print("You are in a dark cave. You can see nothing.") print("Staying here is certainly not wise. You must find your way out.") print() sleep(delay) ######################################################################################################### # This is an example chapter. Your story will follow a similar structure. # You will learn more by NOT copy and pasting this section. Write your section on your own, and when you get stuck, # refer to this code to help you get unstuck. Of course, raise your hand if you get really stuck. direction = input("Which direction would you like to go? [North/South/East/West]" ) if direction == "North": # Good choice! print("You are still trapped in the dark, but someone else is there with you now! I hope they're friendly...") sleep(delay) elif direction == "South": # Oh... Bad choice print("You hear a growl. Not a stomach growl. More like a big nasty animal growl.") sleep(delay) print("Oops. Turns out the cave was home to a nasty grizzly bear. ") print("Running seems like a good idea now. But... it's really, really dark.") print("You turn and run like hell. The bear wakes up to the sound of your head bouncing off a low stalactite. ") print("He eats you. You are delicious.") dead = True else: # Neutral choice print("You're in another part of the cave. It is equally dark, and equally uninteresting. Please get me out of here!") sleep(delay) if dead == True: print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() ######################################################################################################### # Christson & Alfaro # Refactored by Team 1 direction = input("Where do you want to go today?. Choose carefully hahaahhaha [Wakanda, New York, Asgard, Gotham City]") if direction == "Asgard": # Well done! print() print("Wow, I'm shocked!. Good Choice!") print() print() sleep(delay) print("Thor deems you worthy to fight by his side! Welcome to Asgard", username,) sleep(delay) elif direction == "Gotham City": #oh.. bad choice print() sleep(delay * 2) print("You find yourself in an dark alley, you hear two gunshots *bang, bang*") sleep(delay * 2) print("A man runs past you, no witnesses he says...") sleep (delay *2 ) print ("*Bang*") print(username,"You're Dead") dead = True elif direction == "Wakanda": #interesting choice print() name = input ("Are you a Wakanda citizen ?") if name == "Yes": sleep (delay *2 ) print("Welcome back, your family missed you", username,) else: sleep (delay *2 ) print ("You can't find Wakanda. You only see a rhino here") print("He looks friendly but this is boring") sleep (delay *2 ) else: #neutral choice print("You are in New York. Not much for you to do here") sleep (delay *2 ) print("Press the green button so you can see if you have better luck next time") sleep(delay * 2) if dead == True: print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() ######################################################################################################### # toktobaeva & coxb # Refactored by Team 2 print () print () direction = input ("As a Berean, no matter where you end up, you have to constantly make this hard decision: Go to dining or Go do homework, what do you say? [Go to dining/Go do homework]") if direction == "Go to dining": # Good choice! print () print("you get tired of this trivial cave and leave and head to dining to meet up friends") print () sleep(delay*3) elif direction == "Go do homework": # Bad choice! print () sleep (delay*3) print("You think you are making the right choice to conform to this capitalist world.") sleep(delay*3) print () print("When you, at heart, are a leftist Marxist") sleep(delay*3) print () print("You know you shouldn't be enslaved by the instiution that is generally accepted in the form of") sleep(delay*3) print () print("'all american college'") sleep(delay*3) print () print("You graduate with a degree.") sleep(delay*3) print () print("Work an 8-5 job.") sleep(delay*3) print () print("Have two children.") sleep(delay*3) print () print("Get old.") sleep(delay*3) print () print("And, when sitting at your white wood porch, looking at your old pictures, quietly sob realizing...") sleep(delay*3) print () print("that you should have gone to the dining hall") sleep(delay*3) print () print ("You die a victim of this machine.") print () print () dead = True else: sleep (delay) print () print("You are not a true Berean.") print () sleep(delay) if dead == True: sleep(delay) print("Oh no. You are dead. Bye.") quit() money = int(input ("How much is your family income?")) if money < 30000: sleep (delay) print () print ("Berea, berea, beloved") elif money > 30000: sleep (delay) print () print ("you don't belong here") dead = True else: sleep (delay) print ("illiterate. bye. *middle finger emoji* *clown emoji* *middle finger emoji*") if dead == True: print ("go back to the centre college where you belong.") quit () ######################################################################################################### # cullomn & coreass # Refactored by Team 3 print() print("You wake up in the middle of the night to footsteps coming down the hallway.") sleep (delay * 2) print() print("You could hide in the closet, go out the window, or go investigate.") print() choice = input("What do you want to do? (Please type closet, window, or investigate)") if choice == "window": #good choice print() print("You managed to land safely in a bush. And run to a neighbor's house to call the police.") sleep(delay) elif choice == "investigate": #bad choice print("While trying to investigate, you heard a loud bang.") print() sleep(delay) print("You got so startled that you tripped and fell down the stairs. Better luck next time!") dead = True else: # Neutral Choice print("After finding your way to the closet, the footsteps enter your room") print() print("You see the shadows of the invader's feet in front of the door.") sleep(delay) print() print("The footsteps slowly leave your room, and downstairs you hear the front door close.") print("You are safe and alone, but are they coming back?") if dead == True: print() print("Sorry you died, have a nice funeral! If you want to play again hit the green button.") quit() ######################################################################################################### # Morgan's & Matilda # Refactored by Team 4 #Sleep is between the lines to make it so a wall of text doesn't appear at once. print("You hear some sort of... Odd sound. Is that a dripping sound?") sleep(delay) print("It sounds like it's coming from a side path, though you were remaining on the main one.") sleep(delay) print("It might be rain from outside. Or, maybe even an underground oasis.") sleep(delay) print("Or, perhaps, something a lot more dangerous...") sleep(delay * 2) direction = input("What do you do? [Ignore, Investigate, Run like hell]") if direction == "Ignore": #Good choice! print("You carry on down the path, ignoring the strange sound.") sleep(delay) print("As you walk, you hear the sound of water rushing behind you.") sleep(delay) print("Glancing back, you notice that water had suddenly burst from the side tunnel into the other.") sleep(delay) print("Good thing you avoided that. Close call.") elif direction == "Investigate": #Bad choice! print("You decide, for some reason, to go check out the suspicious dripping sound.") sleep(delay) print("As you walk, you feel the droplets of water soak into your shirt, and a roaring sound fills you ears.") sleep(delay * 2) print("... Shit.") sleep(delay * 2) print("A sudden rush of water drags you along, and though you try and fight the current, it's no use.") sleep(delay) print("Guess this is the end.") dead=True else: #Guess what? TWO BAD ENDS. AHAHHAHA. print("Rather than doing either option that would be somewhat sensible, you make a horrible decision.") sleep(delay) print("Breaking out into a sprint, you start to run from that location.") sleep(delay) print("Frankly, the cave's floors are slick from water.") sleep(delay) print("You trip and fall, hitting your head on the rocky floor.") sleep(delay) print("As you start to lose consciousness, you hear the sound of a creature moving somewhere nearby.") sleep(delay) print("You're perfect prey like this.") dead=True if dead == True: sleep(delay) print("Ha! Guess that's the end. Good job, sucker.") quit() #'s Chapter print(" You hear an odd sound. You feel your way around and see that there are two options.") print (" Option 1: Investigate ") print ( "Option 2: Scale the cave wall and go through an opening in the cave") print ("Option 3:Stay where you are") direction= input(" Which choice do you make? [ Option 1, Option 2, Option 3]") if direction == "Option 1": print (" The odd sound belonged to an animal. You made for a tasty meal") dead=True sleep(delay) elif direction== "Option 2": print (" You made it to another part of the cave!") sleep(delay) print (" Unfortunately, you trip over a boulder, fall back through the opening, and you are now injured") dead=False else: print (" The noise is getting louder and you are still in danger.") sleep(delay) print ("However, it appears the darkenss of the cave is keeping you alive...for now ") dead= False if dead == True: print(" Looks like you've reached the end of the road. Better luck next time!") quit() ######################################################################################################### # Dunn & Dovranov # Refactored by Team 5 direction = input("Where do you want to go? [North/South/East/West]" ) if direction == "East": # Bad Choice print("You followed the light and it led to another person that was lost.") print("Slowly approaching the other person you fall and they now know they are not alone.") print("You are now injured and the other person is leaving you because of the noise.") print("After they have left you fall asleep.") sleep(delay) print("You awaken to the noise of bear that is approaching closer to you.") print("Unfortunately, you can't walk and the bear is close to you.") print("The bear is hungry and is looking for a delicious meal.") print("The bear begins to eat you.") print("You have one more chance to live. You see a rock.") userinput = input ("Can you grab it? [Yes/No]") if userinput == "Yes": print("You hit the bear and it runs off.") elif userinput == "No": print("The bear ate you.") else : print("The bear ate you.") dead = True elif direction == "West": # Good choice print("You are walking in the dark and you stumble across something on the ground.") print("You bend over and pick it up.") print("It is a flashlight!") print("However, you are still in the dark but now you have a flashlight to see more with so you do not fall.") sleep(delay) else: # Neutral choice print("You found a place to stay for the night until daytime.") sleep(delay) if dead == True: print("Oh no! You died. Try again by hitting the green play button.") quit() ######################################################################################################### # lovelle # Refactored by Team 6 direction = input("Which direction would you like to go? [North/South/East/West] ") if direction == "East": # Good choice print("You come upon an underground lake, fed by a glistening stream.") print("The sound of the water soothes your troubled nerves.") sleep(delay) elif direction == "South": # Bad choice print("Ever so suddenly, you find yourself surrounded by ogres twice your size.") print("They realize you are harmless and you catch your breath. It seems they might let you pass...") sleep(delay * 3) print("They strike up a song, ready to continue on their way.") print("Oh, but how loud their voices are! And you aren't feeling so good...") sleep(delay * 3) print("The leader asks you to rank the quality of their singing, on a scale of 1 to 10.") rating = int(input("What do you say? Choose wisely; your life depends on it... ")) if rating < 10: print("You fall to the ground, feeling the power of a cursed song. Looks like your time is up, friend.") dead = True else: print("The ogre thanks you for the complement and sends you on your merry way.") else: # Neutral choice print("Phew, you're still on solid ground. But still in the dark. Think fast!") sleep(delay) if dead == True: print("Oh no! You died. And what a shame it had to happen this way.") print("Better luck next time - try again by hitting the green play button!") quit() ######################################################################################################### # Eppersonb & Barnetth # Refactored by Team 7 print() print(username, "continues on their quest") sleep(delay) print("You continue your path in the forest") print("As you walk through the forest, you encounter a bear wearing a fez and sunglasses.") print( "You notice that the fez has the name 'Bosco' labeled on it. You deduce that this is the famous runaway circus bear, Bosco the Bear.") sleep(delay) print() print("However, Bosco has took notice of you and stands on his hind legs and takes interest in you.") print("You must make a choice, or it could end very badly for you!") choice = input("What would you like to do? [Entertain or Fight?]") if choice == "Fight": #Good Choice! print("You choose to engage in fisticuffs with Bosco the Bear. This seems like a very bad idea.") print() sleep(delay) print("Luckily for you, Bosco the Bear lived in the circus his whole life. He does not know how to fight.") print("Feeling intimated, Bosco the Bear flees. Dropping his fez and glasses.") print() print("You are free to continue on your journey while rocking the fez and glasses. Well at least you look nice.") print() elif choice == "Entertain": # Bad Choice print("Bosco the Bear is not amused with your performance.") print() sleep(delay) print("He ran away from the circus because he hated that life.") print("Your entertainment reminded him of that hatred. How inconsiderate of you.") print() sleep(delay) print("In a fit of rage, Bosco the Bear kills you with his bare hands.") print() dead = True else: #Neutral Choice print("Bosco the Bear is confused by your actions.") print("Bosco the Bear does not see you as a threat and leaves.") print() print("You are free to continue on your journey.") print() if dead == True: print("Oh no! You died. Better luck next time! Try again by hiting the green play button. ") quit() ######################################################################################################### # Guillermo & Tanner # Refactored by Team 8 #We pick it up from the point where you are in a dark room with a stranger. What happens next? decision = input("The stranger tells you that he knows the way out, but you have to follow his every word. What is your decision? [I trust you/No way, No thank you] ") if decision == "I trust you" : #Good choice! print("The stranger is overcome with joy, and hands you flashlight and a ham sandwich.") sleep(delay) elif decision == "No way" : #Bad choice... print("Your unwillingness to trust the stranger angers him. He begins to chase you through the dark cave, and you find a place to hide. You hide there for several days.") sleep(delay) print("After several days of hiding, you begin to fell fatigued. You lose consciousness, and the stranger is able to find your body and he dismembers you.") dead = True else: print("You respectfully decline his offer, and decide to wonder around in the dark by yourself. You wonder in the dark for hours, and make no progress. ") sleep(delay) if dead == True: print("You died, oh no! Try again by hitting the green button.") quit() ######################################################################################################### # hilljac & nudgarrobot # Refactored by Team 9 direction = input("Which direction would you like to go? [North/South/East/West]" ) if direction == "South": # Good choice! print("...") sleep(delay) print("Ooooooo boy!! You enter a room FILLED WITH GOLD!") sleep(delay) print("In addition to the gold, there seems to be a flashlight right in front of you! This is too good to be true!!") sleep(delay) itemChoice = input("What do you do? [Pocket the gold]/[Grab the flashlight]/[Try to grab both]") sleep(delay) if itemChoice == "Pocket the gold": print("You stuff your pockets as full as you can, and continue on your journey") sleep(delay*3) print("But wait!!") sleep(delay) print("Suddenly an enchanted skeleton appears, demanding that you return the gold, or pay with your life") skeletonChoice = input("Which will you do? [Keep the gold / Leave the gold]") sleep(delay) #branching good path if skeletonChoice == "Keep the gold": print("You decide to keep the gold for yourself, and attempt to run for your life. You escape the room, but in the process, the skeleton stabs you in the shoulder, injuring you for the duration of the adventure") elif skeletonChoice == "Leave the gold": print("You leave the gold and peacefully leave the room. Satisfied with your following his orders, the skeleton disappears. Your adventure continues") else: print("You have the confused the skeleton.") sleep(delay) print("Now the skeleton is angry!") sleep(delay*5) print("the skeleton has killed you...") sleep(delay) dead = True sleep(delay) if dead == True: print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() elif itemChoice == "Grab the flashlight": print("You decide to play it safe and only grab the flashlight. Obviously, the gold was a trap.") sleep(delay) print("You peacefully leave the room and your adventure continues. Also, now you have a flashlight!") elif itemChoice == "Try to grab both": print("You rush towards the motherlode in front of you!") sleep(delay) print("You grab the flashlight and start stuffing your pockets with as much gold as you can carry.") sleep(delay) print("You're gonna be so ri-") sleep(delay*2) print("everything is going dark...") sleep(delay*2) print("you're not sure, but you feel as though you have been stabbed from behind.") sleep(delay*2) print("You fall to the ground...") sleep(delay*2) dead = True sleep(delay) if dead == True: print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() else: print("You decide this whole situation is too good to be true, and is certainly a trap.") sleep(delay) print("You turn away and your adventure continues.") elif direction == "East": # Bad direction 2. Internal decisions can make it a trade, but an injury is normally guaranteed. print("You notice a rather low overhang in the darkness of the cave") sleep(delay) print("You're wary, but nothing's going to get done if you're overly hesitant.") sleep(delay) print("You crawl under the overhang and realize it's more of a short tunnel-") sleep(delay) print("It's very narrow, and you barely make your way out the other side.") sleep(delay*1.33) print("The air is has a notable chill and movement on the other side of the tunnel,") sleep(delay) print("and you hear a faint dripping reverberating through the space.") sleep(delay) if flashlight == 1: print("You sweep the flashlight over the space, but its beam doesn't reach the opposite wall.") sleep(delay*2) print("The stone in this part of the cave is smooth, seemingly worn down.") sleep(delay) print("The light does, however, illuminate a layer of mist swirling over a small pool") sleep(delay*1.33) print("The pool is perfectly still, and despite the darkness, is a deep, almost ethereal blue.") sleep(delay*2.33) print("In the far side of the cave, you see something small glisten as you sweep the flashlight over it.") choice = input("[Inspect pool]/[Check Glint]") #TODO Flesh out choices for flashlight-enabled play! if choice == "Check Glint": print("You carefully walk around the pool and inspect the base of the wall for anything unusual.") sleep(delay) print("Unlike most of the room, there are rough, broken rocks here and a crack in the wall.") sleep(delay) print("Sifting through the rocks and debris, you find a kind of cup--") sleep(delay) print("The cup is shaped in such a way as to resemble a stemless goblet.") sleep(delay) print("It's inlaid with small gemstones, and strange symbols mark its surface.") sleep(delay) print("You decide that it's worth keeping.") checkGlint = 1 chalice = 1 elif choice == "Inspect pool": checkPool = 1 print("You walk up to the lip of the pool. As you approach, the mist recedes.") sleep(delay) print("Thick and unnatural, the mist seems almost to pulse as you draw near.") sleep(delay) print("Upon closer observation, the pool is by no means water-") sleep(delay) print("Instead, it's a thinner liquid, so much so that the edge seems at times to blur with the mist above it.") sleep(delay) print("As you remain by the edge, the mist seems to grow more agitated in its swirling.") sleep(delay) if checkGlint == 1: choice = input("[Collect from Pool]/[Touch Pool]/[Remain Motionless]/[Retreat]") else: choice = input("[Check Glint]/[Touch Pool]/[Remain Motionless]/[Retreat]") if choice == "Touch Pool": print("You dip your hand into the crystal clear liquid.") sleep(delay) print("It feels strange, as if it were fine silk that was impossible to hold.") sleep(delay) print("Suddenly, you feel something coil around your wrist") sleep(delay) print("But the pool is still perfectly clear, and you see nothing.") sleep(delay) print("In panic you try to wrest your arm free, but only throw yourself off balance.") sleep(delay) print("Your other arm plunges into the pool as you try to steady yourself") sleep(delay) print("You claw at your bound wrist, trying to remove the invisible restraint") sleep(delay) print("But your hand finds nothing to grasp.") sleep(delay) print("You struggle helplessly against the swirling fluid, which is now pulling your arms deeper") sleep(delay) print("Absorbed in your struggle, you notice the mist too late--") sleep(delay) print("It has rolled forward, and is upon you, enveloping you.") sleep(delay) print("Forced to breathe it in, the last of your strength drains away") sleep(delay) print("As your vision slowly goes black, the last you feel is the soft, silky feeling of the pool's embrace.") sleep(delay) sleep(delay) dead = True elif choice == "Check Glint": print("You carefully walk around the pool and inspect the base of the wall for anything unusual.") sleep(delay) print("Unlike most of the room, there are rough, broken rocks here and a crack in the wall.") sleep(delay) print("Sifting through the rocks and debris, you find a kind of cup--") sleep(delay) print("The cup is shaped in such a way as to resemble a stemless goblet.") sleep(delay) print("It's inlaid with small gemstones, and strange symbols mark its surface.") sleep(delay) print("You decide that it's worth keeping, but upon taking it the wall behind caves in--") sleep(delay) print("You're blinded by light pouring through the opening the cave in created.") sleep(delay) print("When you can see again, you realize you're looking out over a range of mountains.") sleep(delay) print("Far from being deep underground, you had been trapped in the top of a mountain!") sleep(delay) print("You step out and breathe a sigh of relief in the clean mountain air.") checkGlint = 1 chalice = 1 else: print("If you're seeing this, you've probably referred to one of our placeholders!") print("While we intend to flesh these out later, at present it would be detrimental") print("to assignment deadlines! Speaking of deadlines, this is one! Have fun replaying!") dead = True else: print("Although the room is still too dark to see anything, the cavern feels immense.") sleep(delay) print("The cave floor under you feels smoother than the rest of the cave so far.") print("You place a hand on the wall to ground yourself- In the pitch blackness, you feel you could easily lose yourself.") sleep(delay*1.33) print("The wall is angled inward, and is just as smooth as the floor.") print("You don't particularly feel the space inviting...") sleep(delay*2) print("...But you still need to find a way out of here.") while antisoftlock == 0: choice = input("[Follow wall]/[Venture into dark]/[Retreat through tunnel]") if choice == "Follow wall": print("Placeholder text, you follow the wall.") antisoftlock = antisoftlock + 1 elif choice == "Venture into dark": print("Placeholder text, you leave the wall and walk into the inky blackness.") antisoftlock = antisoftlock + 1 elif choice == "Retreat through tunnel": print("Placeholder text. The tunnel is too wide to retreat through without forcing yourself through.") else: print("If you're seeing this, you've probably referred to one of our placeholders!") print("(Or just something that doesn't exist!)") print("While we intend to flesh these out later, at present it would be detrimental") print("to assignment deadlines! Speaking of deadlines, this is one! Have fun replaying!") dead = True else: # Neutral choice print("You're in another part of the cave. It is equally dark, and equally uninteresting. Please get me out of here!") sleep(delay) if dead == True: print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() ######################################################################################################### # jamalie & juem # Refactored by Team 10 direction = input("There is a river in your path, what would you do to cross the river? (swim, make a bridge,etc)") sleep(delay) if direction == "make a bridge": # this is the best choice! print("Well done, you have made a wise choice") print("you reward is that you will survive and explore more of the jungle") sleep(delay) elif direction == "swim": # surprisingly, this is a bad choice! print("Oh,no! Just like Goblet of Fire, there are deadly mermaids looking for fresh blood") print("you will be dragged down the ocean to be eaten at a feast") sleep(delay*3) print("Now you're in their territory, you see some Gillyweeds just next to where you're trap") sleep(delay*3) print("You should be careful with eating Gillyweed") direction = int(input("You have the option to eat between 1-3 strands of Gillyweed, what will you do?")) if direction <= 2: # Good idea print("Good job! now you have more strength and you can breath under water!") sleep(delay*3) print("fight them and survive") elif direction > 2 and direction <= 3: # this is a bad idea print("Too much Gillyweed will cause suffocation!") dead = True sleep(delay*5) else: # We would like the user to use whole number print("Since you did not choose from the given numbers, your only chance is to fight and survive") else: # this is a neutral choice! print("Well done for the creativity! you crossed the river!") sleep(delay*3) print("but...") sleep(delay*3) print("you got injured for the hard work, so you can't move on and you need to rest by the river") sleep(delay) if dead == True: print("oops.. I guess that's all for you!") sleep(delay*3) print("you were not very successful this time") sleep(delay*3) print("see you in your next journey") ######################################################################################################### # nashab & phillipsvi # Refactored by Team 11 print() print("To your left, you notice a house. Curious... Looking around more, you see a cat behind you.") print("The cat has seven tails and a missing eye. You ponder for a moment. You feel sleepy.") sleep(delay * 2) print() direction = input ("What will you do? [House/Cat/Sleep]") if direction == "House": #bad choice print("You decide that you need help and make your way towards the house. The path is a bit rocky though...") sleep(delay) print("...") sleep(delay) print("......") sleep(delay) print(".........") sleep(delay * 2) print("Oh no! You tripped on a rock! It was so shocking, you die before you hit the ground.") dead = True elif direction == "Cat": # neutral choice print("The cat is just so damn intriguing, you can't help but examine it.") print("You stretch out your hand, and the cat nuzzles you, its several tails twitching affectionately.") print("This is nice, but accomplishes nothing.") sleep (delay) print() print ("You waste time loving the cat, but nothing gets done.") sleep (delay) dead == False else: print ("You disregaurd that because you fell asleep.") sleep (delay * 5) print ("You awake feeling refreshed.") dead == False if dead == True: print("What a sad way to die.") quit() ######################################################################################################### # prattw & phillipsde # Refactored by Team 12 print() print('An eerie box lays before you, and for some reason you are drawn to it.') print() print('As you draw closer you hear a voice in your head...') print() print('"In order to receive the treasures of the box you must reveal your deepest and darkest secret"') choice = input('Will you reveal your secret? [Yes/No]') if choice == "Yes" or choice == "Y": secret = input('Speak now and reveal the truth.') print(secret) print("The box opens and you reach inside to retrieve your treasure...") sleep(delay) print() print('''It's a flower with petals made of fire and a note that says, "It's a me, copyright."''' ) sleep(delay) print() print('Confused by the note, you take your reward and move on.') print() sleep(delay) elif choice == "No" or choice == "N": death = input('Will you open the box? [Yes/No]') if death == "Yes": print('You attempt to open the box but you become consumed by a deadly darkness that envelops your body.') print() print('You died. LOL') revive=input("would You like to restart") if revive=="Yes": riddle=input("What starts with 'e' ends with 'e' and contains one letter? " "[a/an]") if riddle=="envelope": print("you live good job but you don't get the treasure") if revive=="No": print("ah its your choice") quit() elif death == "No": print('You decide not to open the box.') print() print('You feel like you have avoided some mysterious danger but missed out on some sweet loot.') else: print("You walk away") #hi ######################################################################################################### # mayerss & kinyunaa # Refactored by Team 13 jump = input("which direction would you like to go?[jump/stay/parachute]") if jump == "jump": #bad choice print("you fall from the sky and land on your head..") print("your skull burst open and your brains spread everywhere") print("your chances of survival are zero") print("youre dead meat") dead = True sleep(delay) elif jump == "parachute": #good choice print("Open your parachute at approximately 1000 feet and you avoid injury") print("Congratulations you passed your parachute test today!") else: print("you decided to stay. so now you are alone in the cave and have to find your way out") if dead == True: print("You died at least you dont have to take 226 anymore :)") ######################################################################################################### # stettner & vankirk # Refactored by Team 14 direction = input(" You see a ladder in front of you and hear Water to the right. Do you want to go for a Swim or Climb the ladder? " "[Swim, Climb]") print() if direction == "Climb": print(" When you reach the top of the ladder you come face to face with a demented clown") print("The clown jumps at you causing you to fall back and break your right arm but as you were falling you caught a glimpse " "of a tunnel to your left.") sleep(delay) direction == input (" Would you like to take a Hike or go for a Swim? [Hike, Swim]") elif direction == "Swim": print("As you go into the water you see a faint outline of a hole accros from you and you begin to swim towards it.") print("With your nose almost even with the watter you are able to fit through the hole.") sleep(delay) if direction == "Hike": sleep(delay) print("As you go down the path to your left, you hear a large form coming for you. " "You start running instinctively but you are not fast enough... ") dead = True else: print("That was not an option!") dead= True if dead == True: sleep(delay) print("Oh no! You died. Better luck next time! Try again by hitting the green play button. ") quit() ######################################################################################################### # stetzera and whitfordr # Refactored by Team 15 print() print("A figure emerges from the shadows, hunched and withered. Her single good eye turns to face you -- a witch!") sleep(delay) print("Two more eyes blink out of the darkness, the witch's black cat slinking their way out from around the hem of her dress.") sleep(delay) #Exposition for the upcoming choices. choice = input("The witch stares at you, blocking the way forward. What do you do? [Pet the cat/Attack the witch/Run away]") if choice == "Pet the cat": #Cats always equal best choice. print("You kneel down, holding out a hand to the cat.") print("The kitty pads forward, sniffing at you...") sleep(delay *5) print("The little black cat purrs.") print("With a throaty laugh the witch shuffles to the side, apparently trusting her cat's judgement. You're free to go!") elif choice == "Attack the witch": #What sort of idiot attacks a mysterious woman with a cat? How rude. print("Fearing for your life -- it's a witch, who trusts witches? -- you pull out a dagger from the sheathe at your belt.") print("With a echoing bellow you rush forward, only to find yourself frozen in place.") print("A hex!") dead = True elif choice == "Run away": #Arguably the most rational. print("Not your circus, not your monkeys.") print("You just turn around, avoid eye contact and meander back into the darkness of the cave from whence you came.") else: #Neutral/indecisive choice. print("You find yourself full of strange thoughts, pulled backwards into the labyrinth once more.") sleep(delay) if dead == True: print("Your muscles lock up, which, unfortunately, includes your heart.") sleep(delay) print("As your lifeless body falls to the ground, the witch and cat both turn, melting back into the shadows of the cave.") print("Serves you right for attacking a mostly-defenseless old woman.") print("Better luck next time! Try again by hitting the green play button.") quit() ######################################################################################################### # Refactored by Team 16 print() print("Deeper in the cave, you hear the sound of someone crying!") sleep(delay) print("As you investigate the noise, you discover that it is coming from a little girl in a pink dress.") sleep(delay) choice = input("She looks up at you tearfully, huddled against the wall. What do you do? [Pick her up/Interrogate her/Back away slowly]") if choice =="Interrogate her": print("Frankly you find this to be a bit suspect. What's a little kid doing in some kind of creepy magic cave?") sleep(delay) print("You point an accusatory finger at her and ask what her deal is") print("she immediately stops crying and looks grumpy instead. She sticks her tongue out at you and turns into a bat, flying away") print("Welp. guess you dodged that bullet.") elif choice =="Back away slowly": print("Ok you never signed up to be a childcare service. This is someone else's problem. You turn and leave") sleep(delay) print("The little girl looks at you incredulously but doesn't stop you") elif choice =="Pick her up": print("Despite your best efforts to calm her, the girl keeps crying. ...but after a moment, her cries begin to change.") sleep(delay) print("you realize she is laughing just as sharp fangs pierce your neck. You fall to the ground in surprise") print("As you look up, you realize that her eyes have turned deep red! Vampire!") dead = True else: print("Before you can decide what to do about the little kid, the ground collapses beneath you") sleep(delay) print("You find yourself in a totally different tunnel. A bit startled, but miraculously unhurt.") if dead == True: print("As your consiousness fades away, her giggles continue.") print("This is what you get for trying to help kids lost in caves apparently") print("Better luck next time! Try again by hitting the green play button.") quit() ######################################################################################################### # westth & whitakerj # Refactored by Team 17 Move = input("You see a cell phone up ahead. Do you want to pick it up, leave it where it is, or try to watch youtube videos? Type pick up, leave it or youtube, please. ") if Move == "pick up" or "Pick up": #This will be good later on. To call for help. print("Since you did not turn it on this could be helpful in the future.") sleep(delay) elif Move == "youtube" or "Youtube": #Oh no... this isn't going to be good print("Loud volume came out of the speakers, it was a bears mating call, the bear was NOT happy that you were not another bear.") sleep(delay) dead = True else : #Nothing happens, the volume doesn't turn on and you can't call for help later print("You left the phone. Oh well.") if dead == True: print("Oh no, your dead by a mating bear.") quit()
41.952242
224
0.621541
6,239
43,043
4.288027
0.202276
0.067656
0.051583
0.012559
0.202557
0.142451
0.113819
0.113819
0.104287
0.099353
0
0.004749
0.241758
43,043
1,025
225
41.993171
0.814965
0.069582
0
0.489796
0
0.063776
0.620349
0.004187
0
0
0
0.000976
0
1
0
false
0.002551
0.001276
0
0.001276
0.482143
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
6b8eb68d651fe2f3973d6258338aed3f82e05c3d
90
py
Python
tawsocks/constant.py
comeacrossyun/skyun
96ef2e98da2826863850c8b917bf1cba8a8a796b
[ "MIT" ]
1
2021-05-23T15:50:25.000Z
2021-05-23T15:50:25.000Z
tawsocks/constant.py
comeacrossyun/skyun
96ef2e98da2826863850c8b917bf1cba8a8a796b
[ "MIT" ]
null
null
null
tawsocks/constant.py
comeacrossyun/skyun
96ef2e98da2826863850c8b917bf1cba8a8a796b
[ "MIT" ]
null
null
null
#!/usr/bin/env python # @Time : 2019-06-03 # @Author : hongshu BUFF_SIZE = 32 * 1024
15
23
0.611111
14
90
3.857143
1
0
0
0
0
0
0
0
0
0
0
0.2
0.222222
90
5
24
18
0.571429
0.677778
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6ba0b0cb88433c042ca25747c1498b6fe7781f52
251
py
Python
pages/blender-scripts/simple-blocks.py
makersall/learn-python-blender
45f82f32a9b5d9fad6275d8912d5828a6d45b727
[ "MIT" ]
null
null
null
pages/blender-scripts/simple-blocks.py
makersall/learn-python-blender
45f82f32a9b5d9fad6275d8912d5828a6d45b727
[ "MIT" ]
null
null
null
pages/blender-scripts/simple-blocks.py
makersall/learn-python-blender
45f82f32a9b5d9fad6275d8912d5828a6d45b727
[ "MIT" ]
null
null
null
import bpy from mathutils import * D = bpy.data C = bpy.context for i in range(0,3): bpy.ops.mesh.primitive_cube_add(location=(1, 2, i)) # Now all I need to be able to do is add a mouseclick and a control z command in blender, and I'm good to go
27.888889
108
0.713147
53
251
3.339623
0.754717
0
0
0
0
0
0
0
0
0
0
0.019901
0.199203
251
9
108
27.888889
0.860697
0.422311
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
6ba48e7128b7a057d5f72e9950790980dd0f6128
1,246
py
Python
tests/molecular/reactions/reaction/fixtures/one_one_reaction.py
stevenbennett96/stk
6e5af87625b83e0bfc7243bc42d8c7a860cbeb76
[ "MIT" ]
null
null
null
tests/molecular/reactions/reaction/fixtures/one_one_reaction.py
stevenbennett96/stk
6e5af87625b83e0bfc7243bc42d8c7a860cbeb76
[ "MIT" ]
null
null
null
tests/molecular/reactions/reaction/fixtures/one_one_reaction.py
stevenbennett96/stk
6e5af87625b83e0bfc7243bc42d8c7a860cbeb76
[ "MIT" ]
null
null
null
import itertools as it import pytest import stk from ..case_data import CaseData @pytest.fixture def one_one_reaction( functional_group1, functional_group1_2, bond_order, periodicity, ): """ A :class:`.CaseData` instance. """ return CaseData( reaction=stk.OneOneReaction( functional_group1=functional_group1, functional_group2=functional_group1_2, bond_order=bond_order, periodicity=periodicity, ), new_atoms=(), new_bonds=( get_bond( functional_group1=functional_group1, functional_group2=functional_group1_2, bond_order=bond_order, periodicity=periodicity, ), ), deleted_atoms=tuple(it.chain( functional_group1.get_deleters(), functional_group1_2.get_deleters(), )), deleted_bonds=(), ) def get_bond( functional_group1, functional_group2, bond_order, periodicity, ): return stk.Bond( atom1=next(functional_group1.get_bonders()), atom2=next(functional_group2.get_bonders()), order=bond_order, periodicity=periodicity, )
21.482759
54
0.605939
118
1,246
6.059322
0.322034
0.268531
0.218182
0.134266
0.436364
0.293706
0.293706
0.293706
0.293706
0.293706
0
0.025611
0.310594
1,246
57
55
21.859649
0.806752
0.024077
0
0.444444
0
0
0
0
0
0
0
0
0
1
0.044444
false
0
0.088889
0.022222
0.177778
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6baddfd6c2bc7b76ee7cb32726d54db33f057904
583
py
Python
5/new code/OpenKE-OpenKE-PyTorch/openke/module/model/__init__.py
smurf-1119/knowledge-engeneering-experiment
7fd3647bfc5b05e5fd6f93fea324e7ec0d55d4a1
[ "MIT" ]
10
2021-11-19T06:24:51.000Z
2022-02-09T15:44:00.000Z
5/new code/OpenKE-OpenKE-PyTorch/openke/module/model/__init__.py
smurf-1119/knowledge-engeneering-experiment
7fd3647bfc5b05e5fd6f93fea324e7ec0d55d4a1
[ "MIT" ]
9
2021-10-01T11:06:27.000Z
2021-12-23T02:10:52.000Z
5/new code/OpenKE-OpenKE-PyTorch/openke/module/model/__init__.py
smurf-1119/knowledge-engeneering-experiment
7fd3647bfc5b05e5fd6f93fea324e7ec0d55d4a1
[ "MIT" ]
2
2021-09-14T04:08:36.000Z
2021-11-19T06:24:54.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .Model import Model from .TransE import TransE from .TransD import TransD from .TransR import TransR from .TransH import TransH from .DistMult import DistMult from .ComplEx import ComplEx from .RESCAL import RESCAL from .Analogy import Analogy from .SimplE import SimplE from .RotatE import RotatE __all__ = [ 'Model', 'TransE', 'TransD', 'TransR', 'TransH', 'DistMult', 'ComplEx', 'RESCAL', 'Analogy', 'SimplE', 'RotatE' ]
20.103448
38
0.722127
70
583
5.757143
0.271429
0.074442
0.119107
0
0
0
0
0
0
0
0
0
0.198971
583
29
39
20.103448
0.862955
0
0
0
0
0
0.118151
0
0
0
0
0
0
1
0
false
0
0.518519
0
0.518519
0.037037
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
6bd8f9bf02a6766c4d6a7fccca5eeed4aef8e654
9,225
py
Python
api/metadata_routes.py
ImagingDataCommons/ISB-CGC-API
d3207a6ada958ad5ac3cb8834b216ec1108dcf1c
[ "Apache-2.0" ]
null
null
null
api/metadata_routes.py
ImagingDataCommons/ISB-CGC-API
d3207a6ada958ad5ac3cb8834b216ec1108dcf1c
[ "Apache-2.0" ]
5
2020-07-07T23:45:21.000Z
2021-06-11T17:52:29.000Z
api/metadata_routes.py
ImagingDataCommons/ISB-CGC-API
d3207a6ada958ad5ac3cb8834b216ec1108dcf1c
[ "Apache-2.0" ]
2
2019-10-15T01:17:35.000Z
2021-04-05T19:54:12.000Z
# # Copyright 2019, Institute for Systems Biology # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from flask import jsonify from python_settings import settings from . metadata_views import get_versions, get_attributes, get_collections, get_analysis_results from flask import Blueprint metadata_bp = Blueprint('metadata_bp', __name__, url_prefix='/{}'.format(settings.API_VERSION)) logger = logging.getLogger(settings.LOGGER_NAME) @metadata_bp.route('/versions/', methods=['GET'], strict_slashes=False) def versions(): """Retrieve a list of IDC versions""" response = None try: results = get_versions() if 'message' in results: response = jsonify(results) response.status_code = results['code'] else: response = jsonify({ 'code': 200, **results }) response.status_code = 200 except Exception as e: logger.error("[ERROR] While retrieving IDC versions:") logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while retrieving the versions list.' }) response.status_code = 500 return response # @metadata_bp.route('/data_sources/', methods=['GET'], strict_slashes=False) # def data_sources(): # """Retrieve a list of IDC versions""" # # response = None # # try: # results = get_data_sources() # # if 'message' in results: # response = jsonify(results) # response.status_code = results['code'] # else: # response = jsonify({ # 'code': 200, # **results # }) # response.status_code = 200 # except Exception as e: # logger.error("[ERROR] While retrieving IDC versions:") # logger.exception(e) # response = jsonify({ # 'code': 500, # 'message': 'Encountered an error while retrieving the program list.' # }) # response.status_code = 500 # # return response @metadata_bp.route('/attributes', methods=['GET'], strict_slashes=False) def attributes(): """Retrieve a list of IDC versions""" response = None try: results = get_attributes() if 'message' in results: response = jsonify(results) response.status_code = results['code'] else: response = jsonify({ 'code': 200, **results }) response.status_code = 200 except Exception as e: logger.error("[ERROR] While retrieving IDC versions:") logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while retrieving the attributes.' }) response.status_code = 500 return response # @metadata_bp.route('/programs/', methods=['GET'], strict_slashes=False) # def programs(): # """Retrieve the list of programs and builds currently available for cohort creation.""" # # response = None # # try: # results = get_programs() # # if 'message' in results: # response = jsonify(results) # response.status_code = results['code'] # else: # response = jsonify({ # 'code': 200, # **results # }) # response.status_code = 200 # except Exception as e: # logger.error("[ERROR] While retrieving program information:") # logger.exception(e) # response = jsonify({ # 'code': 500, # 'message': 'Encountered an error while retrieving the program list.' # }) # response.status_code = 500 # # return response # # # @metadata_bp.route('/programs/<program_name>', methods=['GET'], strict_slashes=False) # def program_collections(program_name): # """Retrieve the list of collections and versions in program <program_name>.""" # response = None # # try: # # results = get_program_collections(program_name) # # if 'message' in results: # response = jsonify(results) # response.status_code = results['code'] # else: # response = jsonify({ # 'code': 200, # **results # }) # response.status_code = 200 # except Exception as e: # logger.error("[ERROR] While retrieving collection information:") # logger.exception(e) # response = jsonify({ # 'code': 500, # 'message': 'Encountered an error while retrieving the collection list.' # }) # response.status_code = 500 # # return response @metadata_bp.route('/collections/', methods=['GET'], strict_slashes=False) def collections(): """Retrieve the list of collections in some IDC versions """ response = None try: results = get_collections() if 'message' in results: response = jsonify(results) response.status_code = results['code'] else: response = jsonify({ 'code': 200, **results }) response.status_code = 200 except Exception as e: logger.error("[ERROR] While retrieving collection information:") logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while retrieving the collection list.' }) response.status_code = 500 return response @metadata_bp.route('/analysis_results/', methods=['GET'], strict_slashes=False) def analysis_results(): """Retrieve the list of analysis results in some IDC versions """ response = None try: results = get_analysis_results() if 'message' in results: response = jsonify(results) response.status_code = results['code'] else: response = jsonify({ 'code': 200, **results }) response.status_code = 200 except Exception as e: logger.error("[ERROR] While retrieving analysis results information:") logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while retrieving the analysis results list.' }) response.status_code = 500 return response @metadata_bp.route('/fields', methods=['GET'], strict_slashes=False) def fields(): """Retrieve a list of IDC versions""" response = jsonify({ 'code': 500, 'message': '/fields not yet supported.' }) return response response = None try: results = get_attributes() if 'message' in results: response = jsonify(results) response.status_code = results['code'] else: response = jsonify({ 'code': 200, **results }) response.status_code = 200 except Exception as e: logger.error("[ERROR] While retrieving IDC versions:") logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while retrieving the attributes.' }) response.status_code = 500 return response # @metadata_bp.route('/programs/<program_name>/<collection_name>/', methods=['GET'], strict_slashes=False) # def collection(program_name, collection_name): # """"Get a list of the available fields for a specific version of a collection.""" # response = None # # try: # results = get_collection_info(program_name, collection_name) # if results: # if 'message' in results: # response = jsonify(results) # response.status_code = 500 # # else: # code = 200 # response = jsonify({ # 'code': code, # **results # }) # response.status_code = 200 # else: # response = jsonify({ # 'code': 500, # 'message': 'Encountered an error while retrieving the collection list.' # }) # response.status_code = 500 # except Exception as e: # logger.error("[ERROR] While retrieving collection information:") # logger.exception(e) # response = jsonify({ # 'code': 500, # 'message': 'Encountered an error while retrieving the collection metadata.' # }) # response.status_code = 500 # # return response
29.854369
106
0.572358
925
9,225
5.610811
0.140541
0.083815
0.09711
0.086705
0.732755
0.698073
0.649518
0.63025
0.63025
0.614066
0
0.020389
0.319458
9,225
308
107
29.951299
0.806308
0.496369
0
0.795276
0
0
0.168376
0
0
0
0
0
0
1
0.03937
false
0
0.03937
0
0.125984
0.015748
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d41224f4ff45a38d4e8a034a7a6c35db41c23971
873
py
Python
packages/api-server/api_server/routes/building_map.py
cnboonhan/rmf-web
4389c53ef87e95c9a4bf1a6a72ed11f6f441a33f
[ "Apache-2.0" ]
null
null
null
packages/api-server/api_server/routes/building_map.py
cnboonhan/rmf-web
4389c53ef87e95c9a4bf1a6a72ed11f6f441a33f
[ "Apache-2.0" ]
null
null
null
packages/api-server/api_server/routes/building_map.py
cnboonhan/rmf-web
4389c53ef87e95c9a4bf1a6a72ed11f6f441a33f
[ "Apache-2.0" ]
null
null
null
from fastapi import Depends from rx import operators as rxops from api_server.base_app import BaseApp from api_server.fast_io import FastIORouter, SubscriptionRequest from api_server.models import BuildingMap from api_server.repositories.rmf import RmfRepository class BuildingMapRouter(FastIORouter): def __init__(self, app: BaseApp): super().__init__(tags=["Building"]) @self.get("", response_model=BuildingMap) async def get_building_map(rmf_repo: RmfRepository = Depends(app.rmf_repo)): """ Available in socket.io """ return await rmf_repo.get_bulding_map() @self.sub("", response_model=BuildingMap) def sub_building_map(_req: SubscriptionRequest): return app.rmf_events().building_map.pipe( rxops.filter(lambda x: x is not None) )
33.576923
84
0.68614
104
873
5.490385
0.5
0.049037
0.091068
0
0
0
0
0
0
0
0
0
0.230241
873
25
85
34.92
0.849702
0
0
0
0
0
0.009768
0
0
0
0
0
0
1
0.117647
false
0
0.352941
0.058824
0.647059
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d41dcd0b703b0cef481717fe5ec5b997bf1f78dd
19,894
py
Python
tools/w3af/w3af/plugins/bruteforce/form_auth.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
3
2019-04-09T22:59:33.000Z
2019-06-14T09:23:24.000Z
tools/w3af/w3af/plugins/bruteforce/form_auth.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
tools/w3af/w3af/plugins/bruteforce/form_auth.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
""" form_auth.py Copyright 2006 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af 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 General Public License for more details. You should have received a copy of the GNU General Public License along with w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from __future__ import with_statement import time from copy import deepcopy from itertools import izip, repeat import w3af.core.data.kb.knowledge_base as kb import w3af.core.controllers.output_manager as om import w3af.core.data.constants.severity as severity from w3af.core.data.fuzzer.utils import rand_alnum from w3af.core.data.fuzzer.mutants.querystring_mutant import QSMutant from w3af.core.data.fuzzer.mutants.postdata_mutant import PostDataMutant from w3af.core.data.dc.generic.form import Form from w3af.core.data.kb.vuln import Vuln from w3af.core.controllers.misc.diff import diff from w3af.core.controllers.misc.epoch_to_string import epoch_to_string from w3af.core.controllers.plugins.bruteforce_plugin import BruteforcePlugin from w3af.core.controllers.misc.fuzzy_string_cmp import fuzzy_equal from w3af.core.controllers.exceptions import BaseFrameworkException class form_auth(BruteforcePlugin): """ Bruteforce HTML form authentication. :author: Andres Riancho (andres.riancho@gmail.com) """ def __init__(self): BruteforcePlugin.__init__(self) self._found = set() def audit(self, freq, debugging_id=None): """ Tries to bruteforce a form auth. This is slow! :param freq: A FuzzableRequest :param debugging_id: The ID to use in the logs to be able to track this call to audit(). Plugins need to send this ID to the ExtendedUrllib to get improved logging. """ if freq.get_url() in self._already_tested: return mutant = form_pointer_factory(freq) if not self._is_login_form(mutant): # Not a login form, login forms have these fields: # * username/password # * password return self._already_tested.append(mutant.get_url()) try: session = self._create_new_session(mutant, debugging_id) except BaseFrameworkException, bfe: msg = 'Failed to create new session during form bruteforce setup: "%s"' om.out.debug(msg % bfe) return try: login_failed_bodies = self._id_failed_login_pages(mutant, session, debugging_id) except BaseFrameworkException, bfe: msg = 'Failed to ID failed login page during form bruteforce setup: "%s"' om.out.debug(msg % bfe) return try: self._signature_test(mutant, session, login_failed_bodies, debugging_id) except BaseFrameworkException, bfe: msg = 'Signature test failed during form bruteforce setup: "%s"' om.out.debug(msg % bfe) return user_token, pass_token = mutant.get_dc().get_login_tokens() # Let the user know what we are doing msg = 'Found a user login form. The form action is: "%s"' om.out.information(msg % mutant.get_url()) if user_token is not None: msg = 'The username field to be used is: "%s"' om.out.information(msg % user_token.get_name()) msg = 'The password field to be used is: "%s"' om.out.information(msg % pass_token.get_name()) msg = 'Starting form authentication bruteforce on URL: "%s"' om.out.information(msg % mutant.get_url()) start = time.time() if user_token is not None: generator = self._create_user_pass_generator(mutant.get_url()) else: generator = self._create_pass_generator(mutant.get_url()) self._bruteforce_pool(mutant, login_failed_bodies, generator, session, debugging_id) # Report that we've finished. took_str = epoch_to_string(start) msg = 'Finished bruteforcing "%s" (spent %s)' args = (mutant.get_url(), took_str) om.out.information(msg % args) def _create_new_session(self, mutant, debugging_id): """ Creates a new session in the xurllib. This session will be used to send HTTP requests and brute force the login. :param mutant: The form mutant :return: The session ID (a string) """ session = self._uri_opener.get_new_session() # And initialize the session (send a request so that in the response # we receive the cookie from the application and save it to the # cookiejar) self._uri_opener.send_mutant(mutant, grep=False, session=session, debugging_id=debugging_id) return session def _bruteforce_pool(self, mutant, login_failed_res, generator, session, debugging_id): args_iter = izip(repeat(mutant), repeat(login_failed_res), generator, repeat(session), repeat(debugging_id)) self.worker_pool.map_multi_args(self._brute_worker, args_iter, chunksize=100) def _bruteforce_test(self, mutant, login_failed_res, generator, session, debugging_id): for combination in generator: self._brute_worker(mutant, login_failed_res, combination, session, debugging_id) def _password_only_login(self, form): user_token, pass_token = form.get_login_tokens() if user_token is None: return True return False def _fill_form(self, form, username, password): """ Set the username and password fields to the provided params. Handle the case where the form only has a password field. :param form: The Form instance to brute-force :param username: Username value :param password: Password value :return: The form instance with the username (optional) and password """ user_token, pass_token = form.get_login_tokens() # Setup the data_container, remember that we can have password # only forms! if user_token is not None: form.set_login_username(username) form.set_login_password(password) return form def _id_failed_login_pages(self, mutant, session, debugging_id): """ Generate different response bodies that are the result of failed authentication. Return a list with at least the following response bodies: * Two response bodies for failed login using a randomly generated username and leaving the password field empty. This is stored in a FailedLoginPage instance. * Two response bodies for failed login using a randomly generated username and password. This is stored in a FailedLoginPage instance. """ # The result is going to be stored here login_failed_result_list = [] form = mutant.get_dc() self._true_extra_fields(form) # # Create the FailedLoginPage instance for randomly generated username # and password # random_user_pass = [] for _ in xrange(2): user, password = rand_alnum(8), rand_alnum(8) self._fill_form(form, user, password) response = self._uri_opener.send_mutant(mutant, grep=False, session=session, debugging_id=debugging_id) body = self._clean_body(response, user, password) random_user_pass.append(body) failed_login_page = FailedLoginPage(random_user_pass[0], random_user_pass[1]) login_failed_result_list.append(failed_login_page) # # Create the FailedLoginPage instance for randomly generated username # and empty password # random_user_empty_pass = [] for _ in xrange(2): user, password = rand_alnum(8), '' self._fill_form(form, user, password) response = self._uri_opener.send_mutant(mutant, grep=False, session=session, debugging_id=debugging_id) body = self._clean_body(response, user, password) random_user_empty_pass.append(body) failed_login_page = FailedLoginPage(random_user_empty_pass[0], random_user_empty_pass[1]) login_failed_result_list.append(failed_login_page) return login_failed_result_list def _signature_test(self, mutant, session, login_failed_bodies, debugging_id): """ Perform a signature test before starting the brute-force process. This test makes sure that the signatures captured in _id_failed_login_pages are usable. The basic idea is to send more failed login attempts and all should be identified as failed logins. :param mutant: The mutant that holds the login form :param session: The HTTP session / cookies to use in the test :param login_failed_bodies: The login failed bodies signatures :return: True if success, raises exception on failure """ tests = [(rand_alnum(8), rand_alnum(8)), (rand_alnum(8), '')] form = mutant.get_dc() for user, passwd in tests: self._fill_form(form, user, passwd) response = self._uri_opener.send_mutant(mutant, grep=False, session=session, debugging_id=debugging_id) body = self._clean_body(response, user, passwd) if self._matches_any_failed_page(body, login_failed_bodies): continue msg = 'Failed to generate a response that matches the failed login page' raise BaseFrameworkException(msg) return True def _matches_any_failed_page(self, resp_body, login_failed_result_list): """ :return: True if the resp_body matches the previously created responses that are stored in login_failed_result_list. """ for failed_login_page in login_failed_result_list: if failed_login_page.matches(resp_body): return True # I'm happy! The response_body *IS NOT* a failed login page. return False def _is_login_form(self, mutant): """ :return: True if this FuzzableRequest is a login form. """ form = mutant.get_dc() if isinstance(form, Form): return form.is_login_form() return False def _true_extra_fields(self, form): """ Some login forms have "extra" parameters. In some cases I've seen login forms that have an "I agree with the terms and conditions" checkbox. If w3af does not set that extra field to "true", even if I have the correct username and password combination, it won't perform a successful login. :return: A data_container that has all fields (other than the username and password) set to 1, """ user_token, pass_token = form.get_login_tokens() pass_field = pass_token.get_name() user_pass_fields = {pass_field} if user_token is not None: user_pass_fields.add(user_token.get_name()) for pname, value, path, value_setter in form.iter_setters(): if pname not in user_pass_fields: if not value: value_setter('1') def _clean_body(self, http_response, username, password): """ Remove username and password from HTTP response, just in case the application included them in the response. :param http_response: An HTTP response instance :param username: The username to replace :param password: The password to replace :return: A clean body (string) """ # # At some point this method was implemented as follows: # # strings_to_replace_list = [username, password] # return get_clean_body_impl(http_response, strings_to_replace_list) # # There is a complex interaction between cleaning the response body # and the diff() in FailedLoginPage.matches(). The problem is that the # bruteforce plugin will extract usernames and passwords from the HTML # thus doing a _clean_body() with username and password will "break" # one HTTP response in one way (clean with password A) and another HTTP # response in another way (clean with password B) thus making diff() # crazy # return http_response.body def _brute_worker(self, mutant, login_failed_result_list, combination, session, debugging_id): """ :param mutant: A Mutant holding a QsMutant of PostDataMutant, created using form_pointer_factory :param combination: A tuple with (user, pass) or a pass if this is a password only form. """ if mutant.get_url() in self._found and self._stop_on_first: return mutant = deepcopy(mutant) form = mutant.get_dc() if self._password_only_login(form): user = 'password-only-form' password = combination else: user, password = combination self._true_extra_fields(form) self._fill_form(form, user, password) resp = self._uri_opener.send_mutant(mutant, session=session, grep=False, debugging_id=debugging_id) body = self._clean_body(resp, user, password) if self._matches_any_failed_page(body, login_failed_result_list): return # # SUCCESS (most likely) # # The application is most likely answering with one of these # messages (first 3 are examples of errors, last is success): # # (f) "The username is valid but the password is invalid" # # (f) "Brute-force detected, user blocked" # # (f) "Brute-force detected, please complete this CAPTCHA form" # # (s) "Welcome Mr. Admin, how can I help?" # # Let's try to identify if we're in the (f) cases... # # This needs to be done in a different browser session, the old # session is (potentially) already logged in, sending a new # authentication request in that session will most likely # succeed with a 302 redirect to the user's home page or similar # new_session = self._create_new_session(mutant, debugging_id) password_1 = rand_alnum(8) form.set_login_password(password_1) verify_resp_1 = self._uri_opener.send_mutant(mutant, session=new_session, grep=False, debugging_id=debugging_id) password_2 = rand_alnum(8) form.set_login_password(password_2) verify_resp_2 = self._uri_opener.send_mutant(mutant, session=new_session, grep=False, debugging_id=debugging_id) body_1 = self._clean_body(verify_resp_1, user, password_1) body_2 = self._clean_body(verify_resp_2, user, password_2) potential_captcha_page = FailedLoginPage(body_1, body_2) if self._matches_any_failed_page(body, [potential_captcha_page]): om.out.debug('The form brute-force plugin detected a response' ' that might indicate that a user exists or CAPTCHA' ' protection is present. Please manually review HTTP' ' response with ID %s.' % verify_resp_2.id) return # # Found a valid username and password! # freq_url = mutant.get_url() self._found.add(freq_url) user_token, pass_token = form.get_login_tokens() if user_token is not None: desc = ('Found authentication credentials to: "%s". A correct' ' user and password combination is: %s/%s') desc %= (freq_url, user, password) else: # There is no user field! desc = ('Found authentication credentials to: "%s". The correct' ' password is: "%s".') desc %= (freq_url, password) v = Vuln.from_mutant('Guessable credentials', desc, severity.HIGH, resp.id, self.get_name(), mutant) v['user'] = user v['pass'] = password v['response'] = resp v['request'] = mutant.get_fuzzable_request() kb.kb.append(self, 'auth', v) om.out.vulnerability(desc, severity=severity.HIGH) def end(self): self._found = set() self._already_tested = [] self._already_reported = [] def form_pointer_factory(freq): if isinstance(freq.get_uri().querystring, Form): return QSMutant(freq) return PostDataMutant(freq) class FailedLoginPage(object): def __init__(self, body_a, body_b): self.body_a = body_a self.body_b = body_b self.diff_a_b = None def matches(self, query): """ This method is used to check if the `query` HTTP response body matches the failed login page instance. :param query: An HTTP response body :return: True if the `query` response body is equal to the failed login bodies which were received in __init__(). """ if self.body_a == query: return True if self.body_b == query: return True if not fuzzy_equal(self.body_a, query, 0.60): # They are really different, no need to calculate diff() return False if self.diff_a_b is None: self.diff_a_b, _ = diff(self.body_a, self.body_b) _, diff_query_a = diff(self.body_a, query) # Had to add this in order to prevent issues with CSRF tokens, which # might be part of the HTTP response body, are random (not removed by # clean_body) and will "break" the diff if len(diff_query_a) < 64: return True if fuzzy_equal(self.diff_a_b, diff_query_a, 0.9): return True return False
36.840741
98
0.59817
2,397
19,894
4.768043
0.183563
0.027911
0.017324
0.016537
0.296614
0.244378
0.20798
0.18838
0.148657
0.112083
0
0.006044
0.334624
19,894
539
99
36.909091
0.857369
0.10752
0
0.33463
0
0
0.065384
0
0
0
0
0
0
0
null
null
0.198444
0.066148
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
d41f2e6ad842c3dcc252d1a4c7fa71c7d5d7d944
948
py
Python
fhir_kindling/util/resources.py
azmeuk/fhir-kindling
4f73c384cb00abe978044785eea228756c1054af
[ "MIT" ]
3
2021-12-19T03:17:54.000Z
2022-02-24T10:29:25.000Z
fhir_kindling/util/resources.py
azmeuk/fhir-kindling
4f73c384cb00abe978044785eea228756c1054af
[ "MIT" ]
60
2021-10-30T12:12:39.000Z
2022-03-28T07:24:38.000Z
fhir_kindling/util/resources.py
azmeuk/fhir-kindling
4f73c384cb00abe978044785eea228756c1054af
[ "MIT" ]
1
2022-02-24T11:06:48.000Z
2022-02-24T11:06:48.000Z
from typing import Union, List from pydantic.fields import ModelField from fhir.resources.resource import Resource from fhir.resources import get_fhir_model_class from fhir.resources.fhirtypes import ResourceType def get_resource_fields(resource: Union[Resource, ResourceType, str]) -> List[ModelField]: """ Get the fields of a resource. Args: resource: Returns: """ # If the resource is a string, then we need to get the resource class if isinstance(resource, str): resource = get_fhir_model_class(resource) # Get the resource model fields fields = list(resource.__fields__.values()) return fields def valid_resource_name(resource_name: str) -> str: """ Args: resource_name: Returns: """ try: get_fhir_model_class(resource_name) except KeyError: raise ValueError(f"Invalid resource name: {resource_name}") return resource_name
22.571429
90
0.700422
118
948
5.440678
0.355932
0.130841
0.079439
0.079439
0.077882
0
0
0
0
0
0
0
0.223629
948
41
91
23.121951
0.872283
0.203587
0
0
0
0
0.054286
0
0
0
0
0
0
1
0.125
false
0
0.3125
0
0.5625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d42330431628c02abbfae562dd0d55db21f4866f
186
py
Python
imd_weather/__init__.py
bhardwajRahul/imd_weather
cdb4cd171eb35d7557cfc52deee273b093f1ba28
[ "MIT" ]
null
null
null
imd_weather/__init__.py
bhardwajRahul/imd_weather
cdb4cd171eb35d7557cfc52deee273b093f1ba28
[ "MIT" ]
null
null
null
imd_weather/__init__.py
bhardwajRahul/imd_weather
cdb4cd171eb35d7557cfc52deee273b093f1ba28
[ "MIT" ]
1
2021-01-01T12:36:24.000Z
2021-01-01T12:36:24.000Z
#!/usr/bin/python3 ''' Collects Weather Forecast by Indian Meterological Department, by parsing webpages :) ''' __version__ = '0.2.0' __author__ = 'Anjan Roy<anjanroy@yandex.com>'
20.666667
88
0.715054
23
186
5.434783
0.913043
0
0
0
0
0
0
0
0
0
0
0.025157
0.145161
186
8
89
23.25
0.761006
0.548387
0
0
0
0
0.486111
0.333333
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d42a8604bb2d70ad65e56defe7c0d2fcca097723
1,094
py
Python
python/test/resource/test_dataset_mixed.py
Fosstack/vmaf
e13b6c383ec20dba0cbd64d3265cfe49677a6f18
[ "BSD-2-Clause-Patent" ]
2,874
2016-06-06T16:11:37.000Z
2022-03-31T10:10:22.000Z
python/test/resource/test_dataset_mixed.py
Fosstack/vmaf
e13b6c383ec20dba0cbd64d3265cfe49677a6f18
[ "BSD-2-Clause-Patent" ]
619
2016-06-07T19:30:53.000Z
2022-03-31T16:36:05.000Z
python/test/resource/test_dataset_mixed.py
Fosstack/vmaf
e13b6c383ec20dba0cbd64d3265cfe49677a6f18
[ "BSD-2-Clause-Patent" ]
723
2016-06-05T02:44:33.000Z
2022-03-31T03:29:12.000Z
dataset_name = 'example' quality_width = 1920 quality_height = 1080 from vmaf.config import VmafConfig ref_videos = [ {'content_id': 0, 'path': VmafConfig.resource_path('yuv', 'checkerboard_1920_1080_10_3_0_0.yuv'), 'yuv_fmt': 'yuv420p', 'width': 1920, 'height': 1080}, {'content_id': 1, 'path': VmafConfig.resource_path('yuv', 'flat_1920_1080_0.yuv'), 'yuv_fmt': 'yuv420p', 'width': 720, 'height': 480}, ] dis_videos = [ {'content_id': 0, 'asset_id': 0, 'dmos': 100, 'path': VmafConfig.resource_path('yuv', 'checkerboard_1920_1080_10_3_0_0.yuv'), 'yuv_fmt': 'yuv420p', 'width': 1920, 'height': 1080}, # ref {'content_id': 0, 'asset_id': 1, 'dmos': 50, 'path': VmafConfig.resource_path('yuv', 'checkerboard_1920_1080_10_3_1_0.264'), 'yuv_fmt': 'notyuv',}, {'content_id': 1, 'asset_id': 2, 'dmos': 100, 'path': VmafConfig.resource_path('yuv', 'flat_1920_1080_0.yuv'), 'yuv_fmt': 'yuv420p', 'width': 720, 'height': 480}, # ref {'content_id': 1, 'asset_id': 3, 'dmos': 80, 'path': VmafConfig.resource_path('yuv', 'flat_1920_1080_10.264'), 'yuv_fmt': 'notyuv',}, ]
52.095238
189
0.669104
161
1,094
4.21118
0.242236
0.079646
0.19469
0.230089
0.741888
0.641593
0.641593
0.620944
0.560472
0.560472
0
0.14657
0.120658
1,094
20
190
54.7
0.558212
0.006399
0
0
0
0
0.414207
0.116236
0
0
0
0
0
1
0
false
0
0.071429
0
0.071429
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d4308ff2bb28a84034c881fb380435ac9669edd4
18,320
py
Python
translate/problemdef_pb2.py
schultet/goa
b76af608109ff217a2b68ca4e66582850c0a47ea
[ "MIT" ]
2
2019-05-13T11:59:18.000Z
2019-05-13T12:37:51.000Z
translate/problemdef_pb2.py
schultet/goa
b76af608109ff217a2b68ca4e66582850c0a47ea
[ "MIT" ]
null
null
null
translate/problemdef_pb2.py
schultet/goa
b76af608109ff217a2b68ca4e66582850c0a47ea
[ "MIT" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: problemdef.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='problemdef.proto', package='', serialized_pb=_b('\n\x10problemdef.proto\"-\n\x11PlanProblemVarVal\x12\x0b\n\x03var\x18\x01 \x02(\x05\x12\x0b\n\x03val\x18\x02 \x02(\x05\"\x1f\n\x10PlanProblemState\x12\x0b\n\x03val\x18\x01 \x03(\x05\"7\n\x14PlanProblemPartState\x12\x1f\n\x03val\x18\x01 \x03(\x0b\x32\x12.PlanProblemVarVal\"T\n\x0ePlanProblemVar\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\r\n\x05range\x18\x02 \x02(\x05\x12\x11\n\tfact_name\x18\x03 \x03(\t\x12\x12\n\nis_private\x18\x04 \x01(\x08\"4\n\x10PlanProblemMutex\x12 \n\x04\x66\x61\x63t\x18\x01 \x03(\x0b\x32\x12.PlanProblemVarVal\"\\\n\x12PlanProblemCondEff\x12\"\n\x03pre\x18\x01 \x02(\x0b\x32\x15.PlanProblemPartState\x12\"\n\x03\x65\x66\x66\x18\x02 \x02(\x0b\x32\x15.PlanProblemPartState\"\xd6\x01\n\x13PlanProblemOperator\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04\x63ost\x18\x02 \x02(\x05\x12\"\n\x03pre\x18\x03 \x02(\x0b\x32\x15.PlanProblemPartState\x12\"\n\x03\x65\x66\x66\x18\x04 \x02(\x0b\x32\x15.PlanProblemPartState\x12%\n\x08\x63ond_eff\x18\x05 \x03(\x0b\x32\x13.PlanProblemCondEff\x12\r\n\x05owner\x18\x06 \x01(\x05\x12\x11\n\tglobal_id\x18\x07 \x01(\x05\x12\x12\n\nis_private\x18\x08 \x01(\x08\"\xaa\x02\n\x0bPlanProblem\x12\x0f\n\x07version\x18\x01 \x02(\x05\x12\x1c\n\x03var\x18\x02 \x03(\x0b\x32\x0f.PlanProblemVar\x12 \n\x05mutex\x18\x03 \x03(\x0b\x32\x11.PlanProblemMutex\x12%\n\ninit_state\x18\x04 \x02(\x0b\x32\x11.PlanProblemState\x12#\n\x04goal\x18\x05 \x02(\x0b\x32\x15.PlanProblemPartState\x12&\n\x08operator\x18\x06 \x03(\x0b\x32\x14.PlanProblemOperator\x12\x12\n\nagent_name\x18\x07 \x03(\t\x12\x30\n\x12projected_operator\x18\x08 \x03(\x0b\x32\x14.PlanProblemOperator\x12\x10\n\x08\x61gent_id\x18\t \x01(\x05') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _PLANPROBLEMVARVAL = _descriptor.Descriptor( name='PlanProblemVarVal', full_name='PlanProblemVarVal', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='var', full_name='PlanProblemVarVal.var', index=0, number=1, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='val', full_name='PlanProblemVarVal.val', index=1, number=2, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=20, serialized_end=65, ) _PLANPROBLEMSTATE = _descriptor.Descriptor( name='PlanProblemState', full_name='PlanProblemState', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='val', full_name='PlanProblemState.val', index=0, number=1, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=67, serialized_end=98, ) _PLANPROBLEMPARTSTATE = _descriptor.Descriptor( name='PlanProblemPartState', full_name='PlanProblemPartState', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='val', full_name='PlanProblemPartState.val', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=100, serialized_end=155, ) _PLANPROBLEMVAR = _descriptor.Descriptor( name='PlanProblemVar', full_name='PlanProblemVar', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='PlanProblemVar.name', index=0, number=1, type=9, cpp_type=9, label=2, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='range', full_name='PlanProblemVar.range', index=1, number=2, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='fact_name', full_name='PlanProblemVar.fact_name', index=2, number=3, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='is_private', full_name='PlanProblemVar.is_private', index=3, number=4, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=157, serialized_end=241, ) _PLANPROBLEMMUTEX = _descriptor.Descriptor( name='PlanProblemMutex', full_name='PlanProblemMutex', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='fact', full_name='PlanProblemMutex.fact', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=243, serialized_end=295, ) _PLANPROBLEMCONDEFF = _descriptor.Descriptor( name='PlanProblemCondEff', full_name='PlanProblemCondEff', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='pre', full_name='PlanProblemCondEff.pre', index=0, number=1, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='eff', full_name='PlanProblemCondEff.eff', index=1, number=2, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=297, serialized_end=389, ) _PLANPROBLEMOPERATOR = _descriptor.Descriptor( name='PlanProblemOperator', full_name='PlanProblemOperator', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='PlanProblemOperator.name', index=0, number=1, type=9, cpp_type=9, label=2, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='cost', full_name='PlanProblemOperator.cost', index=1, number=2, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pre', full_name='PlanProblemOperator.pre', index=2, number=3, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='eff', full_name='PlanProblemOperator.eff', index=3, number=4, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='cond_eff', full_name='PlanProblemOperator.cond_eff', index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='owner', full_name='PlanProblemOperator.owner', index=5, number=6, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='global_id', full_name='PlanProblemOperator.global_id', index=6, number=7, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='is_private', full_name='PlanProblemOperator.is_private', index=7, number=8, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=392, serialized_end=606, ) _PLANPROBLEM = _descriptor.Descriptor( name='PlanProblem', full_name='PlanProblem', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='version', full_name='PlanProblem.version', index=0, number=1, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='var', full_name='PlanProblem.var', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='mutex', full_name='PlanProblem.mutex', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='init_state', full_name='PlanProblem.init_state', index=3, number=4, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='goal', full_name='PlanProblem.goal', index=4, number=5, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='operator', full_name='PlanProblem.operator', index=5, number=6, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='agent_name', full_name='PlanProblem.agent_name', index=6, number=7, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='projected_operator', full_name='PlanProblem.projected_operator', index=7, number=8, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='agent_id', full_name='PlanProblem.agent_id', index=8, number=9, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=609, serialized_end=907, ) _PLANPROBLEMPARTSTATE.fields_by_name['val'].message_type = _PLANPROBLEMVARVAL _PLANPROBLEMMUTEX.fields_by_name['fact'].message_type = _PLANPROBLEMVARVAL _PLANPROBLEMCONDEFF.fields_by_name['pre'].message_type = _PLANPROBLEMPARTSTATE _PLANPROBLEMCONDEFF.fields_by_name['eff'].message_type = _PLANPROBLEMPARTSTATE _PLANPROBLEMOPERATOR.fields_by_name['pre'].message_type = _PLANPROBLEMPARTSTATE _PLANPROBLEMOPERATOR.fields_by_name['eff'].message_type = _PLANPROBLEMPARTSTATE _PLANPROBLEMOPERATOR.fields_by_name['cond_eff'].message_type = _PLANPROBLEMCONDEFF _PLANPROBLEM.fields_by_name['var'].message_type = _PLANPROBLEMVAR _PLANPROBLEM.fields_by_name['mutex'].message_type = _PLANPROBLEMMUTEX _PLANPROBLEM.fields_by_name['init_state'].message_type = _PLANPROBLEMSTATE _PLANPROBLEM.fields_by_name['goal'].message_type = _PLANPROBLEMPARTSTATE _PLANPROBLEM.fields_by_name['operator'].message_type = _PLANPROBLEMOPERATOR _PLANPROBLEM.fields_by_name['projected_operator'].message_type = _PLANPROBLEMOPERATOR DESCRIPTOR.message_types_by_name['PlanProblemVarVal'] = _PLANPROBLEMVARVAL DESCRIPTOR.message_types_by_name['PlanProblemState'] = _PLANPROBLEMSTATE DESCRIPTOR.message_types_by_name['PlanProblemPartState'] = _PLANPROBLEMPARTSTATE DESCRIPTOR.message_types_by_name['PlanProblemVar'] = _PLANPROBLEMVAR DESCRIPTOR.message_types_by_name['PlanProblemMutex'] = _PLANPROBLEMMUTEX DESCRIPTOR.message_types_by_name['PlanProblemCondEff'] = _PLANPROBLEMCONDEFF DESCRIPTOR.message_types_by_name['PlanProblemOperator'] = _PLANPROBLEMOPERATOR DESCRIPTOR.message_types_by_name['PlanProblem'] = _PLANPROBLEM PlanProblemVarVal = _reflection.GeneratedProtocolMessageType('PlanProblemVarVal', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMVARVAL, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemVarVal) )) _sym_db.RegisterMessage(PlanProblemVarVal) PlanProblemState = _reflection.GeneratedProtocolMessageType('PlanProblemState', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMSTATE, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemState) )) _sym_db.RegisterMessage(PlanProblemState) PlanProblemPartState = _reflection.GeneratedProtocolMessageType('PlanProblemPartState', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMPARTSTATE, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemPartState) )) _sym_db.RegisterMessage(PlanProblemPartState) PlanProblemVar = _reflection.GeneratedProtocolMessageType('PlanProblemVar', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMVAR, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemVar) )) _sym_db.RegisterMessage(PlanProblemVar) PlanProblemMutex = _reflection.GeneratedProtocolMessageType('PlanProblemMutex', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMMUTEX, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemMutex) )) _sym_db.RegisterMessage(PlanProblemMutex) PlanProblemCondEff = _reflection.GeneratedProtocolMessageType('PlanProblemCondEff', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMCONDEFF, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemCondEff) )) _sym_db.RegisterMessage(PlanProblemCondEff) PlanProblemOperator = _reflection.GeneratedProtocolMessageType('PlanProblemOperator', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEMOPERATOR, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblemOperator) )) _sym_db.RegisterMessage(PlanProblemOperator) PlanProblem = _reflection.GeneratedProtocolMessageType('PlanProblem', (_message.Message,), dict( DESCRIPTOR = _PLANPROBLEM, __module__ = 'problemdef_pb2' # @@protoc_insertion_point(class_scope:PlanProblem) )) _sym_db.RegisterMessage(PlanProblem) # @@protoc_insertion_point(module_scope)
37.61807
1,667
0.742522
2,232
18,320
5.806004
0.087366
0.056795
0.050004
0.043213
0.622502
0.584536
0.564241
0.545644
0.515395
0.511228
0
0.041247
0.133188
18,320
486
1,668
37.695473
0.774811
0.032587
0
0.653759
1
0.002278
0.179729
0.115584
0
0
0
0
0
1
0
false
0
0.013667
0
0.013667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d445167c129f0fee7127509d25fc78e9fed6e319
100
py
Python
micro-benchmark/snippets/external/cls_parent/main.py
WenJinfeng/PyCG
b45e8e04fe697d8301cf27222a8f37646d69f168
[ "Apache-2.0" ]
121
2020-12-16T20:31:37.000Z
2022-03-21T20:32:43.000Z
micro-benchmark/snippets/external/cls_parent/main.py
WenJinfeng/PyCG
b45e8e04fe697d8301cf27222a8f37646d69f168
[ "Apache-2.0" ]
24
2021-03-13T00:04:00.000Z
2022-03-21T17:28:11.000Z
micro-benchmark/snippets/external/cls_parent/main.py
WenJinfeng/PyCG
b45e8e04fe697d8301cf27222a8f37646d69f168
[ "Apache-2.0" ]
19
2021-03-23T10:58:47.000Z
2022-03-24T19:46:50.000Z
from ext import parent class A(parent): def fn(self): self.parent_fn() a = A() a.fn()
11.111111
24
0.58
17
100
3.352941
0.529412
0.070175
0
0
0
0
0
0
0
0
0
0
0.27
100
8
25
12.5
0.780822
0
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0.166667
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d45d36879d463d078c14e712d7f0575764948839
289
py
Python
securityscrape/securityscrape/items.py
ArcIX/vsdscrapy
998232f9f8b41ae83040a628ed599a51da378d18
[ "MIT" ]
null
null
null
securityscrape/securityscrape/items.py
ArcIX/vsdscrapy
998232f9f8b41ae83040a628ed599a51da378d18
[ "MIT" ]
null
null
null
securityscrape/securityscrape/items.py
ArcIX/vsdscrapy
998232f9f8b41ae83040a628ed599a51da378d18
[ "MIT" ]
null
null
null
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field class SecurityItem(Item): # define the fields for your item here like: # name = scrapy.Field() source_url = Field()
24.083333
53
0.716263
42
289
4.904762
0.714286
0.067961
0
0
0
0
0
0
0
0
0
0
0.183391
289
11
54
26.272727
0.872881
0.636678
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d45db6bf4b1f5eb843ac891cdb32a017e59d1ba3
638
py
Python
apps/djnext/__init__.py
martync/zython
e008bbb33e212f0856e85b8594003402e0a635c0
[ "Beerware" ]
null
null
null
apps/djnext/__init__.py
martync/zython
e008bbb33e212f0856e85b8594003402e0a635c0
[ "Beerware" ]
null
null
null
apps/djnext/__init__.py
martync/zython
e008bbb33e212f0856e85b8594003402e0a635c0
[ "Beerware" ]
null
null
null
from django.http import HttpResponseRedirect # Ask GET then POST def get_post(request, url, key="next"): return request.GET.get(key, request.POST.get(key, url)) def get_post_response(*args, **kwargs): return HttpResponseRedirect(get_post(*args, **kwargs)) # Ask POST then GET def post_get(request, url, key="next"): return request.POST.get(key, request.GET.get(key, url)) def post_get_response(*args, **kwargs): return HttpResponseRedirect(post_get(*args, **kwargs)) # REFERRER ? def ref_get_post(request, url, key="next"): return request.META.get("HTTP_REFERER", request.GET.get(key, request.POST.get(key, url)))
33.578947
93
0.727273
95
638
4.768421
0.231579
0.07947
0.086093
0.112583
0.567329
0.373068
0.306843
0.306843
0.15894
0
0
0
0.122257
638
19
93
33.578947
0.808929
0.0721
0
0
0
0
0.040747
0
0
0
0
0
0
1
0.454545
false
0
0.090909
0.454545
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
d46b8a28734476fc07b094bb7d6120cd6392d36d
140
py
Python
calorimeter/__init__.py
jevandezande/dsc
482b32026bd769a0fe0b20750e051e356f1fcdac
[ "MIT" ]
null
null
null
calorimeter/__init__.py
jevandezande/dsc
482b32026bd769a0fe0b20750e051e356f1fcdac
[ "MIT" ]
null
null
null
calorimeter/__init__.py
jevandezande/dsc
482b32026bd769a0fe0b20750e051e356f1fcdac
[ "MIT" ]
null
null
null
"""Top-level package for Calorimeter.""" __author__ = """Jonathon Vandezande""" __email__ = 'jevandezande@gmail.com' __version__ = '0.2.1'
23.333333
40
0.714286
16
140
5.5
1
0
0
0
0
0
0
0
0
0
0
0.024
0.107143
140
5
41
28
0.68
0.242857
0
0
0
0
0.46
0.22
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d47cde2d88200d0120c3cc99d44676263aaceb49
509
py
Python
cyberpunk_theme/widget/checkbutton.py
pyrustic/tk-cyberpunk-theme
be0386abf293e2f3612b64fb31f7b2bf554acb8e
[ "MIT" ]
5
2021-03-28T02:52:03.000Z
2021-06-10T11:34:09.000Z
cyberpunk_theme/widget/checkbutton.py
pyrustic/tk-cyberpunk-theme
be0386abf293e2f3612b64fb31f7b2bf554acb8e
[ "MIT" ]
null
null
null
cyberpunk_theme/widget/checkbutton.py
pyrustic/tk-cyberpunk-theme
be0386abf293e2f3612b64fb31f7b2bf554acb8e
[ "MIT" ]
null
null
null
import tkstyle from cyberpunk_theme import constant def get_style(font_family=constant.FONT_FAMILY, font_size=constant.FONT_SIZE): style = tkstyle.Checkbutton() style.background = constant.BACKGROUND_COLOR style.foreground = "#9B9B9B" style.font = (font_family, font_size, "normal") style.highlightThickness = 0 style.selectColor = constant.BACKGROUND_COLOR style.activeBackground = constant.BACKGROUND_COLOR style.activeForeground = "#B9B9B9" return style
31.8125
54
0.744597
56
509
6.571429
0.446429
0.081522
0.1875
0.228261
0
0
0
0
0
0
0
0.016667
0.174853
509
15
55
33.933333
0.859524
0
0
0
0
0
0.039293
0
0
0
0
0
0
1
0.076923
false
0
0.153846
0
0.307692
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d47e9a34c853b5dc3fca8b991390e543326fef11
5,192
py
Python
esphome/components/tcs34725/sensor.py
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
249
2018-04-07T12:04:11.000Z
2019-01-25T01:11:34.000Z
esphome/components/tcs34725/sensor.py
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
243
2018-04-11T16:37:11.000Z
2019-01-25T16:50:37.000Z
esphome/components/tcs34725/sensor.py
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
40
2018-04-10T05:50:14.000Z
2019-01-25T15:20:36.000Z
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import i2c, sensor from esphome.const import ( CONF_COLOR_TEMPERATURE, CONF_GAIN, CONF_ID, CONF_ILLUMINANCE, CONF_GLASS_ATTENUATION_FACTOR, CONF_INTEGRATION_TIME, DEVICE_CLASS_ILLUMINANCE, ICON_LIGHTBULB, STATE_CLASS_MEASUREMENT, UNIT_PERCENT, ICON_THERMOMETER, UNIT_KELVIN, UNIT_LUX, ) DEPENDENCIES = ["i2c"] CONF_RED_CHANNEL = "red_channel" CONF_GREEN_CHANNEL = "green_channel" CONF_BLUE_CHANNEL = "blue_channel" CONF_CLEAR_CHANNEL = "clear_channel" tcs34725_ns = cg.esphome_ns.namespace("tcs34725") TCS34725Component = tcs34725_ns.class_( "TCS34725Component", cg.PollingComponent, i2c.I2CDevice ) TCS34725IntegrationTime = tcs34725_ns.enum("TCS34725IntegrationTime") TCS34725_INTEGRATION_TIMES = { "auto": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_AUTO, "2.4ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_2_4MS, "24ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_24MS, "50ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_50MS, "101ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_101MS, "120ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_120MS, "154ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_154MS, "180ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_180MS, "199ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_199MS, "240ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_240MS, "300ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_300MS, "360ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_360MS, "401ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_401MS, "420ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_420MS, "480ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_480MS, "499ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_499MS, "540ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_540MS, "600ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_600MS, "614ms": TCS34725IntegrationTime.TCS34725_INTEGRATION_TIME_614MS, } TCS34725Gain = tcs34725_ns.enum("TCS34725Gain") TCS34725_GAINS = { "1X": TCS34725Gain.TCS34725_GAIN_1X, "4X": TCS34725Gain.TCS34725_GAIN_4X, "16X": TCS34725Gain.TCS34725_GAIN_16X, "60X": TCS34725Gain.TCS34725_GAIN_60X, } color_channel_schema = sensor.sensor_schema( unit_of_measurement=UNIT_PERCENT, icon=ICON_LIGHTBULB, accuracy_decimals=1, state_class=STATE_CLASS_MEASUREMENT, ) color_temperature_schema = sensor.sensor_schema( unit_of_measurement=UNIT_KELVIN, icon=ICON_THERMOMETER, accuracy_decimals=1, state_class=STATE_CLASS_MEASUREMENT, ) illuminance_schema = sensor.sensor_schema( unit_of_measurement=UNIT_LUX, accuracy_decimals=1, device_class=DEVICE_CLASS_ILLUMINANCE, state_class=STATE_CLASS_MEASUREMENT, ) CONFIG_SCHEMA = ( cv.Schema( { cv.GenerateID(): cv.declare_id(TCS34725Component), cv.Optional(CONF_RED_CHANNEL): color_channel_schema, cv.Optional(CONF_GREEN_CHANNEL): color_channel_schema, cv.Optional(CONF_BLUE_CHANNEL): color_channel_schema, cv.Optional(CONF_CLEAR_CHANNEL): color_channel_schema, cv.Optional(CONF_ILLUMINANCE): illuminance_schema, cv.Optional(CONF_COLOR_TEMPERATURE): color_temperature_schema, cv.Optional(CONF_INTEGRATION_TIME, default="auto"): cv.enum( TCS34725_INTEGRATION_TIMES, lower=True ), cv.Optional(CONF_GAIN, default="1X"): cv.enum(TCS34725_GAINS, upper=True), cv.Optional(CONF_GLASS_ATTENUATION_FACTOR, default=1.0): cv.float_range( min=1.0 ), } ) .extend(cv.polling_component_schema("60s")) .extend(i2c.i2c_device_schema(0x29)) ) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) await cg.register_component(var, config) await i2c.register_i2c_device(var, config) cg.add(var.set_integration_time(config[CONF_INTEGRATION_TIME])) cg.add(var.set_gain(config[CONF_GAIN])) cg.add(var.set_glass_attenuation_factor(config[CONF_GLASS_ATTENUATION_FACTOR])) if CONF_RED_CHANNEL in config: sens = await sensor.new_sensor(config[CONF_RED_CHANNEL]) cg.add(var.set_red_sensor(sens)) if CONF_GREEN_CHANNEL in config: sens = await sensor.new_sensor(config[CONF_GREEN_CHANNEL]) cg.add(var.set_green_sensor(sens)) if CONF_BLUE_CHANNEL in config: sens = await sensor.new_sensor(config[CONF_BLUE_CHANNEL]) cg.add(var.set_blue_sensor(sens)) if CONF_CLEAR_CHANNEL in config: sens = await sensor.new_sensor(config[CONF_CLEAR_CHANNEL]) cg.add(var.set_clear_sensor(sens)) if CONF_ILLUMINANCE in config: sens = await sensor.new_sensor(config[CONF_ILLUMINANCE]) cg.add(var.set_illuminance_sensor(sens)) if CONF_COLOR_TEMPERATURE in config: sens = await sensor.new_sensor(config[CONF_COLOR_TEMPERATURE]) cg.add(var.set_color_temperature_sensor(sens))
39.037594
86
0.759052
604
5,192
6.130795
0.183775
0.093168
0.226843
0.236025
0.20794
0.180124
0.180124
0.137996
0.075614
0.05293
0
0.101482
0.155431
5,192
132
87
39.333333
0.742987
0
0
0.066116
0
0
0.042951
0.00443
0
0
0.00077
0
0
1
0
false
0
0.033058
0
0.033058
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2e07b20c9adc514cedce0a1835709bcabae73d57
733
py
Python
src/admissionreviewrequest/apiversion.py
nokia/conftest-runner
a809f642407663ae0bff39554fdc3c2cb5e430ce
[ "BSD-3-Clause" ]
2
2022-03-03T23:37:06.000Z
2022-03-11T21:36:06.000Z
src/admissionreviewrequest/apiversion.py
nokia/conftest-runner
a809f642407663ae0bff39554fdc3c2cb5e430ce
[ "BSD-3-Clause" ]
null
null
null
src/admissionreviewrequest/apiversion.py
nokia/conftest-runner
a809f642407663ae0bff39554fdc3c2cb5e430ce
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2021 Nokia # Licensed under the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause class ApiVersion(object): def __init__(self, group: str, version: str): self.group = group self.version = version class Kind(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.kind = kind class Resource(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.resource = kind def parse_api_version(api_version: str) -> ApiVersion: if '/' in api_version: return ApiVersion(*api_version.split('/', 1)) return ApiVersion('', api_version)
26.178571
60
0.664393
92
733
5.01087
0.336957
0.10846
0.071584
0.104121
0.370933
0.370933
0.370933
0.308026
0.308026
0.308026
0
0.012153
0.214188
733
27
61
27.148148
0.788194
0.135061
0
0.25
0
0
0.003175
0
0
0
0
0
0
1
0.25
false
0
0
0
0.5625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
2e0d1e3a83b4f30f17bb556a1b901364ab2cb0e2
1,682
py
Python
tests/unit/test_cards.py
ChristChurchMayfair/ccm-assistant
3d9a922642f0275882c6829e54a6fbc940067f26
[ "MIT" ]
null
null
null
tests/unit/test_cards.py
ChristChurchMayfair/ccm-assistant
3d9a922642f0275882c6829e54a6fbc940067f26
[ "MIT" ]
null
null
null
tests/unit/test_cards.py
ChristChurchMayfair/ccm-assistant
3d9a922642f0275882c6829e54a6fbc940067f26
[ "MIT" ]
null
null
null
import unittest from datetime import date, datetime import cards class TestCards(unittest.TestCase): def test_get_passage_title(self): morning = "morning" evening = "evening" self.assertEqual(cards.get_passage_title(date(2012, 4, 21), morning), "Bible reading for 21st April 2012 AM service") self.assertEqual(cards.get_passage_title(date(1997, 6, 2), evening), "Bible reading for 2nd June 1997 PM service") self.assertEqual(cards.get_passage_title(date(2018, 6, 3), evening), "Bible reading for 3rd June 2018 PM service") self.assertEqual(cards.get_passage_title(date(2018, 7, 4), evening), "Bible reading for 4th July 2018 PM service") self.assertEqual(cards.get_passage_title(date(2018, 11, 13), morning), "Bible reading for 13th November 2018 AM service") self.assertEqual(cards.get_passage_title(date(2018, 12, 11), morning), "Bible reading for 11th December 2018 AM service") def test_get_next_event_title(self): test_event_datetime = datetime(2000, 1, 1, 4, 20, 33) self.assertEqual(cards.get_next_event_title("Mission Breakfast", test_event_datetime), "Mission Breakfast - 04:20, Saturday 01 January") def test_get_next_event_content(self): self.assertEqual(cards.get_next_event_content("", "The Moon"), "The Moon") self.assertEqual(cards.get_next_event_content("Brunch for Women", "Christ Church Mayfair"), "Brunch for Women\nLocation: Christ Church Mayfair")
50.969697
99
0.643282
211
1,682
4.957346
0.322275
0.129063
0.172084
0.197897
0.431166
0.394837
0.364245
0.25239
0.25239
0.156788
0
0.073446
0.263377
1,682
32
100
52.5625
0.770783
0
0
0
0
0
0.263377
0
0
0
0
0
0.333333
1
0.111111
false
0.259259
0.111111
0
0.259259
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
2e1a3d1d3c216dd3ce3e8b734b07005db6b159c3
727
py
Python
SIT312-Group1-Prototype-main/flaskwebsite/dashboardPackage/__init__.py
FrozenKnight101/SITSystem-Design101
0cf2b5f3b5fd54e881b70f9b515aa3828d136402
[ "MIT" ]
null
null
null
SIT312-Group1-Prototype-main/flaskwebsite/dashboardPackage/__init__.py
FrozenKnight101/SITSystem-Design101
0cf2b5f3b5fd54e881b70f9b515aa3828d136402
[ "MIT" ]
null
null
null
SIT312-Group1-Prototype-main/flaskwebsite/dashboardPackage/__init__.py
FrozenKnight101/SITSystem-Design101
0cf2b5f3b5fd54e881b70f9b515aa3828d136402
[ "MIT" ]
null
null
null
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from sqlalchemy import create_engine import pymysql pymysql.install_as_MySQLdb() app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{password}@{server}/{database}'.format(user='admin', password='sit312Group!', server='rfidcheckin.cljhbnnuplh1.ap-southeast-2.rds.amazonaws.com', database='rfidDB') app.config['SECRET_KEY'] = '2392510167989ae56f41070a' db = SQLAlchemy(app) bcrypt = Bcrypt(app) login_manager = LoginManager(app) login_manager.login_view = 'login_page' login_manager.login_message_category = 'info' from dashboardPackage import routes
40.388889
221
0.792297
90
727
6.177778
0.511111
0.064748
0.053957
0
0
0
0
0
0
0
0
0.038168
0.099037
727
17
222
42.764706
0.810687
0
0
0
0
0
0.276056
0.209859
0
0
0
0
0
1
0
false
0.0625
0.4375
0
0.4375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
2e3c8f4bd26227fdb2c328ea513c5297064cd78e
139
py
Python
music/__model/_number/temporal.py
jedhsu/music
dea68c4a82296cd4910e786f533b2cbf861377c3
[ "MIT" ]
null
null
null
music/__model/_number/temporal.py
jedhsu/music
dea68c4a82296cd4910e786f533b2cbf861377c3
[ "MIT" ]
null
null
null
music/__model/_number/temporal.py
jedhsu/music
dea68c4a82296cd4910e786f533b2cbf861377c3
[ "MIT" ]
null
null
null
""" *Temporal Number* """ from abc import ABCMeta __all__ = ["TemporalNumber"] class TemporalNumber: __metaclass__ = ABCMeta
9.928571
28
0.676259
12
139
7.166667
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.215827
139
13
29
10.692308
0.788991
0.122302
0
0
0
0
0.12963
0
0
0
0
0
0
1
0
false
0
0.25
0
0.75
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
2e42c6fa1451793870610d45a13885b8ba881cb1
2,439
py
Python
plot/plot_curve.py
MasterLX/utils
71445e174323641e31558cdab16f4d41e52c3881
[ "MIT" ]
1
2021-06-22T01:15:56.000Z
2021-06-22T01:15:56.000Z
plot/plot_curve.py
MasterLX/utils
71445e174323641e31558cdab16f4d41e52c3881
[ "MIT" ]
null
null
null
plot/plot_curve.py
MasterLX/utils
71445e174323641e31558cdab16f4d41e52c3881
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) fig = plt.figure(figsize=(6,3)) ax1 = fig.add_subplot(1,2,1) x_ind = [2, 4, 6, 8, 10] x_lab = [r'$\mathcal{T}_2$', r'$\mathcal{T}_4$', r'$\mathcal{T}_6$', r'$\mathcal{T}_8$', r'$\mathcal{T}_{{10}}$'] leg = [r'$\mathcal{T}_1$',r'$\mathcal{T}_2$',r'$\mathcal{T}_3$'] # fig, axs = plt.subplots(9,1) # fig.subplots_adjust(hspace=0) plt.xlabel('Task',fontsize=15) plt.ylabel('Accuracy (\%)',fontsize=15) plt.title('(a) 10-split CIFAR-100', y=-0.5, fontsize=15) plt.ylim([50, 95]) ax1.plot([1,2,3,4,5,6,7,8,9,10], [87.4,83.7,85.0,82.8,85.5,84.6,83.6,84.7,83.5,83.7], label=leg[0], marker='*', markersize=5)#[89.1,82.0,84.6,83.6,85.1,84.1,82.7,82.2,82.4,84.2] ax1.plot([2,3,4,5,6,7,8,9,10], [78.4,75.5,75.3,76.4,75.1,71.6,72.7,73.7,76.3], label=leg[1], marker='.', markersize=5)#[80.5,79.2,79.1,80.9,80.6,78.3,77.6,81,80.2] ax1.plot([3,4,5,6,7,8,9,10], [79.9,73.2, 78.5,75.1,72.9,75.0,75.1,76.5], label=leg[2], marker='*', markersize=5)#[84.2,74.2,76.3,74.6,73.4,74.7,76.5,76.3] plt.xticks(x_ind,x_lab,fontsize=12) plt.yticks(size = 12) # plt.legend(bbox_to_anchor=(1,0.48),fontsize=13) ax2 = fig.add_subplot(1,2,2) x_ind = [5, 10, 15, 20, 25] x_lab = [r'$\mathcal{T}_5$', r'$\mathcal{T}_{{10}}$', r'$\mathcal{T}_{{15}}$', r'$\mathcal{T}_{{20}}$', r'$\mathcal{T}_{{25}}$'] # set_xlabel(r'$\mathcal{T}',fontsize=1) # fig, axs = plt.subplots(9,1) # fig.subplots_adjust(hspace=0) plt.xlabel('Task',fontsize=15) plt.ylabel('Accuracy (\%)',fontsize=15) plt.title('(b) 25-split TinyImageNet', y=-0.5, fontsize=15) plt.ylim([25, 75]) ax2.plot(list(range(1,26)), [68.25,65.75,65.75,60.25,64.75,63,59,60.25,53.75,57.25,54.5,57.5,52.75,56,57.25,56,55.25,57.5,54.75,56,54.75,56.75,59.5,54.25,58.5],marker='*', markersize=5) ax2.plot(list(range(2,26)), [73,71.75,68.25,69.25,68.25,67,69,67.5,67.5,66.75,70.25,65.5,62.75,66,65.25,66.25,65.5,66,67.25,69.75,68.5,69.5,64.25,68.25],marker='.', markersize=5) ax2.plot(list(range(3,26)), [72.0, 66.0, 65.0, 67.75, 68.5, 67.5,66.5,68.75, 69.0, 65.5,66.5,67.0,68.0,68.25,68.0,68.0,67.25,67.5, 66.5,68.0,62.75,59.75,71.0],marker='*', markersize=5) plt.xticks(x_ind,x_lab,fontsize=12) plt.yticks(size = 12) # plt.legend(bbox_to_anchor=(1,0.48),fontsize=13) plt.tight_layout() plt.subplots_adjust(top=0.85, bottom=0.3) fig.legend(bbox_to_anchor=(0.98,1),fontsize=12,ncol=3) plt.savefig('acc.pdf') #,bbox_inches='tight' plt.show()
49.77551
185
0.637966
580
2,439
2.622414
0.210345
0.073636
0.08284
0.00789
0.389218
0.347798
0.347798
0.253123
0.247206
0.234057
0
0.247602
0.059451
2,439
48
186
50.8125
0.415432
0.167282
0
0.235294
0
0
0.157504
0
0
0
0
0
0
1
0
false
0
0.058824
0
0.058824
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2e4967f94cf168917348f39b2ed3bfe7b78e54d2
620
py
Python
judge/templatetags/markdown_tags.py
TheAvidDev/pnoj-site
63299e873b1fb654667545222ce2b3157e78acd9
[ "MIT" ]
null
null
null
judge/templatetags/markdown_tags.py
TheAvidDev/pnoj-site
63299e873b1fb654667545222ce2b3157e78acd9
[ "MIT" ]
null
null
null
judge/templatetags/markdown_tags.py
TheAvidDev/pnoj-site
63299e873b1fb654667545222ce2b3157e78acd9
[ "MIT" ]
null
null
null
import requests import markdown as markdown_pkg from django import template from django.utils.safestring import mark_safe register = template.Library() # @register.filter # def markdown(markdown_content, mode="gfm"): # post_content = {'text': markdown_content, 'mode': mode, 'context': 'pnoj/site'} # rendered_markdown = requests.post("https://api.github.com/markdown", json=post_content) # rendered_markdown.raise_for_status() # return mark_safe(rendered_markdown.text) @register.filter def markdown(markdown_content): html = markdown_pkg.markdown(markdown_content) return mark_safe(html)
31
93
0.759677
78
620
5.833333
0.448718
0.131868
0.151648
0.10989
0.175824
0.175824
0
0
0
0
0
0
0.129032
620
19
94
32.631579
0.842593
0.519355
0
0
0
0
0
0
0
0
0
0
0
1
0.111111
false
0
0.444444
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
2e5729c4ea10db3d5b4d1d20228ad56d25fb7cd3
147
py
Python
CURSO UDEMY/TEORICAS/8.py
CamilliCerutti/Exercicios-de-Python-curso-em-video
6571a5c5cb7b4398352a7778c55588c0c16f13c2
[ "MIT" ]
null
null
null
CURSO UDEMY/TEORICAS/8.py
CamilliCerutti/Exercicios-de-Python-curso-em-video
6571a5c5cb7b4398352a7778c55588c0c16f13c2
[ "MIT" ]
null
null
null
CURSO UDEMY/TEORICAS/8.py
CamilliCerutti/Exercicios-de-Python-curso-em-video
6571a5c5cb7b4398352a7778c55588c0c16f13c2
[ "MIT" ]
null
null
null
""" USO DO JOIN """ string = 'O brasil é penta.' lista = string.split(' ') strint_2 = ','.join(lista) print(string) print(lista) print(strint_2)
12.25
28
0.646259
22
147
4.227273
0.590909
0.150538
0
0
0
0
0
0
0
0
0
0.016129
0.156463
147
12
29
12.25
0.733871
0.07483
0
0
0
0
0.147287
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
2e5c752c5c755fd94c0e7098d1bc261aa38549db
344
py
Python
0x0A-python-inheritance/3-is_kind_of_class.py
Dev-Loup/holbertonschool-higher_level_programming
af6fe9a05c87dcdbb88270eec4c7ec81d6a70d9b
[ "FSFAP" ]
null
null
null
0x0A-python-inheritance/3-is_kind_of_class.py
Dev-Loup/holbertonschool-higher_level_programming
af6fe9a05c87dcdbb88270eec4c7ec81d6a70d9b
[ "FSFAP" ]
null
null
null
0x0A-python-inheritance/3-is_kind_of_class.py
Dev-Loup/holbertonschool-higher_level_programming
af6fe9a05c87dcdbb88270eec4c7ec81d6a70d9b
[ "FSFAP" ]
null
null
null
#!/usr/bin/python3 """ Class check module Functions: is_kind_of_class: checks if obj is inherit from determined class """ def is_kind_of_class(obj, a_class): """ checks class inheritance Args: obj: object to evaluate a_class: suspect father """ return isinstance(obj, a_class)
20.235294
50
0.619186
44
344
4.636364
0.613636
0.088235
0.078431
0.127451
0
0
0
0
0
0
0
0.004132
0.296512
344
16
51
21.5
0.838843
0.601744
0
0
0
0
0
0
0
0
0
0
0
1
0.5
false
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
2e6851db4eb6b0d98f1ae630e0bb8dd940964688
1,619
py
Python
cinemanio/api/schema/properties.py
cinemanio/backend
c393dc8c2d59dc99aa2c3314d3372b6e2bf5497f
[ "MIT" ]
4
2018-07-05T07:00:04.000Z
2021-02-03T22:02:13.000Z
cinemanio/api/schema/properties.py
cinemanio/backend
c393dc8c2d59dc99aa2c3314d3372b6e2bf5497f
[ "MIT" ]
19
2018-09-03T23:27:49.000Z
2020-02-12T00:09:02.000Z
cinemanio/api/schema/properties.py
cinemanio/backend
c393dc8c2d59dc99aa2c3314d3372b6e2bf5497f
[ "MIT" ]
null
null
null
import graphene from graphene_django import DjangoObjectType from cinemanio.api.helpers import global_id from cinemanio.api.utils import DjangoObjectTypeMixin from cinemanio.core.models import Genre, Language, Country, Role from cinemanio.core.utils.languages import translated_fields PROPERTY_FIELDS = ('id',) + translated_fields('name') class RoleNode(DjangoObjectTypeMixin, DjangoObjectType): class Meta: model = Role only_fields = PROPERTY_FIELDS def resolve_id(self, info): return global_id(Role(id=self.pk)) class GenreNode(DjangoObjectType): class Meta: model = Genre only_fields = PROPERTY_FIELDS def resolve_id(self, info): return global_id(Genre(id=self.pk)) class LanguageNode(DjangoObjectType): class Meta: model = Language only_fields = PROPERTY_FIELDS def resolve_id(self, info): return global_id(Language(id=self.pk)) class CountryNode(DjangoObjectType): class Meta: model = Country only_fields = PROPERTY_FIELDS + ('code',) def resolve_id(self, info): return global_id(Country(id=self.pk)) class PropertiesQuery: roles = graphene.List(RoleNode) genres = graphene.List(GenreNode) languages = graphene.List(LanguageNode) countries = graphene.List(CountryNode) def resolve_roles(self, _): return Role.objects.all() def resolve_genres(self, _): return Genre.objects.all() def resolve_languages(self, _): return Language.objects.all() def resolve_countries(self, _): return Country.objects.all()
24.907692
64
0.702285
187
1,619
5.925134
0.240642
0.072202
0.090253
0.108303
0.187726
0.187726
0.187726
0.187726
0.15704
0.15704
0
0
0.209389
1,619
64
65
25.296875
0.865625
0
0
0.25
0
0
0.006177
0
0
0
0
0
0
1
0.181818
false
0
0.136364
0.181818
0.795455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
2e6fb3af88737869eb321c1147f1789b5d1ec474
5,827
py
Python
dsb.py
edbezci/mapOverlayHumanoid
95d5e16fb983a7384abea6f51599483274ff0f62
[ "MIT" ]
null
null
null
dsb.py
edbezci/mapOverlayHumanoid
95d5e16fb983a7384abea6f51599483274ff0f62
[ "MIT" ]
null
null
null
dsb.py
edbezci/mapOverlayHumanoid
95d5e16fb983a7384abea6f51599483274ff0f62
[ "MIT" ]
null
null
null
''' this is the file holding the description texts to be inserted this file is imported to the src.py ''' bf_desc = [ "Brute-Force Algorithm:", " ", "Summary:", "The brute force algorithm is very aggressive.", "It checks every single line segment against every other line segment for an intersection.", "This is done through vector mathematics, direction vectors and scalars.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of intersections from left to right.", " ", "Efficiency:", "The efficiency of this algorithm is O(n*n). This is due to the fact that the presence of", "intersections has to be checked between all line segments. This is computationally expensive.", "There is no consideration of shortcuts, rather all possibilities are computed till it finds a solution." ] bo_desc = [ "Bentley-Ottmann Algorithm:", " ", "Summary:", "The Bentley-Ottmann algorithm incorporates the idea of an imaginary line.", "This line will sweep from left-to-right over the line segments to compute", "all the intersecting pairs of line segments. Once again, this is done through", "vector mathematics, direction vectors and scalars.", " ", "Event Queue:", "This algorithm keeps an event queue.", "Adding a line-segment to the list when its leftmost endpoint is discovered during", "the sweep and also deleting a line-segment from the list when its rightmost endpoint", "is discovered during the sweep. This way, when the sweep reaches the end of the plane,", "the event queue should be empty.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of", "when they are discovered by the sweep-line." " " "Efficiency:", "The efficiency of this algorithm is O((n + k)logn). This algorithm is output-sensitive", "as the running time is sensitive to the size of the output. This algorithm is also intersection-sensitive", "as the number of intersections contributes to the size of the output generated." ] sh_desc = [ "Shamos-Hoey Algorithm:", " ", "Summary:", "The Shamos-Hoey algorithm also incorporates the idea of an imaginary line.", "This line will sweep from left-to-right over the line segments. Once it discovers its first intersection,", "the algorithm will stop. Once again, this is done through vector mathematics, direction vectors and scalars.", " ", "Event Queue:", "This algorithm keeps an event queue. Adding a line-segment to the list when its leftmost endpoint is discovered", "during the sweep and also deleting a line-segment from the list when its rightmost endpoint is discovered during the sweep.", "As the algorithm stops at the first intersection that is discovered, the event queue will not be empty by the time the algorithm terminates.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of when they are discovered by the sweep-line.", " ", "Efficiency:", "The efficiency of this algorithm is O(nlogn) time to compute due to it terminating on the first intersection point that it discovers.", "As the algorithm terminates at the first intersection point, its efficiency is not sensitive to the number of intersections that it discovers.", ] effic_desc = [ "Efficiency:", " ", "Brute-Force Algorithm:", "O(n*n) is very computationally expensive. Out of all the algorithms, where we see a high number of line segments,the brute-force algorithm", "will always be the most inefficient.", " ", "Bentley-Ottmann Algorithm:", "O((n + k)logn) is very efficient in terms of taking into consideration the number of intersections. Where we see a high number of line", "segments but low number of intersections, the brute-force algorithm will play its part as an efficient algorithm.", " ", "Shamos-Hoey Algorithm:", "O(nlogn) is also very efficient which is all due to how the algorithm terminates at the first intersection", "point that it discovers. Because of this, the efficiency is not hindered by a large number of intersection points within the plane.", " ", "Summary:", "If we look at the map-overlay problem, we wish to discover every intersection point that exists within the plane. The likeliness that when two thematic", "map layers overlap, all of their line segments intersect is slim. Knowing this, the better suited algorithm would be the Bentley-Ottmann algorithm rather", "than the Brute-Force algorithm. We have a plane with many line segments whereby, all intersections in existence need to be identified and we know that", "not every pair of line segments intersect. Here, the Shamos-Hoey algorithm would not be suitable as we are interested in finding more than one intersection.", "However, where we concern ourself with robotic movement, a given motion trajectory between two ligaments such as the humanoids arms, we only need to look at", "whether this motion trajectory has any intersection. We are not interested in searching for every single intersection within the plane. For this, the Shamos-Hoey algorithm", "would be better suited. Furthermore, the efficiency O(nlogn) of the Shamos-Hoey algorithm compared to O((n+k)logn) is also another key reason the Shamos-Hoey would be a better suit.", "We would expect the movement of a humanoid to be flawless and not at any stage have to pause for a long-period of time to calculate its next movements. The Shamos-Hoey algorithm yielding", "a higher efficiency would mean that intersections can be calculated faster, which will in turn, contribute towards the flawless movement of the humanoid robot." ]
61.336842
192
0.72902
862
5,827
4.935035
0.277262
0.030559
0.031265
0.025858
0.370945
0.341796
0.332393
0.319464
0.296427
0.269864
0
0
0.201819
5,827
94
193
61.989362
0.912492
0.016647
0
0.37931
0
0.252874
0.879413
0.003845
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2e718f603be7a18012f5634d1852d85958615512
111
py
Python
ww1.py
blogs1801/test
2a005cb9d9340419aa9e15c7e97dcfaec3763e54
[ "Apache-2.0" ]
null
null
null
ww1.py
blogs1801/test
2a005cb9d9340419aa9e15c7e97dcfaec3763e54
[ "Apache-2.0" ]
null
null
null
ww1.py
blogs1801/test
2a005cb9d9340419aa9e15c7e97dcfaec3763e54
[ "Apache-2.0" ]
null
null
null
import uuid pass def func(): obj = uuid.uuid4() return obj.hex if __name__=='__main__': func()
9.25
24
0.603604
15
111
3.933333
0.8
0
0
0
0
0
0
0
0
0
0
0.012195
0.261261
111
11
25
10.090909
0.707317
0
0
0
0
0
0.073395
0
0
0
0
0
0
1
0.142857
false
0.142857
0.142857
0
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
2e732e50c64bd0890499ea5c064de7eca475d3e6
96
py
Python
intform.py
chidanandpujar/Python_scripts
0ee70e07ef4ab4d8c04955466ea9b305bdac0a53
[ "Unlicense" ]
null
null
null
intform.py
chidanandpujar/Python_scripts
0ee70e07ef4ab4d8c04955466ea9b305bdac0a53
[ "Unlicense" ]
null
null
null
intform.py
chidanandpujar/Python_scripts
0ee70e07ef4ab4d8c04955466ea9b305bdac0a53
[ "Unlicense" ]
null
null
null
try: n = int(input("Enter number")) print(n*n) except: print("Non integer entered")
16
34
0.604167
14
96
4.142857
0.785714
0
0
0
0
0
0
0
0
0
0
0
0.229167
96
5
35
19.2
0.783784
0
0
0
0
0
0.322917
0
0
0
0
0
0
1
0
false
0
0
0
0
0.4
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2e88c24aefa6a32a03f2918d4a607a6af1094875
938
py
Python
services/scraper.py
AlperRehaYAZGAN/ytu-web-data-mining-termpaper
d86f6963f0dd2cb08af521ade5bbe568dac98ffc
[ "MIT" ]
null
null
null
services/scraper.py
AlperRehaYAZGAN/ytu-web-data-mining-termpaper
d86f6963f0dd2cb08af521ade5bbe568dac98ffc
[ "MIT" ]
null
null
null
services/scraper.py
AlperRehaYAZGAN/ytu-web-data-mining-termpaper
d86f6963f0dd2cb08af521ade5bbe568dac98ffc
[ "MIT" ]
null
null
null
from urllib.request import urlopen from bs4 import BeautifulSoup import re class Scraper(): Newlines = re.compile(r'[\r\n]\s+') def __init__(self): pass def scrape_url_text_content(self,url): return self.__get_page_text_content(url) def __get_page_text_content(self,url): # given a url, get page content data = urlopen(url).read() # parse as html structured document bs = BeautifulSoup(data,"html.parser") # kill javascript content for s in bs.findAll('script'): s.replaceWith('') # find body and extract text txt = bs.find('body').getText('\n') # remove multiple linebreaks and whitespace return self.Newlines.sub('\n', txt) #def __get_content_with_trafilatura(self,url): # downloaded = trafilatura.fetch_url(url) # return trafilatura.extract(downloaded) pass
29.3125
52
0.6258
115
938
4.904348
0.513043
0.058511
0.053191
0.06383
0
0
0
0
0
0
0
0.001468
0.273987
938
31
53
30.258065
0.826725
0.304904
0
0.117647
0
0
0.052877
0
0
0
0
0
0
1
0.176471
false
0.117647
0.176471
0.058824
0.588235
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
2e89e09da8031427416db5dc051f730ed4de3c8a
1,361
py
Python
gcn/anal.py
s1998/gcn
8b92342d4f4a8d037593732072ed89cfd8aa9be9
[ "MIT" ]
null
null
null
gcn/anal.py
s1998/gcn
8b92342d4f4a8d037593732072ed89cfd8aa9be9
[ "MIT" ]
null
null
null
gcn/anal.py
s1998/gcn
8b92342d4f4a8d037593732072ed89cfd8aa9be9
[ "MIT" ]
1
2019-11-26T14:59:20.000Z
2019-11-26T14:59:20.000Z
import pickle import operator import numpy as np import csv import os.path with open ('y_test', 'rb') as f: y_test=pickle.load(f) dicvocab={} f=open("data/vocab.csv") vocab=csv.reader(f) for word in vocab: if word[0]!='': dicvocab[int(word[0])-1]=word[1] f.close() label_size=y_test.shape[1] topics=["/Artificial_Intelligence/Machine_Learning/Case-Based/", "/Artificial_Intelligence/Machine_Learning/Genetic_Algorithms/", "/Artificial_Intelligence/Machine_Learning/Neural_Networks/", "/Artificial_Intelligence/Machine_Learning/Probabilistic_Methods/", "/Artificial_Intelligence/Machine_Learning/Reinforcement_Learning/", "/Artificial_Intelligence/Machine_Learning/Rule_Learning/", "/Artificial_Intelligence/Machine_Learning/Theory/"] maxlabel=np.argmax(y_test, axis=1) for ind in range(label_size+1): st='dictionary' + str(ind) if not os.path.isfile(st): continue if ind<label_size: print("Class ",ind, "enabled") else: print("All Classes enabled") with open(st, 'rb') as f: dic= pickle.load(f) for i in range(label_size): dic2={} print("Top 5 Highest Relevance Features for Class ", topics[i], "->", end='') for x in dic[i]: if x not in dic2: dic2[x]=0 dic2[x]+=1 k=sorted(dic2.items(), key=lambda kv: (kv[1], kv[0]), reverse=True) for z in k[:15]: print((dicvocab[z[0]],z[1]),end=',') print() print() print()
33.195122
441
0.71712
209
1,361
4.54067
0.401914
0.162276
0.213909
0.272919
0.094837
0
0
0
0
0
0
0.017456
0.116091
1,361
41
442
33.195122
0.771405
0
0
0.081081
0
0
0.380323
0.298091
0
0
0
0
0
1
0
false
0
0.135135
0
0.135135
0.189189
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
5cf9a7c1bb1d09d465374c4ca2f91186c8631750
345
py
Python
solvers/common/cell.py
andrinmeier/solvers
01c5ba29d6c880a9c22cb897ad0e7e006ab1816b
[ "MIT" ]
null
null
null
solvers/common/cell.py
andrinmeier/solvers
01c5ba29d6c880a9c22cb897ad0e7e006ab1816b
[ "MIT" ]
1
2022-03-31T14:10:33.000Z
2022-03-31T20:11:51.000Z
solvers/common/cell.py
andrinmeier/solvers
01c5ba29d6c880a9c22cb897ad0e7e006ab1816b
[ "MIT" ]
null
null
null
from typing import Optional class Cell: def __init__(self, row: int, column: int, value: int = None) -> None: self.row = row self.column = column self.value = value def set_value(self, new_value: int) -> None: self.value = new_value def get_value(self) -> Optional[int]: return self.value
23
73
0.611594
47
345
4.319149
0.382979
0.133005
0.118227
0
0
0
0
0
0
0
0
0
0.284058
345
14
74
24.642857
0.821862
0
0
0
0
0
0
0
0
0
0
0
0
1
0.3
false
0
0.1
0.1
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
cf0a981285b4ae44a0016c805a358ea2a5c148e3
324
py
Python
geometric_algebra_attention/keras/Multivector2Vector.py
klarh/geometric_algebra_attention
327f5d964b5bf72b6bf54b503c23ad8a0d7dc438
[ "MIT" ]
5
2021-10-14T22:24:00.000Z
2022-03-24T20:11:59.000Z
geometric_algebra_attention/keras/Multivector2Vector.py
klarh/geometric_algebra_attention
327f5d964b5bf72b6bf54b503c23ad8a0d7dc438
[ "MIT" ]
1
2021-12-03T18:51:19.000Z
2021-12-03T18:51:19.000Z
geometric_algebra_attention/keras/Multivector2Vector.py
klarh/geometric_algebra_attention
327f5d964b5bf72b6bf54b503c23ad8a0d7dc438
[ "MIT" ]
2
2021-10-14T22:26:07.000Z
2022-03-24T20:23:05.000Z
from tensorflow import keras from .. import base class Multivector2Vector(base.Multivector2Vector, keras.layers.Layer): __doc__ = base.Multivector2Vector.__doc__ def call(self, inputs, mask=None): return self._evaluate(inputs) keras.utils.get_custom_objects()['Multivector2Vector'] = Multivector2Vector
24.923077
75
0.771605
35
324
6.828571
0.628571
0.1841
0
0
0
0
0
0
0
0
0
0.017857
0.135802
324
12
76
27
0.835714
0
0
0
0
0
0.055728
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0.142857
0.857143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
cf0cc6c5c4f6131b0f8dc9785310f78758084d2b
603
py
Python
accounts/admin.py
lakshaykhatter/djangox-project-attempt
754d6ce58af06855125db3654e3a92b1c854883e
[ "MIT" ]
null
null
null
accounts/admin.py
lakshaykhatter/djangox-project-attempt
754d6ce58af06855125db3654e3a92b1c854883e
[ "MIT" ]
null
null
null
accounts/admin.py
lakshaykhatter/djangox-project-attempt
754d6ce58af06855125db3654e3a92b1c854883e
[ "MIT" ]
null
null
null
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username'] fieldsets = UserAdmin.fieldsets + ( ("Bio", {'fields': ('bio',)}), ("Social Media links", {'fields': ('instagram_url','tiktok_url','twitter_url','youtube_url',)}), ) admin.site.register(CustomUser, CustomUserAdmin)
31.736842
131
0.769486
66
603
6.909091
0.545455
0.065789
0.111842
0.092105
0
0
0
0
0
0
0
0
0.107794
603
19
132
31.736842
0.847584
0
0
0
0
0
0.155629
0
0
0
0
0
0
1
0
false
0
0.357143
0
0.785714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
cf10c6d9fa3cd81af14cc3cf34915ce513e1c988
2,290
py
Python
src/Service/Sandbox/runners/PythonRunner/test_frameworks/ck1_test/__init__.py
jakhax/code-runner-sandbox
049bc2ae6c581decff06291140d72f223e997137
[ "MIT" ]
null
null
null
src/Service/Sandbox/runners/PythonRunner/test_frameworks/ck1_test/__init__.py
jakhax/code-runner-sandbox
049bc2ae6c581decff06291140d72f223e997137
[ "MIT" ]
null
null
null
src/Service/Sandbox/runners/PythonRunner/test_frameworks/ck1_test/__init__.py
jakhax/code-runner-sandbox
049bc2ae6c581decff06291140d72f223e997137
[ "MIT" ]
null
null
null
import unittest import traceback from time import perf_counter class CodeKombatTestRunner(object): def __init__(self): pass def run(self, test): r = CodeKombatTestResult() s = perf_counter() print("\n<DESCRIBE::>Tests") try: test(r) finally: pass print("\n<COMPLETEDIN::>{:.4f}".format(1000*(perf_counter() - s))) return r __unittest = True class CodeKombatTestResult(unittest.TestResult): def __init__(self): super().__init__() self.start = 0.0 def startTest(self, test): print("\n<IT::>" + test._testMethodName) super().startTest(test) self.start = perf_counter() def stopTest(self, test): print("\n<COMPLETEDIN::>{:.4f}".format(1000*(perf_counter() - self.start))) super().stopTest(test) def addSuccess(self, test): print("\n<PASSED::>Test Passed") super().addSuccess(test) def addError(self, test, err): print("\n<ERROR::>Unhandled Exception") print("\n<LOG:ESC:Error>" + esc(''.join(traceback.format_exception_only(err[0], err[1])))) print("\n<LOG:ESC:Traceback>" + esc(self._exc_info_to_string(err, test))) super().addError(test, err) def addFailure(self, test, err): print("\n<FAILED::>Test Failed") print("\n<LOG:ESC:Failure>" + esc(''.join(traceback.format_exception_only(err[0], err[1])))) super().addFailure(test, err) # from unittest/result.py def _exc_info_to_string(self, err, test): exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: length = self._count_relevant_tb_levels(tb) # Skip assert*() traceback levels else: length = None return ''.join(traceback.format_tb(tb, limit=length)) def _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def esc(s): return s.replace("\n", "<:LF:>")
31.805556
100
0.60524
287
2,290
4.623693
0.303136
0.045215
0.02939
0.03165
0.185381
0.159759
0.125094
0.125094
0.064808
0.064808
0
0.010526
0.253275
2,290
71
101
32.253521
0.765497
0.038865
0
0.034483
0
0
0.101957
0.030496
0
0
0
0
0
1
0.206897
false
0.051724
0.051724
0.034483
0.37931
0.172414
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
cf2215f3d2c850c77ba0ec41befba0d5ea8de6de
1,013
py
Python
sdk/ml/azure-ai-ml/tests/online_services/unittests/test_resource_requirements_settings.py
dubiety/azure-sdk-for-python
62ffa839f5d753594cf0fe63668f454a9d87a346
[ "MIT" ]
1
2022-02-01T18:50:12.000Z
2022-02-01T18:50:12.000Z
sdk/ml/azure-ai-ml/tests/online_services/unittests/test_resource_requirements_settings.py
ellhe-blaster/azure-sdk-for-python
82193ba5e81cc5e5e5a5239bba58abe62e86f469
[ "MIT" ]
null
null
null
sdk/ml/azure-ai-ml/tests/online_services/unittests/test_resource_requirements_settings.py
ellhe-blaster/azure-sdk-for-python
82193ba5e81cc5e5e5a5239bba58abe62e86f469
[ "MIT" ]
null
null
null
import pytest from azure.ai.ml.entities import ResourceSettings @pytest.mark.unittest class TestResourceRequirementsSettings: def test_resource_requirements_settings_from_object(self) -> None: rest_resource_settings = ResourceSettings(cpu="1", memory="1.0Gi", gpu="1") resource_settings = ResourceSettings._from_rest_object(settings=rest_resource_settings) assert resource_settings.cpu == rest_resource_settings.cpu assert resource_settings.memory == rest_resource_settings.memory assert resource_settings.gpu == rest_resource_settings.gpu def test_resource_requirements_settings_to_objects(self) -> None: resource_settings = ResourceSettings(cpu="1", memory="1.0Gi", gpu="1") rest_resource_settings = resource_settings._to_rest_object() assert resource_settings.cpu == rest_resource_settings.cpu assert resource_settings.memory == rest_resource_settings.memory assert resource_settings.gpu == rest_resource_settings.gpu
48.238095
95
0.773939
119
1,013
6.226891
0.243697
0.388664
0.242915
0.072874
0.634278
0.539811
0.539811
0.539811
0.539811
0.539811
0
0.009259
0.147088
1,013
20
96
50.65
0.84838
0
0
0.375
0
0
0.01382
0
0
0
0
0
0.375
1
0.125
false
0
0.125
0
0.3125
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
cf22e5b27bb848a7487923ed2552186be004e856
1,230
py
Python
soda/core/soda/telemetry/memory_span_exporter.py
duyet/soda-core
92a52e0d7c1e88624d0637123cfcb2610af6d112
[ "Apache-2.0" ]
4
2022-03-23T02:43:42.000Z
2022-03-31T15:20:54.000Z
soda/core/soda/telemetry/memory_span_exporter.py
duyet/soda-core
92a52e0d7c1e88624d0637123cfcb2610af6d112
[ "Apache-2.0" ]
543
2022-03-22T09:02:17.000Z
2022-03-31T16:29:41.000Z
soda/core/soda/telemetry/memory_span_exporter.py
duyet/soda-core
92a52e0d7c1e88624d0637123cfcb2610af6d112
[ "Apache-2.0" ]
1
2022-03-27T03:37:55.000Z
2022-03-27T03:37:55.000Z
import json from typing import Dict, List, Sequence from opentelemetry.sdk.trace import ReadableSpan from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult class MemorySpanExporter(SpanExporter): """Implementation of :class:`SpanExporter` that saves spans in memory. This class can be used for diagnostic purposes, multi-threaded scenarios etc. """ __instance = None __spans = [] @staticmethod def get_instance(): if MemorySpanExporter.__instance is None: MemorySpanExporter() return MemorySpanExporter.__instance def __init__(self): if MemorySpanExporter.__instance is not None: raise Exception("This class is a singleton!") else: MemorySpanExporter.__instance = self def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: for span in spans: self.__spans.append(span) return SpanExportResult.SUCCESS def reset(self): self.__spans = [] @property def spans(self) -> List[ReadableSpan]: return self.__spans @property def span_dicts(self) -> List[Dict]: return [json.loads(span.to_json()) for span in self.spans]
27.954545
81
0.679675
132
1,230
6.143939
0.439394
0.055487
0.049322
0.061652
0
0
0
0
0
0
0
0
0.239837
1,230
43
82
28.604651
0.86738
0.118699
0
0.068966
0
0
0.024322
0
0
0
0
0
0
1
0.206897
false
0
0.137931
0.068966
0.586207
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
cf3453b50dda53baa027b0bcfd23dbe385ff3da8
1,234
py
Python
setup.py
Yasumoto/sapling
73c51a2f93441ab9c03441b4864cf735e57c8e2a
[ "Apache-2.0" ]
24
2015-02-10T18:44:17.000Z
2021-04-02T13:29:54.000Z
setup.py
Yasumoto/sapling
73c51a2f93441ab9c03441b4864cf735e57c8e2a
[ "Apache-2.0" ]
2
2015-08-26T02:01:29.000Z
2018-11-05T19:02:34.000Z
setup.py
Yasumoto/sapling
73c51a2f93441ab9c03441b4864cf735e57c8e2a
[ "Apache-2.0" ]
3
2015-12-13T08:32:49.000Z
2020-03-06T19:13:02.000Z
from setuptools import setup from sapversion import version setup( name = 'sapling', version = version(), author = 'John Sirois', author_email = 'john.sirois@gmail.com', description = 'A git porcelain to manage bidirectional subtree syncing with foreign git ' 'repositories', license = 'Apache License Version 2.0', url = 'http://github.com/jsirois/sapling', provides = 'sapling', install_requires = ( 'gitdb >= 0.5.1', 'GitPython > 0.2, < 0.4', ), packages = [ 'saplib', 'sapversion' ], package_data = { 'sapversion': [ 'version.txt' ] }, scripts = [ 'sapling.py' ], classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', # TODO(jsirois): the sapling.py --install action is actually unix/symlink dependant - # perhaps detect windows and just copy the sapling.py script to git-core/git-sap ? 'Operating System :: OS Independent', 'Topic :: Software Development :: Version Control' ], )
30.097561
93
0.619125
132
1,234
5.765152
0.674242
0.03548
0.065703
0
0
0
0
0
0
0
0
0.012987
0.251216
1,234
40
94
30.85
0.810606
0.132901
0
0
0
0
0.524836
0.019681
0
0
0
0.025
0
1
0
true
0
0.066667
0
0.066667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
1
0
0
0
0
0
0
2
cf35fe110ed3af6b7439bbe3ebaf4b01b4c2e0d8
200
py
Python
BAEKJOON/Python/23806.py
cmsong111/NJ_code
2df6176d179e168a2789a825ddeb977a82eb8d97
[ "MIT" ]
null
null
null
BAEKJOON/Python/23806.py
cmsong111/NJ_code
2df6176d179e168a2789a825ddeb977a82eb8d97
[ "MIT" ]
null
null
null
BAEKJOON/Python/23806.py
cmsong111/NJ_code
2df6176d179e168a2789a825ddeb977a82eb8d97
[ "MIT" ]
null
null
null
count = int(input()) for i in range(count): print("@"*(count*5)) for i in range(count*3): print("@"*(count)," "*(count*3),"@"*(count),sep="") for i in range(count): print("@"*(count*5))
20
55
0.54
31
200
3.483871
0.354839
0.111111
0.166667
0.305556
0.648148
0.5
0.5
0.5
0
0
0
0.023952
0.165
200
10
56
20
0.622754
0
0
0.571429
0
0
0.024876
0
0
0
0
0
0
1
0
false
0
0
0
0
0.428571
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
cf3b1afdd01e9db4470b50c71ad86d907678aa51
196
py
Python
06. Django + React.js apps/Todo app with CRUD functionality/backend/todolistapp/todoapp/urls.py
rexsimiloluwah/Python-Experiments
63291ab7fe11e61cce2a936dd41b31f0eb35cc1f
[ "MIT" ]
1
2021-01-21T11:39:07.000Z
2021-01-21T11:39:07.000Z
06. Django + React.js apps/Todo app with CRUD functionality/backend/todolistapp/todoapp/urls.py
rexsimiloluwah/Python-Experiments
63291ab7fe11e61cce2a936dd41b31f0eb35cc1f
[ "MIT" ]
null
null
null
06. Django + React.js apps/Todo app with CRUD functionality/backend/todolistapp/todoapp/urls.py
rexsimiloluwah/Python-Experiments
63291ab7fe11e61cce2a936dd41b31f0eb35cc1f
[ "MIT" ]
1
2021-01-21T11:39:19.000Z
2021-01-21T11:39:19.000Z
from django.urls import path from .views import TodoView, TodoDetailView urlpatterns = [ path('tasks', TodoView.as_view()), path('tasks/<int:id>', TodoDetailView.as_view()), ]
19.6
54
0.668367
23
196
5.608696
0.608696
0.139535
0
0
0
0
0
0
0
0
0
0
0.188776
196
10
55
19.6
0.811321
0
0
0
0
0
0.096447
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
cf3fbcf2fb4c741b1eea2adbe119fe0d876a02e8
1,374
py
Python
etabli/dquery.py
antoine-gallix/dev_tools
9d55c7a1e52b9a1cee1d80d3d0cf8bf40ef125c9
[ "MIT" ]
null
null
null
etabli/dquery.py
antoine-gallix/dev_tools
9d55c7a1e52b9a1cee1d80d3d0cf8bf40ef125c9
[ "MIT" ]
null
null
null
etabli/dquery.py
antoine-gallix/dev_tools
9d55c7a1e52b9a1cee1d80d3d0cf8bf40ef125c9
[ "MIT" ]
null
null
null
"""Classes to filter dictionaries """ from pprint import pformat class Filter_Equal: def __init__(self, key, value): self.key = key self.value = value def __call__(self, d): return d[self.key] == self.value class Filter_Keys: def __init__(self, keys): self.keys = keys def __call__(self, d): return {key: d[key] for key in self.keys} class Query(dict): def filter_keys(self, keys): """Select a subset of items keys : list of keys to keep """ return Query(Filter_Keys(keys)(self)) def apply(self, func, key): """Apply filter to item func : filter function key : item key """ obj = self.copy() obj[key] = list(map(func, obj[key])) return Query(obj) def filter(self, func, key): """Apply filter to item func : filter function key : item key """ obj = self.copy() obj[key] = list(filter(func, obj[key])) return Query(obj) def get(self, key): """Get element key : item key """ obj = self.get(key) return Query(obj) def get_path(self, path): """Get element path : list of keys """ obj = self for key in path: obj = obj[key] return Query(obj)
19.913043
49
0.526929
175
1,374
4.017143
0.228571
0.078236
0.079659
0.096728
0.4367
0.332859
0.295875
0.219061
0.219061
0.219061
0
0
0.359534
1,374
68
50
20.205882
0.798864
0.192868
0
0.258065
0
0
0
0
0
0
0
0
0
1
0.290323
false
0
0.032258
0.064516
0.645161
0.032258
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
cf51fb0a687304d6915ac8357600edc9bc78ac6c
256
py
Python
rateApp/urls.py
enockabere/Project_Rating
b50d1474927b94d3d08a708eaff026e91ec9f950
[ "Unlicense" ]
null
null
null
rateApp/urls.py
enockabere/Project_Rating
b50d1474927b94d3d08a708eaff026e91ec9f950
[ "Unlicense" ]
null
null
null
rateApp/urls.py
enockabere/Project_Rating
b50d1474927b94d3d08a708eaff026e91ec9f950
[ "Unlicense" ]
null
null
null
from django.urls import path,include from . import views urlpatterns = [ path('api/projects/', views.ProjectList.as_view()), path('api/projects/profile', views.ProfileList.as_view()), path('api/projects/ratings', views.RatingList.as_view()), ]
32
62
0.71875
33
256
5.484848
0.515152
0.116022
0.248619
0.143646
0.232044
0
0
0
0
0
0
0
0.117188
256
8
63
32
0.800885
0
0
0
0
0
0.206226
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
cf571f1032d71d97c904c8951ea3ac1d6579fde4
2,089
py
Python
tests/test_projectq_import.py
rmoyard/pennylane-pq
e229f5fe38a1330b3e3a84080f72ced4a2b55a65
[ "Apache-2.0" ]
2
2020-08-17T14:46:01.000Z
2020-08-19T02:41:51.000Z
tests/test_projectq_import.py
rmoyard/pennylane-pq
e229f5fe38a1330b3e3a84080f72ced4a2b55a65
[ "Apache-2.0" ]
12
2020-08-17T14:00:27.000Z
2022-03-28T20:16:10.000Z
tests/test_projectq_import.py
rmoyard/pennylane-pq
e229f5fe38a1330b3e3a84080f72ced4a2b55a65
[ "Apache-2.0" ]
2
2020-08-17T14:46:07.000Z
2021-08-03T15:06:17.000Z
# Copyright 2018 Xanadu Quantum Technologies 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. """ Unit tests for the :mod:`pennylane_pq` devices' behavior when applying unsupported operations. """ import unittest import logging as log import sys from unittest import mock from pkg_resources import iter_entry_points from defaults import pennylane as qml, BaseTest log.getLogger('defaults') class ProjectQImportTest(BaseTest): """test of projectq import. """ def test_projectq_import(self): """Check that from projectq.ops import MatrixGate can raise an exception without problems, this ensures backward compatibility with older versions of ProjectQ """ del sys.modules["pennylane_pq.pqops"] import projectq.ops if 'MatrixGate' in projectq.ops.__dict__: del projectq.ops.__dict__['MatrixGate'] import pennylane_pq.pqops del sys.modules["pennylane_pq.pqops"] import projectq.ops if 'MatrixGate' not in projectq.ops.__dict__: projectq.ops.__dict__['MatrixGate'] = projectq.ops.__dict__['BasicGate'] import pennylane_pq.pqops # restore del sys.modules["projectq.ops"] import pennylane_pq.pqops if __name__ == '__main__': print('Testing PennyLane ProjectQ Plugin version ' + qml.version() + ', import test.') # run the tests in this file suite = unittest.TestSuite() for t in (ProjectQImportTest, ): ttt = unittest.TestLoader().loadTestsFromTestCase(t) suite.addTests(ttt) unittest.TextTestRunner().run(suite)
34.816667
166
0.716611
268
2,089
5.440299
0.492537
0.067901
0.05487
0.045267
0.079561
0.079561
0.079561
0.079561
0.079561
0.079561
0
0.004799
0.202011
2,089
59
167
35.40678
0.869826
0.428435
0
0.25
0
0
0.145064
0
0
0
0
0
0
1
0.035714
false
0
0.535714
0
0.607143
0.035714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
cf6239aa8d4a645b53190ef28a34898e081f0419
365
py
Python
papers/PACMOO/utils.py
mindspore-ai/contrib
85dccac7a2ba6e962092ecd51aefd962d7f2aeac
[ "Apache-2.0" ]
2
2021-11-10T06:16:55.000Z
2022-02-22T11:30:04.000Z
papers/PACMOO/utils.py
mindspore-ai/contrib
85dccac7a2ba6e962092ecd51aefd962d7f2aeac
[ "Apache-2.0" ]
null
null
null
papers/PACMOO/utils.py
mindspore-ai/contrib
85dccac7a2ba6e962092ecd51aefd962d7f2aeac
[ "Apache-2.0" ]
1
2022-03-22T06:03:15.000Z
2022-03-22T06:03:15.000Z
""" :author: hxq, shy """ import numpy as np from mindspore import ops DIV = ops.Div() def l2_regularizer(input_x, axis=1): """ :param input_x: :param axis: :return: """ return DIV(input_x, ((input_x**2).sum(axis=axis, keepdims=True))**0.5) def set_rng_seed(seed): """ :param seed: :return: """ np.random.seed(seed)
14.6
74
0.583562
53
365
3.886792
0.566038
0.116505
0
0
0
0
0
0
0
0
0
0.017986
0.238356
365
24
75
15.208333
0.723022
0.210959
0
0
0
0
0
0
0
0
0
0
0
1
0.285714
false
0
0.285714
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
cf67b619d87d5ce5eeae0b24a7585eb4348c40f3
896
py
Python
tests/dtqw/mesh/percolation/test_permanent.py
alfabr90/sparkquantum
e17ec73c0ba0a7a244419cc1ac99c5c6a181db1a
[ "MIT" ]
2
2020-04-07T18:25:03.000Z
2020-04-07T18:25:21.000Z
tests/dtqw/mesh/percolation/test_permanent.py
alfabr90/sparkquantum
e17ec73c0ba0a7a244419cc1ac99c5c6a181db1a
[ "MIT" ]
null
null
null
tests/dtqw/mesh/percolation/test_permanent.py
alfabr90/sparkquantum
e17ec73c0ba0a7a244419cc1ac99c5c6a181db1a
[ "MIT" ]
null
null
null
import unittest from tests.base import Base from sparkquantum.dtqw.mesh.percolation.percolation import is_percolation from sparkquantum.dtqw.mesh.percolation.permanent import Permanent, is_permanent # TODO: implement test_generate class TestPermanent(Base): def setUp(self): super().setUp() self.edges = [2, 4] self.percolation = Permanent(self.edges) def test_is_percolation(self): self.assertTrue(is_percolation(self.percolation)) def test_str(self): self.assertEqual(str(self.percolation), 'Permanent percolations generator with {} percolations'.format(len(self.edges))) def test_is_permanent(self): self.assertTrue(is_permanent(self.percolation)) def test_edges(self): self.assertTupleEqual(self.percolation.edges, tuple(self.edges)) if __name__ == '__main__': unittest.main()
28
105
0.708705
104
896
5.923077
0.355769
0.121753
0.064935
0.077922
0.172078
0
0
0
0
0
0
0.002755
0.189732
896
31
106
28.903226
0.84573
0.032366
0
0
0
0
0.07052
0
0
0
0
0.032258
0.2
1
0.25
false
0
0.2
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
0
0
0
0
0
0
2
cf6f2fdeb86ed51353e8adf7aa58ca052fa342b7
338
py
Python
bookmarks/models.py
jlugao/elephant-bot
e764573fba133c6ec4acde0634505e41f84f803f
[ "Apache-2.0" ]
null
null
null
bookmarks/models.py
jlugao/elephant-bot
e764573fba133c6ec4acde0634505e41f84f803f
[ "Apache-2.0" ]
null
null
null
bookmarks/models.py
jlugao/elephant-bot
e764573fba133c6ec4acde0634505e41f84f803f
[ "Apache-2.0" ]
null
null
null
from django.db import models from utils.models import CreateUpdateTracker, nb, GetOrNoneManager from taggit.managers import TaggableManager # Create your models here. class Bookmark(CreateUpdateTracker): user = models.ForeignKey("tgbot.User", on_delete=models.CASCADE) url = models.URLField(**nb) tags = TaggableManager()
26
68
0.775148
39
338
6.692308
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.139053
338
12
69
28.166667
0.896907
0.071006
0
0
0
0
0.032051
0
0
0
0
0
0
1
0
false
0
0.428571
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
cf73022d4934564176367a695184cf012d8ff519
1,717
py
Python
vdibroker/db/sqlalchemy/types.py
cloudbase/vdi-broker
e6250d65f62fbc9f8d1c0026208bc318b6161c83
[ "Apache-2.0" ]
29
2017-05-10T20:04:55.000Z
2021-11-19T04:50:40.000Z
vdibroker/db/sqlalchemy/types.py
cloudbase/vdi-broker
e6250d65f62fbc9f8d1c0026208bc318b6161c83
[ "Apache-2.0" ]
1
2017-11-21T15:24:56.000Z
2020-12-29T11:30:07.000Z
vdibroker/db/sqlalchemy/types.py
cloudbase/vdi-broker
e6250d65f62fbc9f8d1c0026208bc318b6161c83
[ "Apache-2.0" ]
17
2017-07-18T09:50:35.000Z
2021-12-23T12:22:49.000Z
# Copyright 2016 Cloudbase Solutions Srl # 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. from oslo_serialization import jsonutils from sqlalchemy.dialects import mysql from sqlalchemy import types class LongText(types.TypeDecorator): impl = types.Text def load_dialect_impl(self, dialect): if dialect.name == 'mysql': return dialect.type_descriptor(mysql.LONGTEXT()) else: return self.impl class Json(LongText): def process_bind_param(self, value, dialect): return jsonutils.dumps(value) def process_result_value(self, value, dialect): if value is None: return None return jsonutils.loads(value) class List(types.TypeDecorator): impl = types.Text def load_dialect_impl(self, dialect): if dialect.name == 'mysql': return dialect.type_descriptor(mysql.LONGTEXT()) else: return self.impl def process_bind_param(self, value, dialect): return jsonutils.dumps(value) def process_result_value(self, value, dialect): if value is None: return None return jsonutils.loads(value)
28.616667
78
0.685498
221
1,717
5.257919
0.457014
0.051635
0.055077
0.027539
0.483649
0.483649
0.483649
0.483649
0.483649
0.483649
0
0.006144
0.241701
1,717
59
79
29.101695
0.886329
0.354688
0
0.8
0
0
0.009149
0
0
0
0
0
0
1
0.2
false
0
0.1
0.066667
0.8
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
cf850a6e6ee611e8ea993e5d6c53ca7432236b2d
123
py
Python
src/genie/libs/parser/generic/tests/ShowVersion/cli/equal/golden_output_ios_3_expected.py
ykoehler/genieparser
b62cf622c3d8eab77c7b69e932c214ed04a2565a
[ "Apache-2.0" ]
null
null
null
src/genie/libs/parser/generic/tests/ShowVersion/cli/equal/golden_output_ios_3_expected.py
ykoehler/genieparser
b62cf622c3d8eab77c7b69e932c214ed04a2565a
[ "Apache-2.0" ]
null
null
null
src/genie/libs/parser/generic/tests/ShowVersion/cli/equal/golden_output_ios_3_expected.py
ykoehler/genieparser
b62cf622c3d8eab77c7b69e932c214ed04a2565a
[ "Apache-2.0" ]
null
null
null
expected_output = { 'pid': 'CISCO3945-CHASSIS', 'os': 'ios', 'platform': 'c3900', 'version': '15.0(1)M7', }
20.5
31
0.528455
14
123
4.571429
1
0
0
0
0
0
0
0
0
0
0
0.135417
0.219512
123
6
32
20.5
0.53125
0
0
0
0
0
0.435484
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
cf85ee5002545689e378db4eb7a20ca699c82d2e
4,877
py
Python
tests/unit/rjgtoys/xc/test_raises_basics.py
bobgautier/rjgtoys-xc
f20a352633b6e1781af213a5a307cb0017ddc830
[ "MIT" ]
2
2020-09-19T17:03:13.000Z
2021-05-28T21:04:25.000Z
tests/unit/rjgtoys/xc/test_raises_basics.py
bobgautier/rjgtoys-xc
f20a352633b6e1781af213a5a307cb0017ddc830
[ "MIT" ]
null
null
null
tests/unit/rjgtoys/xc/test_raises_basics.py
bobgautier/rjgtoys-xc
f20a352633b6e1781af213a5a307cb0017ddc830
[ "MIT" ]
null
null
null
""" Test the constraint mechanisms in rjgtoys.xc.raises """ from rjgtoys.xc.raises import raises, may_raise, raises_exception from rjgtoys.xc import BadExceptionBug, BadExceptionsInTestBug import pytest from unittest.mock import patch # Fixtures class Allowed1(Exception): """First allowed exception.""" pass class Allowed2(Exception): """Second allowed exception.""" pass def raise_a1(): raise Allowed1() def test_default_may_raise(): """The raise_a1() function has the correct constraint and works correctly.""" # Constraint was not given, so it can do anything assert may_raise(raise_a1) == set((Exception,)) # It always raises the exception. with pytest.raises(Allowed1): raise_a1() @raises(Allowed2) def raise_a2(x): """A function that sometimes raises Allowed2.""" if x: raise Allowed2() def test_raises_decorator(): """The constraint on raises_a2 has been correctly recorded.""" assert raise_a2._raises__xc_raises == (Allowed2,) @raises(Allowed1) def raise_bad(x): """This function can raise a bad exception.""" if x: raise Allowed1() raise Allowed2() @raises(None) def may_not_raise(): """This function is not allowed to raise any exceptions, but does.""" raise Allowed2() def test_raise_bad(): """Test that the may_not_raise() function works as expected.""" with pytest.raises(BadExceptionBug): may_not_raise() def test_raise_ok(): """Test that raise_a2() works as expected.""" with pytest.raises(Allowed2): raise_a2(True) # Does not raise... raise_a2(False) # raise_bad behaves as expected with pytest.raises(Allowed1): raise_bad(True) with pytest.raises(BadExceptionBug): raise_bad(False) def test_try_behaviour_assumptions(): """Test that Python except clauses work as expected.""" x = [] try: x.append('start') raise Allowed1() x.append('notreached') except () as e: raise Exception("Caught nothing") except Allowed1 as e: x.append('caught') assert x == ['start','caught'] # # Set up and try the test fixture stuff # class LowerEx(Exception): """May be raised by a low level function""" pass class LowerEx1(LowerEx): """A subclass of :class:`LowerEx`""" pass class OtherEx(Exception): """An exception unrelated to :class:`LowerEx`""" pass @raises(LowerEx,OtherEx,LowerEx1) def lower(x): """Low-level function that may raise an exception.""" if x: raise LowerEx() def upper(x): """Upper-level function that catches an exception.""" try: lower(x) return None except Exception as e: print("lower raised %s" % (repr(e))) return e def test_raises_exception(): """The raises_exception function generates the exceptions it is passed.""" print("lower may raise %s" % (may_raise(lower))) # Pretend that the lower() function raises some different exceptions exceptions = [LowerEx(), LowerEx1()] results = [] for _ in raises_exception(__name__+'.lower',*exceptions): # print "Here we go..." results.append(upper(False)) assert results == exceptions def test_raises_exception_detects_bad_list(): """Tests that raises_exception refuses to raise an exception that the target is not declared capable of raising """ print("lower may raise %s" %(may_raise(lower))) with pytest.raises(BadExceptionsInTestBug): for _ in raises_exception(__name__+'.lower',Exception('bang'),LowerEx(),LowerEx1()): upper(False) # # Test awkward cases in raises_exception: # # Something goes wrong with the exception list # class UnexpectedExc(Exception): """ This is raised by my fake Raiser to trigger some error paths """ pass class BadRaiser(object): """Replaces _raises.Raiser with a rogue implementation that always raises an unexpected and disallowed exception type""" def __init__(self): pass def configure(self, exceptions): pass def __call__(self,*args,**kwargs): raise UnexpectedExc() class NonRaiser(object): """Replaces _raises.Raiser with a rogue implementation that fails to raise an exception""" def __init__(self): pass def configure(self, exceptions): pass def __call__(self,*args,**kwargs): return def test_raises_exception_error_case(): with patch('rjgtoys.xc.raises.Raiser',BadRaiser): for _ in raises_exception(__name__+'.lower',LowerEx(),LowerEx1()): upper(False) def test_raises_exception_nonraising_case(): with patch('rjgtoys.xc.raises.Raiser',NonRaiser): for _ in raises_exception(__name__+'.lower',LowerEx(),LowerEx1()): upper(False)
21.021552
92
0.661062
601
4,877
5.196339
0.262895
0.057637
0.03074
0.028178
0.213897
0.192123
0.153698
0.131924
0.111431
0.076849
0
0.008495
0.227599
4,877
231
93
21.112554
0.820547
0.312897
0
0.368932
0
0
0.054181
0.015033
0
0
0
0
0.038835
1
0.203884
false
0.097087
0.038835
0.009709
0.349515
0.029126
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
d83dc036c13b6c16c8316be498b029548f3f5345
997
py
Python
okdata/sdk/permission/user_types.py
oslokommune/okdata-sdk-python
39d9f79b96b2fe4c33136bc9344043f33cc0ee4c
[ "MIT" ]
2
2021-01-13T06:53:04.000Z
2021-08-02T05:14:06.000Z
okdata/sdk/permission/user_types.py
oslokommune/okdata-sdk-python
39d9f79b96b2fe4c33136bc9344043f33cc0ee4c
[ "MIT" ]
4
2021-04-21T06:14:36.000Z
2021-08-03T08:35:14.000Z
okdata/sdk/permission/user_types.py
oslokommune/okdata-sdk-python
39d9f79b96b2fe4c33136bc9344043f33cc0ee4c
[ "MIT" ]
1
2021-08-02T05:14:09.000Z
2021-08-02T05:14:09.000Z
# TODO: Use these simplified dataclasses once support for Python 3.6 is # dropped. Meanwhile we'll use the "polyfill" classes defined below. # # from dataclasses import dataclass, field # # @dataclass # class Client: # user_id: str # user_type: str = field(default="client", init=False) # # # @dataclass # class Team: # user_id: str # user_type: str = field(default="team", init=False) # # # @dataclass # class User: # user_id: str # user_type: str = field(default="user", init=False) class Client: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "client" class Team: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "team" class User: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "user" def asdict(obj): return obj.__dict__
18.811321
71
0.642929
141
997
4.262411
0.29078
0.14975
0.08985
0.129784
0.580699
0.580699
0.580699
0.580699
0.324459
0.324459
0
0.00267
0.248746
997
52
72
19.173077
0.799733
0.467402
0
0.6
0
0
0.027505
0
0
0
0
0.019231
0
1
0.2
false
0
0
0.05
0.7
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
1
0
0
2
d83ead17e7240cba519bb5e00d5b470cc24573f7
286
py
Python
ABC/abc051-abc100/abc055/b.py
KATO-Hiro/AtCoder
cbbdb18e95110b604728a54aed83a6ed6b993fde
[ "CC0-1.0" ]
2
2020-06-12T09:54:23.000Z
2021-05-04T01:34:07.000Z
ABC/abc051-abc100/abc055/b.py
KATO-Hiro/AtCoder
cbbdb18e95110b604728a54aed83a6ed6b993fde
[ "CC0-1.0" ]
961
2020-06-23T07:26:22.000Z
2022-03-31T21:34:52.000Z
ABC/abc051-abc100/abc055/b.py
KATO-Hiro/AtCoder
cbbdb18e95110b604728a54aed83a6ed6b993fde
[ "CC0-1.0" ]
null
null
null
'''input 100000 457992974 3 6 10 3628800 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': from math import factorial training_count = int(input()) print(factorial(training_count) % (10 ** 9 + 7))
11.44
53
0.58042
33
286
4.727273
0.848485
0.217949
0.282051
0
0
0
0
0
0
0
0
0.152709
0.29021
286
24
54
11.916667
0.615764
0.339161
0
0
0
0
0.051613
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.25
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d849235fea8740c9dde6dc042e6617422a1ce9e6
1,753
py
Python
pokr/views/statement.py
teampopong/pokr.kr
6cdc32d81c299d75a8e565a3c1478f4e44df0360
[ "Apache-2.0" ]
76
2015-01-19T12:39:43.000Z
2021-10-14T06:10:25.000Z
pokr/views/statement.py
teampopong/pokr.kr
6cdc32d81c299d75a8e565a3c1478f4e44df0360
[ "Apache-2.0" ]
22
2015-01-03T01:00:53.000Z
2019-09-14T11:55:06.000Z
pokr/views/statement.py
teampopong/pokr.kr
6cdc32d81c299d75a8e565a3c1478f4e44df0360
[ "Apache-2.0" ]
28
2015-01-14T15:45:00.000Z
2020-06-03T13:29:41.000Z
#!/usr/bin/env python # -*- encoding: utf-8 -*- from datetime import date import os.path import re from flask import abort, current_app, render_template, redirect, request, send_file, url_for from flask.ext.babel import gettext, format_date from sqlalchemy import and_ from sqlalchemy.orm import undefer, undefer_group from sqlalchemy.orm.exc import NoResultFound from pokr.cache import cache from pokr.database import db_session from pokr.models.statement import Statement from pokr.views.meeting import generate_glossary_js from pokr.widgets.year import year from utils.jinja import breadcrumb def register(app): app.views['statement'] = 'statement_main' gettext('statement') # for babel extraction @app.route('/statement/', methods=['GET']) @breadcrumb(app) def statement_main(): statements = Statement.query return render_template('statements.html', statements=statements) @app.route('/statement/<id>', methods=['GET']) @breadcrumb(app, 'statement') def statement(id): glossary_js = generate_glossary_js() try: statement = Statement.query.filter_by(id=id).one() except NoResultFound, e: abort(404) before_statement = Statement.query.filter(and_(\ Statement.meeting_id==statement.meeting_id, Statement.sequence==statement.sequence - 1)).first() next_statement = Statement.query.filter(and_(\ Statement.meeting_id==statement.meeting_id, Statement.sequence==statement.sequence + 1)).first() return render_template('statement.html', statement=statement,\ before=before_statement, next=next_statement, glossary_js=glossary_js)
33.075472
92
0.69652
208
1,753
5.725962
0.375
0.033585
0.060453
0.09068
0.18136
0.18136
0.18136
0.18136
0.18136
0.18136
0
0.004283
0.200799
1,753
52
93
33.711538
0.845824
0.037079
0
0.051282
0
0
0.060534
0
0
0
0
0
0
0
null
null
0
0.358974
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
d84db89f8bb8b23b91622b1fef840cf65fc1f8d3
687
py
Python
ils_loc_mapper/settings_app.py
birkin/ils_location_mapper_project
59b4b2a5b97092649f80f38580b8e229e2e2064a
[ "MIT" ]
null
null
null
ils_loc_mapper/settings_app.py
birkin/ils_location_mapper_project
59b4b2a5b97092649f80f38580b8e229e2e2064a
[ "MIT" ]
2
2020-06-05T19:19:12.000Z
2021-03-10T21:14:15.000Z
ils_loc_mapper/settings_app.py
birkin/ils_location_mapper_project
59b4b2a5b97092649f80f38580b8e229e2e2064a
[ "MIT" ]
1
2020-11-02T20:26:10.000Z
2020-11-02T20:26:10.000Z
# -*- coding: utf-8 -*- import json, os README_URL = os.environ['ILS_LOC_MPR__README_URL'] ## auth SUPER_USERS = json.loads( os.environ['ILS_LOC_MPR__SUPER_USERS_JSON'] ) STAFF_USERS = json.loads( os.environ['ILS_LOC_MPR__STAFF_USERS_JSON'] ) # users permitted access to admin STAFF_GROUP = os.environ['ILS_LOC_MPR__STAFF_GROUP'] # not grouper-group; rather, name of django-admin group for permissions TEST_META_DCT = json.loads( os.environ['ILS_LOC_MPR__TEST_META_DCT_JSON'] ) POST_LOGIN_ADMIN_REVERSE_URL = os.environ['ILS_LOC_MPR__POST_LOGIN_ADMIN_REVERSE_URL'] # tricky; for a direct-view of a model, the string would be in the form of: `admin:APP-NAME_MODEL-NAME_changelist`
49.071429
202
0.786026
116
687
4.232759
0.422414
0.10998
0.14664
0.183299
0.419552
0.327902
0.185336
0.130346
0
0
0
0.001631
0.107715
687
13
203
52.846154
0.799347
0.350801
0
0
0
0
0.403189
0.403189
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d85f71549d035c587ee70d47ce5fe31ded2c467e
1,014
py
Python
saleor/order/__init__.py
austineinstein/Dsaleor
d181f395f66bbaa7ba24edf9860a8f52c3c2af65
[ "BSD-3-Clause" ]
null
null
null
saleor/order/__init__.py
austineinstein/Dsaleor
d181f395f66bbaa7ba24edf9860a8f52c3c2af65
[ "BSD-3-Clause" ]
null
null
null
saleor/order/__init__.py
austineinstein/Dsaleor
d181f395f66bbaa7ba24edf9860a8f52c3c2af65
[ "BSD-3-Clause" ]
null
null
null
from django.apps import AppConfig from django.utils.translation import pgettext_lazy class OrderAppConfig(AppConfig): name = 'saleor.order' def ready(self): from payments.signals import status_changed from .signals import order_status_change status_changed.connect(order_status_change) class OrderStatus: UNFULFILLED = 'unfulfilled' PARTIALLY_FULFILLED = 'partially fulfilled' FULFILLED = 'fulfilled' CANCELED = 'canceled' CHOICES = [ (UNFULFILLED, pgettext_lazy('order status', 'Unfulfilled')), (PARTIALLY_FULFILLED, pgettext_lazy( 'order status', 'Partially fulfilled')), (FULFILLED, pgettext_lazy('order status', 'Fulfilled')), (CANCELED, pgettext_lazy('order status', 'Canceled'))] class FulfillmentStatus: FULFILLED = 'fulfilled' CANCELED = 'canceled' CHOICES = [ (FULFILLED, pgettext_lazy('order status', 'Fulfilled')), (CANCELED, pgettext_lazy('order status', 'Canceled'))]
28.971429
68
0.684418
97
1,014
7
0.309278
0.129602
0.150221
0.20324
0.403535
0.235641
0.235641
0.235641
0.235641
0.235641
0
0
0.209073
1,014
34
69
29.823529
0.846633
0
0
0.4
0
0
0.209073
0
0
0
0
0
0
1
0.04
false
0
0.16
0
0.68
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
d863aebfff144fa33466b0d7026410974d9c8595
418
py
Python
coding/python/day01/operations.py
dkapanidis/my-tutorials
f3b72c35487782609b556016aba03b275cc6b105
[ "MIT" ]
null
null
null
coding/python/day01/operations.py
dkapanidis/my-tutorials
f3b72c35487782609b556016aba03b275cc6b105
[ "MIT" ]
null
null
null
coding/python/day01/operations.py
dkapanidis/my-tutorials
f3b72c35487782609b556016aba03b275cc6b105
[ "MIT" ]
null
null
null
add = 3+2 print (add) subtract = 3-2 print (subtract) multiply = 3*2 print (multiply) division = 3/2 print (division) modulus = 3%2 print (modulus) lessThan = 3<2 print (lessThan) greaterThan = 3>2 print(greaterThan) equals = 3==3 print (equals) logicalAnd = (2==2) and (3==3) and (4==4) print (logicalAnd) logicalOr = (2==1) or (2==2) or (2==3) print (logicalOr) logicalNot = not (3==2) print (logicalNot)
12.294118
41
0.655502
68
418
4.029412
0.279412
0.058394
0.20438
0
0
0
0
0
0
0
0
0.087209
0.177033
418
33
42
12.666667
0.709302
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
d87300fd270142bce547f78097ac49bba8ab4b60
327
py
Python
masterserver/__init__.py
TheAssassin/python-masterserver
8a6f5168bd5374ff047cb2a8c67299a2a1a4fc7b
[ "MIT" ]
null
null
null
masterserver/__init__.py
TheAssassin/python-masterserver
8a6f5168bd5374ff047cb2a8c67299a2a1a4fc7b
[ "MIT" ]
null
null
null
masterserver/__init__.py
TheAssassin/python-masterserver
8a6f5168bd5374ff047cb2a8c67299a2a1a4fc7b
[ "MIT" ]
1
2020-12-18T15:17:15.000Z
2020-12-18T15:17:15.000Z
# first we need to import the logging module from ._logging import get_logger, setup_logging # noqa: F401 # then we make sure the codec is available from ._codec import register_codec register_codec() # now the regular imports may follow from .masterserver import MasterServer # noqa: F401 E402 __all__ = (MasterServer,)
25.153846
61
0.779817
47
327
5.212766
0.617021
0.065306
0
0
0
0
0
0
0
0
0
0.033088
0.168196
327
12
62
27.25
0.867647
0.443425
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d88766f6debf7c8e4659bf9a480c441e2c87dd2a
345
py
Python
monero_glue/misc/bip/bip39_deriv.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
20
2018-04-05T22:06:10.000Z
2021-09-18T10:43:44.000Z
monero_glue/misc/bip/bip39_deriv.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
null
null
null
monero_glue/misc/bip/bip39_deriv.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
5
2018-08-06T15:06:04.000Z
2021-07-16T01:58:43.000Z
import hashlib import hmac from Crypto.Protocol.KDF import PBKDF2 def mnemonics_to_seed(seed, passphrase=b""): salt = b"mnemonic" + passphrase def prf(p, s): hx = hmac.new(p, msg=s, digestmod=hashlib.sha512) return hx.digest() res = PBKDF2(password=seed, salt=salt, dkLen=64, prf=prf, count=2048) return res
21.5625
73
0.672464
51
345
4.509804
0.627451
0
0
0
0
0
0
0
0
0
0
0.040293
0.208696
345
15
74
23
0.802198
0
0
0
0
0
0.023188
0
0
0
0
0
0
1
0.2
false
0.3
0.3
0
0.7
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
d887ec97cfb7b09577411dad65c207085491fced
261
py
Python
output/models/nist_data/atomic/short/schema_instance/nistschema_sv_iv_atomic_short_max_exclusive_4_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/short/schema_instance/nistschema_sv_iv_atomic_short_max_exclusive_4_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/short/schema_instance/nistschema_sv_iv_atomic_short_max_exclusive_4_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.atomic.short.schema_instance.nistschema_sv_iv_atomic_short_max_exclusive_4_xsd.nistschema_sv_iv_atomic_short_max_exclusive_4 import NistschemaSvIvAtomicShortMaxExclusive4 __all__ = [ "NistschemaSvIvAtomicShortMaxExclusive4", ]
43.5
199
0.896552
30
261
7.1
0.633333
0.15493
0.131455
0.187793
0.356808
0.356808
0.356808
0.356808
0
0
0
0.016194
0.05364
261
5
200
52.2
0.846154
0
0
0
0
0
0.145594
0.145594
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d88c118502a2f95d15026c4565828a1c3fdcf124
705
py
Python
reservationsystem/views/stations.py
RajaFaizanNazir/bus-booking-system
df895793930535d7c1c50d84393d557be73780f3
[ "MIT" ]
1
2021-01-21T20:44:53.000Z
2021-01-21T20:44:53.000Z
reservationsystem/views/stations.py
RajaFaizanNazir/bus-booking-system
df895793930535d7c1c50d84393d557be73780f3
[ "MIT" ]
7
2020-05-02T09:45:54.000Z
2021-04-08T20:19:17.000Z
reservationsystem/views/stations.py
RajaFaizanNazir/bus-booking-system
df895793930535d7c1c50d84393d557be73780f3
[ "MIT" ]
1
2021-11-22T17:21:22.000Z
2021-11-22T17:21:22.000Z
from rest_framework import permissions, serializers from rest_framework.response import Response from rest_framework.views import APIView from reservationsystem.models import BusStation from reservationsystem.services.stations import get_all_stations class StationListApi(APIView): """ List all BusStations """ permission_classes = [permissions.AllowAny] class OutputSerializer(serializers.ModelSerializer): class Meta: model = BusStation fields = ['id', 'name'] def get(self, request, format=None): stations = get_all_stations() serializer = self.OutputSerializer(stations, many=True) return Response(serializer.data)
28.2
64
0.72766
72
705
7.013889
0.555556
0.047525
0.10099
0
0
0
0
0
0
0
0
0
0.2
705
24
65
29.375
0.89539
0.028369
0
0
0
0
0.008969
0
0
0
0
0
0
1
0.066667
false
0
0.333333
0
0.733333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d88fd27b14017c81fe95fd446d02e358a7e9865c
645
py
Python
core/propabilistic_assignment.py
cerm-cirmmp/picasso
d7be216f266ba43d28a2ed8ea199874c195a840d
[ "MIT" ]
null
null
null
core/propabilistic_assignment.py
cerm-cirmmp/picasso
d7be216f266ba43d28a2ed8ea199874c195a840d
[ "MIT" ]
null
null
null
core/propabilistic_assignment.py
cerm-cirmmp/picasso
d7be216f266ba43d28a2ed8ea199874c195a840d
[ "MIT" ]
null
null
null
""" For each single peak, set a probability distribution over all the possibile assignment. Given a function phi(p,p') = {1/dist(p, p')} / {\sum_s 1/dist(p, s)} definiamo le probabilità in base allo scarto con il valor medio anzichè assegnare il particolare picco tale per cui lo scarto con il valor medio sia minimo, ovvero che minimizzi la seguente funzione di costo: cost(p,p') = ||csp(i) - avg_csp(i)||, noi definiamo una distribuzione di probabilità P = {1/cost(p, p')} / {\sum_s 1/cost(p, s)} Poi realizziamo gli assegnamenti usando beam-search Quindi aggiorniamo tutte le distribuzioni Ripetiamo la cosa fino a convergenza. """
30.714286
92
0.736434
107
645
4.411215
0.672897
0.016949
0.025424
0.025424
0.118644
0
0
0
0
0
0
0.007435
0.165891
645
21
93
30.714286
0.869888
0.979845
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
d894647f6b7d42d939fc4f38468477e81261eb26
1,347
py
Python
python-codes/github-follow-sync/follow-sync.py
yjwx0017/test
80071d6b4b83e78282a7607e6311f5c71c87bb3c
[ "MIT" ]
null
null
null
python-codes/github-follow-sync/follow-sync.py
yjwx0017/test
80071d6b4b83e78282a7607e6311f5c71c87bb3c
[ "MIT" ]
1
2016-09-29T05:34:12.000Z
2016-09-30T16:26:07.000Z
python-codes/github-follow-sync/follow-sync.py
yjwx0017/test
80071d6b4b83e78282a7607e6311f5c71c87bb3c
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # GitHub # Follow我的, Follow之 # 未Follow我的,从Following中删除之 # 即同步互Follow关系 import getpass from github import Github from github import PaginatedList from github import NamedUser # 始终Follow ALWAYS_FOLLOW = [ 'torvalds', 'jiangdon2007', 'michaelliao', 'zcbenz', 'ruanyf', ] def sync(): username = raw_input('Username:') password = getpass.getpass() print 'Please wait...' g = Github(username, password) me = g.get_user() followers = me.get_followers() following = me.get_following() followers_names = [x.login for x in followers] following_names = [x.login for x in following] all_is_ok = True for user in following_names: is_my_follower = user in followers_names in_always_list = user in ALWAYS_FOLLOW if (not is_my_follower) and (not in_always_list): me.remove_from_following(g.get_user(user)) print 'User \'%s\' has been removed from following list!' % user all_is_ok = False for user in followers_names: if user not in following_names: me.add_to_following(g.get_user(user)) print 'New user \'%s\' has been followed!' % user all_is_ok = False if all_is_ok: print 'All is OK!' if __name__ == "__main__": sync()
22.830508
76
0.644395
177
1,347
4.666667
0.384181
0.030266
0.042373
0.033898
0.142857
0.104116
0
0
0
0
0
0.005015
0.259837
1,347
58
77
23.224138
0.82347
0.078693
0
0.052632
0
0
0.127332
0
0
0
0
0
0
0
null
null
0.078947
0.105263
null
null
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
d8994f5246bb8f2bf569beae9a291cf57dfe8d89
9,348
py
Python
src/Streamer.py
jaredmichaelsmith/PyMiner
22af188d6f11bbab2c999636d8c2fb49dff45ed7
[ "MIT" ]
null
null
null
src/Streamer.py
jaredmichaelsmith/PyMiner
22af188d6f11bbab2c999636d8c2fb49dff45ed7
[ "MIT" ]
null
null
null
src/Streamer.py
jaredmichaelsmith/PyMiner
22af188d6f11bbab2c999636d8c2fb49dff45ed7
[ "MIT" ]
null
null
null
''' Jared Smith PyMiner, Version 0.1 Streamer.py Authored under MIT License. ''' # Built-in Imports from __future__ import print_function import json import re import logging import threading import sys # 3rd-Party Imports import tweepy from tweepy.models import Status from tweepy.utils import import_simplejson, urlencode_noplus # Define global json to be from tweepy simplejson module json = import_simplejson() # Thread-safe print method for use iin printing tweets print_thread = lambda x: sys.stdout.write("%s\n" % x) # Stream class does handling of Twitter Stream API class Stream: # Initialize class def __init__(self, consumer_key, consumer_secret, key, secret): self.auth = tweepy.OAuthHandler(consumer_key, consumer_secret) self.auth.set_access_token(key, secret) self.tweetsBuffer = TweetsBuffer() self.logger = logging.getLogger('TwitterCollector') # If credentials invalid for tokens provides, exit on error if not tweepy.API(self.auth).verify_credentials(): print("Invalid credentials provided.\nExiting...") logging.error("Invalid credentials provided.\nExiting...") exit(0) # Run the stream in a thread and return the thread to Collector.py def run(self, filters, filter_type): # Initialize the listener and the buffer for the stream sl = StreamListener() sl.init(self.tweetsBuffer) # Insatiate the streamer streamer = tweepy.Stream(self.auth, sl) filter_list = filters.split(',') locations = [-124.848974, 24.396308, -66.885444, 49.384358, -140.9,55.1,-129.8,60.3, -169.6,53.3,-140.9,71.5, -172.0,10.6,-143.3,28.8] stream_thread = threading.Thread(target=streamer.filter, kwargs=dict(locations=locations)) stream_thread.start() '''# Check for filter type provided form config file and for filter parameters. # This will either be a list of lat-lon pairs for geofencing, or keywords if filter_type == 'location': locations = filter_list for location in locations: location = float(location) elif filter_type == 'keyword': keywords = filter_list stream_thread = threading.Thread(target=streamer.filter, kwargs=dict(track=keywords)) stream_thread.start() else: print("Invalid argument provided for config property filter_type.\nExiting...") logging.error("Invalid argument provided for config property filter_type.\nExiting...") exit(0)''' return stream_thread # Returns the tweepy tweet buffer def getTweetsBuffer(self): return self.tweetsBuffer # Listener class handles what to do when data comes through stream to our endpoint class StreamListener(tweepy.StreamListener): # Initialize the tweet buffer def init(self, tweetsBuffer): self.tweetsBuffer = tweetsBuffer # Parses status into python dictionary object for tweet and user def parse_status(self, status, retweet = False): tweet = { 'tweet_id':status.id, 'tweet_text':status.text, 'created_at':status.created_at, 'geo_lat':status.coordinates['coordinates'][0] if not status.coordinates is None else 0, 'geo_long': status.coordinates['coordinates'][1] if not status.coordinates is None else 0, 'user_id':status.user.id, 'tweet_url':"http://twitter.com/"+status.user.id_str+"/status/"+status.id_str, 'retweet_count':status.retweet_count, 'original_tweet_id':status.retweeted_status.id if not retweet and (status.retweet_count > 0) else 0, 'urls': status.entities['urls'], 'hashtags':status.entities['hashtags'], 'mentions': status.entities['user_mentions'] } user = { 'user_id':status.user.id, 'screen_name': status.user.screen_name, 'name': status.user.name, 'followers_count': status.user.followers_count, 'friends_count': status.user.friends_count, 'description': status.user.description if not status.user.description is None else "N/A", 'image_url': status.user.profile_image_url, 'location': status.user.location if not status.user.location is None else "N/A", 'created_at': status.user.created_at } return {'tweet':tweet, 'user':user} # When data is recieved from stream, this could be in the form of several things # Essentially, handle replys, deletes, and rate limiting responses from stream, # and everything else is unneccessary apart from statuses which will be handled # by on_status def on_data(self, data): if 'in_reply_to_status_id' in data: status = Status.parse(self.api, json.loads(data)) if self.on_status(status, data) is False: return False elif 'delete' in data: delete = json.loads(data)['delete']['status'] if self.on_delete(delete['id'], delete['user_id']) is False: return False elif 'limit' in data: if self.on_limit(json.loads(data)['limit']['track']) is False: return False # When status is recieved. print the status out, parse the tweets and retweets, and # insert data into the tweet buffer def on_status(self, status, rawJsonData): keyword_string = 'christmas,holidays,holiday,santa,santa claus,tacky sweater,snowflake,drummer boy,little drummer boy,nutcracker,clause,santa clause,holly jolly,ho ho ho,ho,shepard,Lord,manger,kwanzaa,hanukkah,Apple,apple,windows,Windows,PC,pc,android,Android,Google,google,church,christmas eve,family,toys,decorating,mistletoe,stockings,presents,cookies milk,chimney,north,pole,ornaments,jingle bells,sleigh,elf,rudolph,reindeer,dasher,dixin,prancer,stocking stuffer,holiday spirit,joy,merry,Merry Christmas,happy,white elephant,greetings,new year,happy new year,season,jolly,silent night,wish list,iOS,gmail,samsung,htc,nexus,andorid L, android lollipop, google tablet,macbook pro, macbook air, ipad, ipad mini, ipad air,imac, macbook,yosemite,mavericks,osx,os x,10.10,iOS 8, iwork,ilife,iphoto,macpro,wp8,wp7,windows 8, windows 8.1, windows 7, windows phone,gift,secret santa,letter,christmas tree,christmas lights,ornaments,angel,nativity scene,jesus,jesus birthday,jubilee,festival,yule,yuletide,tidings,scrooge,noel,Noel,Frosty,cards,candy canes,wreath,holly,pageant,savior,wisemen,Lord,Mary,Joseph,Bethlehem,artificial,cedar,icicles,tinsel,pine,lights,fir,star,ribbon,wrapping paper,dolls,elves,sled,sleigh bells,excited,anticipating,exhausted,vixan,donner,cupid,comet,blitzer,carol,Christmas Carol,carolers,Christmas Dinner' keyword_list = keyword_string.split(',') keyword_list = [element.lower() for element in keyword_list] patterns = [r'\b%s\b' % re.escape(s.strip()) for s in keyword_list] rgx = re.compile('|'.join(patterns)) try: if rgx.search(status.text.lower()): print_thread(status.text) tweet = self.parse_status(status) tweet['raw_json'] = rawJsonData self.tweetsBuffer.insert(tweet) if tweet['tweet']['retweet_count'] > 0: if rgx.search(status.retweeted_status.text.lower()): retweet = self.parse_status(status.retweeted_status, True) retweet['raw_json'] = None self.tweetsBuffer.insert(retweet) # On exception (i.e. Unicode errors in tweet), ignore error and move on # to avoid halting collection process except Exception, e: pass # TweetsBuffer class handles the inserting and popping of tweets off the buffer # for tweets. This is here to allow for a data structure from which to pop off # tweets and insert into database class TweetsBuffer(): tweetsBuffer = [] # Initialize the lock def __init__(self): self.lock = threading.Lock() # Acquire the lock, insert the tweet, and release the lock def insert(self, tweet): self.lock.acquire() self.tweetsBuffer.append(tweet) self.lock.release() # Acquire the lock, pop off the tweet, release the lock, and return tweet to collector def pop(self): self.lock.acquire() tweet = self.tweetsBuffer.pop() if len(self.tweetsBuffer) > 0 else None self.lock.release() return tweet
46.049261
1,340
0.619705
1,114
9,348
5.117594
0.369838
0.022803
0.007718
0.009472
0.070163
0.051921
0.051921
0.051921
0.040344
0
0
0.014872
0.287869
9,348
202
1,341
46.277228
0.84152
0.153402
0
0.136752
0
0.008547
0.256895
0.15027
0
0
0
0
0
0
null
null
0.008547
0.08547
null
null
0.034188
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
d8b2283db0ddbff68c69ac26c223a626f6c34ebd
2,818
py
Python
tests/testapp/migrations/0001_initial.py
codingjoe/django-pictures
57fb83d7a3a0b3f29fbe7bcfe639e3a036398a06
[ "BSD-2-Clause" ]
16
2022-03-26T19:27:30.000Z
2022-03-29T20:29:46.000Z
tests/testapp/migrations/0001_initial.py
codingjoe/django-pictures
57fb83d7a3a0b3f29fbe7bcfe639e3a036398a06
[ "BSD-2-Clause" ]
7
2022-03-27T13:30:32.000Z
2022-03-31T08:03:16.000Z
tests/testapp/migrations/0001_initial.py
codingjoe/django-pictures
57fb83d7a3a0b3f29fbe7bcfe639e3a036398a06
[ "BSD-2-Clause" ]
1
2022-03-29T16:15:12.000Z
2022-03-29T16:15:12.000Z
# Generated by Django 4.0.2 on 2022-03-27 14:17 from django.db import migrations, models import pictures.models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Profile", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=100)), ( "picture", pictures.models.PictureField( aspect_ratios=[None, "3/2", "16/9"], breakpoints={ "l": 1200, "m": 992, "s": 768, "xl": 1400, "xs": 576, }, container_width=1200, file_types=["WEBP"], grid_columns=12, pixel_densities=[1, 2], upload_to="testapp/profile/", ), ), ], ), migrations.CreateModel( name="SimpleModel", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("picture_width", models.PositiveIntegerField(null=True)), ("picture_height", models.PositiveIntegerField(null=True)), ( "picture", pictures.models.PictureField( aspect_ratios=[None, "3/2", "16/9"], blank=True, breakpoints={ "l": 1200, "m": 992, "s": 768, "xl": 1400, "xs": 576, }, container_width=1200, file_types=["WEBP"], grid_columns=12, height_field="picture_height", null=True, pixel_densities=[1, 2], upload_to="testapp/simplemodel/", width_field="picture_width", ), ), ], ), ]
32.390805
75
0.334989
175
2,818
5.251429
0.457143
0.045702
0.054407
0.056583
0.616975
0.535365
0.535365
0.4679
0.4679
0.4679
0
0.064677
0.572037
2,818
86
76
32.767442
0.697347
0.015969
0
0.692308
1
0
0.06135
0
0
0
0
0
0
1
0
false
0
0.025641
0
0.076923
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d8ba4a37eb25e82fd0aa5fe28371f7449c460cef
1,020
py
Python
game_servers_status/__init__.py
hamsteruser/gameservers_checking_tool
1c9dc05b203f08cdf6053f1f379641b57e1368e0
[ "MIT" ]
null
null
null
game_servers_status/__init__.py
hamsteruser/gameservers_checking_tool
1c9dc05b203f08cdf6053f1f379641b57e1368e0
[ "MIT" ]
null
null
null
game_servers_status/__init__.py
hamsteruser/gameservers_checking_tool
1c9dc05b203f08cdf6053f1f379641b57e1368e0
[ "MIT" ]
null
null
null
import importlib class PingTesterBase(): ''' Init module imports a file that is match the "game" argument ''' def __init__(self, game, host, port=None, timeout=10): if ":" in host: _host = host.split(':')[0] port = int(host.split(':')[1]) else: _host = host self.game = __import__(game, globals(), level=1).TargetGame(_host, port, timeout) def getServerPing(self, *args, **kwargs): return self.game.get_server_ping(*args, **kwargs) def isServerAlive(self, *args, **kwargs): return self.game.is_server_alive(*args, **kwargs) def Monitor(self, *args, **kwargs): ''' Creates two attributes: self.game.latency and self.game.is_alive and returns answer from server Can be used instead of getServerPing and isServerAlive ''' return self.game.server_monitoring(*args, **kwargs) def __del__(self): del(self.game)
34
107
0.579412
118
1,020
4.830508
0.483051
0.112281
0.073684
0.070175
0.098246
0.098246
0
0
0
0
0
0.006983
0.298039
1,020
30
108
34
0.789106
0.208824
0
0
0
0
0.003881
0
0
0
0
0
0
1
0.294118
false
0
0.117647
0.117647
0.647059
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
d8c1325b6e3da71eb09b6e90fc27a95ea97336d7
44,932
py
Python
ultracart/models/screen_recording.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
1
2018-03-15T16:56:23.000Z
2018-03-15T16:56:23.000Z
ultracart/models/screen_recording.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
null
null
null
ultracart/models/screen_recording.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ScreenRecording(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'ad_platform': 'ScreenRecordingAdPlatform', 'analytics_client_oid': 'int', 'analytics_session_dts': 'int', 'analytics_session_oid': 'int', 'communications_campaign_name': 'str', 'communications_campaign_uuid': 'str', 'communications_email_subject': 'str', 'communications_email_uuid': 'str', 'communications_flow_name': 'str', 'communications_flow_uuid': 'str', 'email': 'str', 'email_domain': 'str', 'end_timestamp': 'str', 'esp_customer_uuid': 'str', 'events_gz_size': 'int', 'events_json_key': 'str', 'favorite': 'bool', 'favorites': 'list[int]', 'geolocation': 'GeoPoint', 'geolocation_country': 'str', 'geolocation_state': 'str', 'language_iso_code': 'str', 'merchant_id': 'str', 'merchant_notes': 'str', 'missing_external_tracking': 'bool', 'order_id': 'str', 'page_view_count': 'int', 'page_views': 'list[ScreenRecordingPageView]', 'preferred_language': 'str', 'referrer_domain': 'str', 'rrweb_version': 'str', 'screen_recording_uuid': 'str', 'signed_download_url': 'str', 'start_timestamp': 'str', 'storefront_oids': 'list[int]', 'storefronts': 'list[ScreenRecordingStoreFront]', 'tags': 'list[str]', 'time_on_site': 'int', 'ucacid': 'str', 'user_agent': 'ScreenRecordingUserAgent', 'user_agent_raw': 'str', 'user_ip': 'str', 'user_properties': 'list[ScreenRecordingUserProperty]', 'utm_campaign': 'str', 'utm_source': 'str', 'visitor_first_seen': 'str', 'visitor_number': 'int', 'watched': 'bool', 'window_height': 'int', 'window_width': 'int' } attribute_map = { 'ad_platform': 'ad_platform', 'analytics_client_oid': 'analytics_client_oid', 'analytics_session_dts': 'analytics_session_dts', 'analytics_session_oid': 'analytics_session_oid', 'communications_campaign_name': 'communications_campaign_name', 'communications_campaign_uuid': 'communications_campaign_uuid', 'communications_email_subject': 'communications_email_subject', 'communications_email_uuid': 'communications_email_uuid', 'communications_flow_name': 'communications_flow_name', 'communications_flow_uuid': 'communications_flow_uuid', 'email': 'email', 'email_domain': 'email_domain', 'end_timestamp': 'end_timestamp', 'esp_customer_uuid': 'esp_customer_uuid', 'events_gz_size': 'events_gz_size', 'events_json_key': 'events_json_key', 'favorite': 'favorite', 'favorites': 'favorites', 'geolocation': 'geolocation', 'geolocation_country': 'geolocation_country', 'geolocation_state': 'geolocation_state', 'language_iso_code': 'language_iso_code', 'merchant_id': 'merchant_id', 'merchant_notes': 'merchant_notes', 'missing_external_tracking': 'missing_external_tracking', 'order_id': 'order_id', 'page_view_count': 'page_view_count', 'page_views': 'page_views', 'preferred_language': 'preferred_language', 'referrer_domain': 'referrer_domain', 'rrweb_version': 'rrweb_version', 'screen_recording_uuid': 'screen_recording_uuid', 'signed_download_url': 'signed_download_url', 'start_timestamp': 'start_timestamp', 'storefront_oids': 'storefront_oids', 'storefronts': 'storefronts', 'tags': 'tags', 'time_on_site': 'time_on_site', 'ucacid': 'ucacid', 'user_agent': 'user_agent', 'user_agent_raw': 'user_agent_raw', 'user_ip': 'user_ip', 'user_properties': 'user_properties', 'utm_campaign': 'utm_campaign', 'utm_source': 'utm_source', 'visitor_first_seen': 'visitor_first_seen', 'visitor_number': 'visitor_number', 'watched': 'watched', 'window_height': 'window_height', 'window_width': 'window_width' } def __init__(self, ad_platform=None, analytics_client_oid=None, analytics_session_dts=None, analytics_session_oid=None, communications_campaign_name=None, communications_campaign_uuid=None, communications_email_subject=None, communications_email_uuid=None, communications_flow_name=None, communications_flow_uuid=None, email=None, email_domain=None, end_timestamp=None, esp_customer_uuid=None, events_gz_size=None, events_json_key=None, favorite=None, favorites=None, geolocation=None, geolocation_country=None, geolocation_state=None, language_iso_code=None, merchant_id=None, merchant_notes=None, missing_external_tracking=None, order_id=None, page_view_count=None, page_views=None, preferred_language=None, referrer_domain=None, rrweb_version=None, screen_recording_uuid=None, signed_download_url=None, start_timestamp=None, storefront_oids=None, storefronts=None, tags=None, time_on_site=None, ucacid=None, user_agent=None, user_agent_raw=None, user_ip=None, user_properties=None, utm_campaign=None, utm_source=None, visitor_first_seen=None, visitor_number=None, watched=None, window_height=None, window_width=None): # noqa: E501 """ScreenRecording - a model defined in Swagger""" # noqa: E501 self._ad_platform = None self._analytics_client_oid = None self._analytics_session_dts = None self._analytics_session_oid = None self._communications_campaign_name = None self._communications_campaign_uuid = None self._communications_email_subject = None self._communications_email_uuid = None self._communications_flow_name = None self._communications_flow_uuid = None self._email = None self._email_domain = None self._end_timestamp = None self._esp_customer_uuid = None self._events_gz_size = None self._events_json_key = None self._favorite = None self._favorites = None self._geolocation = None self._geolocation_country = None self._geolocation_state = None self._language_iso_code = None self._merchant_id = None self._merchant_notes = None self._missing_external_tracking = None self._order_id = None self._page_view_count = None self._page_views = None self._preferred_language = None self._referrer_domain = None self._rrweb_version = None self._screen_recording_uuid = None self._signed_download_url = None self._start_timestamp = None self._storefront_oids = None self._storefronts = None self._tags = None self._time_on_site = None self._ucacid = None self._user_agent = None self._user_agent_raw = None self._user_ip = None self._user_properties = None self._utm_campaign = None self._utm_source = None self._visitor_first_seen = None self._visitor_number = None self._watched = None self._window_height = None self._window_width = None self.discriminator = None if ad_platform is not None: self.ad_platform = ad_platform if analytics_client_oid is not None: self.analytics_client_oid = analytics_client_oid if analytics_session_dts is not None: self.analytics_session_dts = analytics_session_dts if analytics_session_oid is not None: self.analytics_session_oid = analytics_session_oid if communications_campaign_name is not None: self.communications_campaign_name = communications_campaign_name if communications_campaign_uuid is not None: self.communications_campaign_uuid = communications_campaign_uuid if communications_email_subject is not None: self.communications_email_subject = communications_email_subject if communications_email_uuid is not None: self.communications_email_uuid = communications_email_uuid if communications_flow_name is not None: self.communications_flow_name = communications_flow_name if communications_flow_uuid is not None: self.communications_flow_uuid = communications_flow_uuid if email is not None: self.email = email if email_domain is not None: self.email_domain = email_domain if end_timestamp is not None: self.end_timestamp = end_timestamp if esp_customer_uuid is not None: self.esp_customer_uuid = esp_customer_uuid if events_gz_size is not None: self.events_gz_size = events_gz_size if events_json_key is not None: self.events_json_key = events_json_key if favorite is not None: self.favorite = favorite if favorites is not None: self.favorites = favorites if geolocation is not None: self.geolocation = geolocation if geolocation_country is not None: self.geolocation_country = geolocation_country if geolocation_state is not None: self.geolocation_state = geolocation_state if language_iso_code is not None: self.language_iso_code = language_iso_code if merchant_id is not None: self.merchant_id = merchant_id if merchant_notes is not None: self.merchant_notes = merchant_notes if missing_external_tracking is not None: self.missing_external_tracking = missing_external_tracking if order_id is not None: self.order_id = order_id if page_view_count is not None: self.page_view_count = page_view_count if page_views is not None: self.page_views = page_views if preferred_language is not None: self.preferred_language = preferred_language if referrer_domain is not None: self.referrer_domain = referrer_domain if rrweb_version is not None: self.rrweb_version = rrweb_version if screen_recording_uuid is not None: self.screen_recording_uuid = screen_recording_uuid if signed_download_url is not None: self.signed_download_url = signed_download_url if start_timestamp is not None: self.start_timestamp = start_timestamp if storefront_oids is not None: self.storefront_oids = storefront_oids if storefronts is not None: self.storefronts = storefronts if tags is not None: self.tags = tags if time_on_site is not None: self.time_on_site = time_on_site if ucacid is not None: self.ucacid = ucacid if user_agent is not None: self.user_agent = user_agent if user_agent_raw is not None: self.user_agent_raw = user_agent_raw if user_ip is not None: self.user_ip = user_ip if user_properties is not None: self.user_properties = user_properties if utm_campaign is not None: self.utm_campaign = utm_campaign if utm_source is not None: self.utm_source = utm_source if visitor_first_seen is not None: self.visitor_first_seen = visitor_first_seen if visitor_number is not None: self.visitor_number = visitor_number if watched is not None: self.watched = watched if window_height is not None: self.window_height = window_height if window_width is not None: self.window_width = window_width @property def ad_platform(self): """Gets the ad_platform of this ScreenRecording. # noqa: E501 :return: The ad_platform of this ScreenRecording. # noqa: E501 :rtype: ScreenRecordingAdPlatform """ return self._ad_platform @ad_platform.setter def ad_platform(self, ad_platform): """Sets the ad_platform of this ScreenRecording. :param ad_platform: The ad_platform of this ScreenRecording. # noqa: E501 :type: ScreenRecordingAdPlatform """ self._ad_platform = ad_platform @property def analytics_client_oid(self): """Gets the analytics_client_oid of this ScreenRecording. # noqa: E501 :return: The analytics_client_oid of this ScreenRecording. # noqa: E501 :rtype: int """ return self._analytics_client_oid @analytics_client_oid.setter def analytics_client_oid(self, analytics_client_oid): """Sets the analytics_client_oid of this ScreenRecording. :param analytics_client_oid: The analytics_client_oid of this ScreenRecording. # noqa: E501 :type: int """ self._analytics_client_oid = analytics_client_oid @property def analytics_session_dts(self): """Gets the analytics_session_dts of this ScreenRecording. # noqa: E501 :return: The analytics_session_dts of this ScreenRecording. # noqa: E501 :rtype: int """ return self._analytics_session_dts @analytics_session_dts.setter def analytics_session_dts(self, analytics_session_dts): """Sets the analytics_session_dts of this ScreenRecording. :param analytics_session_dts: The analytics_session_dts of this ScreenRecording. # noqa: E501 :type: int """ self._analytics_session_dts = analytics_session_dts @property def analytics_session_oid(self): """Gets the analytics_session_oid of this ScreenRecording. # noqa: E501 :return: The analytics_session_oid of this ScreenRecording. # noqa: E501 :rtype: int """ return self._analytics_session_oid @analytics_session_oid.setter def analytics_session_oid(self, analytics_session_oid): """Sets the analytics_session_oid of this ScreenRecording. :param analytics_session_oid: The analytics_session_oid of this ScreenRecording. # noqa: E501 :type: int """ self._analytics_session_oid = analytics_session_oid @property def communications_campaign_name(self): """Gets the communications_campaign_name of this ScreenRecording. # noqa: E501 Campaign Name # noqa: E501 :return: The communications_campaign_name of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_campaign_name @communications_campaign_name.setter def communications_campaign_name(self, communications_campaign_name): """Sets the communications_campaign_name of this ScreenRecording. Campaign Name # noqa: E501 :param communications_campaign_name: The communications_campaign_name of this ScreenRecording. # noqa: E501 :type: str """ self._communications_campaign_name = communications_campaign_name @property def communications_campaign_uuid(self): """Gets the communications_campaign_uuid of this ScreenRecording. # noqa: E501 Campaign UUID # noqa: E501 :return: The communications_campaign_uuid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_campaign_uuid @communications_campaign_uuid.setter def communications_campaign_uuid(self, communications_campaign_uuid): """Sets the communications_campaign_uuid of this ScreenRecording. Campaign UUID # noqa: E501 :param communications_campaign_uuid: The communications_campaign_uuid of this ScreenRecording. # noqa: E501 :type: str """ self._communications_campaign_uuid = communications_campaign_uuid @property def communications_email_subject(self): """Gets the communications_email_subject of this ScreenRecording. # noqa: E501 Email subject # noqa: E501 :return: The communications_email_subject of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_email_subject @communications_email_subject.setter def communications_email_subject(self, communications_email_subject): """Sets the communications_email_subject of this ScreenRecording. Email subject # noqa: E501 :param communications_email_subject: The communications_email_subject of this ScreenRecording. # noqa: E501 :type: str """ self._communications_email_subject = communications_email_subject @property def communications_email_uuid(self): """Gets the communications_email_uuid of this ScreenRecording. # noqa: E501 Email UUID # noqa: E501 :return: The communications_email_uuid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_email_uuid @communications_email_uuid.setter def communications_email_uuid(self, communications_email_uuid): """Sets the communications_email_uuid of this ScreenRecording. Email UUID # noqa: E501 :param communications_email_uuid: The communications_email_uuid of this ScreenRecording. # noqa: E501 :type: str """ self._communications_email_uuid = communications_email_uuid @property def communications_flow_name(self): """Gets the communications_flow_name of this ScreenRecording. # noqa: E501 Flow Name # noqa: E501 :return: The communications_flow_name of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_flow_name @communications_flow_name.setter def communications_flow_name(self, communications_flow_name): """Sets the communications_flow_name of this ScreenRecording. Flow Name # noqa: E501 :param communications_flow_name: The communications_flow_name of this ScreenRecording. # noqa: E501 :type: str """ self._communications_flow_name = communications_flow_name @property def communications_flow_uuid(self): """Gets the communications_flow_uuid of this ScreenRecording. # noqa: E501 Flow UUID # noqa: E501 :return: The communications_flow_uuid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._communications_flow_uuid @communications_flow_uuid.setter def communications_flow_uuid(self, communications_flow_uuid): """Sets the communications_flow_uuid of this ScreenRecording. Flow UUID # noqa: E501 :param communications_flow_uuid: The communications_flow_uuid of this ScreenRecording. # noqa: E501 :type: str """ self._communications_flow_uuid = communications_flow_uuid @property def email(self): """Gets the email of this ScreenRecording. # noqa: E501 :return: The email of this ScreenRecording. # noqa: E501 :rtype: str """ return self._email @email.setter def email(self, email): """Sets the email of this ScreenRecording. :param email: The email of this ScreenRecording. # noqa: E501 :type: str """ self._email = email @property def email_domain(self): """Gets the email_domain of this ScreenRecording. # noqa: E501 :return: The email_domain of this ScreenRecording. # noqa: E501 :rtype: str """ return self._email_domain @email_domain.setter def email_domain(self, email_domain): """Sets the email_domain of this ScreenRecording. :param email_domain: The email_domain of this ScreenRecording. # noqa: E501 :type: str """ self._email_domain = email_domain @property def end_timestamp(self): """Gets the end_timestamp of this ScreenRecording. # noqa: E501 Ending timestamp # noqa: E501 :return: The end_timestamp of this ScreenRecording. # noqa: E501 :rtype: str """ return self._end_timestamp @end_timestamp.setter def end_timestamp(self, end_timestamp): """Sets the end_timestamp of this ScreenRecording. Ending timestamp # noqa: E501 :param end_timestamp: The end_timestamp of this ScreenRecording. # noqa: E501 :type: str """ self._end_timestamp = end_timestamp @property def esp_customer_uuid(self): """Gets the esp_customer_uuid of this ScreenRecording. # noqa: E501 :return: The esp_customer_uuid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._esp_customer_uuid @esp_customer_uuid.setter def esp_customer_uuid(self, esp_customer_uuid): """Sets the esp_customer_uuid of this ScreenRecording. :param esp_customer_uuid: The esp_customer_uuid of this ScreenRecording. # noqa: E501 :type: str """ self._esp_customer_uuid = esp_customer_uuid @property def events_gz_size(self): """Gets the events_gz_size of this ScreenRecording. # noqa: E501 :return: The events_gz_size of this ScreenRecording. # noqa: E501 :rtype: int """ return self._events_gz_size @events_gz_size.setter def events_gz_size(self, events_gz_size): """Sets the events_gz_size of this ScreenRecording. :param events_gz_size: The events_gz_size of this ScreenRecording. # noqa: E501 :type: int """ self._events_gz_size = events_gz_size @property def events_json_key(self): """Gets the events_json_key of this ScreenRecording. # noqa: E501 :return: The events_json_key of this ScreenRecording. # noqa: E501 :rtype: str """ return self._events_json_key @events_json_key.setter def events_json_key(self, events_json_key): """Sets the events_json_key of this ScreenRecording. :param events_json_key: The events_json_key of this ScreenRecording. # noqa: E501 :type: str """ self._events_json_key = events_json_key @property def favorite(self): """Gets the favorite of this ScreenRecording. # noqa: E501 True if the user calling the API has favorited this particular screen recording. # noqa: E501 :return: The favorite of this ScreenRecording. # noqa: E501 :rtype: bool """ return self._favorite @favorite.setter def favorite(self, favorite): """Sets the favorite of this ScreenRecording. True if the user calling the API has favorited this particular screen recording. # noqa: E501 :param favorite: The favorite of this ScreenRecording. # noqa: E501 :type: bool """ self._favorite = favorite @property def favorites(self): """Gets the favorites of this ScreenRecording. # noqa: E501 Array of user ids that favorited this particular screen recording. # noqa: E501 :return: The favorites of this ScreenRecording. # noqa: E501 :rtype: list[int] """ return self._favorites @favorites.setter def favorites(self, favorites): """Sets the favorites of this ScreenRecording. Array of user ids that favorited this particular screen recording. # noqa: E501 :param favorites: The favorites of this ScreenRecording. # noqa: E501 :type: list[int] """ self._favorites = favorites @property def geolocation(self): """Gets the geolocation of this ScreenRecording. # noqa: E501 :return: The geolocation of this ScreenRecording. # noqa: E501 :rtype: GeoPoint """ return self._geolocation @geolocation.setter def geolocation(self, geolocation): """Sets the geolocation of this ScreenRecording. :param geolocation: The geolocation of this ScreenRecording. # noqa: E501 :type: GeoPoint """ self._geolocation = geolocation @property def geolocation_country(self): """Gets the geolocation_country of this ScreenRecording. # noqa: E501 :return: The geolocation_country of this ScreenRecording. # noqa: E501 :rtype: str """ return self._geolocation_country @geolocation_country.setter def geolocation_country(self, geolocation_country): """Sets the geolocation_country of this ScreenRecording. :param geolocation_country: The geolocation_country of this ScreenRecording. # noqa: E501 :type: str """ self._geolocation_country = geolocation_country @property def geolocation_state(self): """Gets the geolocation_state of this ScreenRecording. # noqa: E501 :return: The geolocation_state of this ScreenRecording. # noqa: E501 :rtype: str """ return self._geolocation_state @geolocation_state.setter def geolocation_state(self, geolocation_state): """Sets the geolocation_state of this ScreenRecording. :param geolocation_state: The geolocation_state of this ScreenRecording. # noqa: E501 :type: str """ self._geolocation_state = geolocation_state @property def language_iso_code(self): """Gets the language_iso_code of this ScreenRecording. # noqa: E501 Language ISO code # noqa: E501 :return: The language_iso_code of this ScreenRecording. # noqa: E501 :rtype: str """ return self._language_iso_code @language_iso_code.setter def language_iso_code(self, language_iso_code): """Sets the language_iso_code of this ScreenRecording. Language ISO code # noqa: E501 :param language_iso_code: The language_iso_code of this ScreenRecording. # noqa: E501 :type: str """ self._language_iso_code = language_iso_code @property def merchant_id(self): """Gets the merchant_id of this ScreenRecording. # noqa: E501 :return: The merchant_id of this ScreenRecording. # noqa: E501 :rtype: str """ return self._merchant_id @merchant_id.setter def merchant_id(self, merchant_id): """Sets the merchant_id of this ScreenRecording. :param merchant_id: The merchant_id of this ScreenRecording. # noqa: E501 :type: str """ self._merchant_id = merchant_id @property def merchant_notes(self): """Gets the merchant_notes of this ScreenRecording. # noqa: E501 :return: The merchant_notes of this ScreenRecording. # noqa: E501 :rtype: str """ return self._merchant_notes @merchant_notes.setter def merchant_notes(self, merchant_notes): """Sets the merchant_notes of this ScreenRecording. :param merchant_notes: The merchant_notes of this ScreenRecording. # noqa: E501 :type: str """ self._merchant_notes = merchant_notes @property def missing_external_tracking(self): """Gets the missing_external_tracking of this ScreenRecording. # noqa: E501 True if external page view was not tracked # noqa: E501 :return: The missing_external_tracking of this ScreenRecording. # noqa: E501 :rtype: bool """ return self._missing_external_tracking @missing_external_tracking.setter def missing_external_tracking(self, missing_external_tracking): """Sets the missing_external_tracking of this ScreenRecording. True if external page view was not tracked # noqa: E501 :param missing_external_tracking: The missing_external_tracking of this ScreenRecording. # noqa: E501 :type: bool """ self._missing_external_tracking = missing_external_tracking @property def order_id(self): """Gets the order_id of this ScreenRecording. # noqa: E501 :return: The order_id of this ScreenRecording. # noqa: E501 :rtype: str """ return self._order_id @order_id.setter def order_id(self, order_id): """Sets the order_id of this ScreenRecording. :param order_id: The order_id of this ScreenRecording. # noqa: E501 :type: str """ self._order_id = order_id @property def page_view_count(self): """Gets the page_view_count of this ScreenRecording. # noqa: E501 :return: The page_view_count of this ScreenRecording. # noqa: E501 :rtype: int """ return self._page_view_count @page_view_count.setter def page_view_count(self, page_view_count): """Sets the page_view_count of this ScreenRecording. :param page_view_count: The page_view_count of this ScreenRecording. # noqa: E501 :type: int """ self._page_view_count = page_view_count @property def page_views(self): """Gets the page_views of this ScreenRecording. # noqa: E501 :return: The page_views of this ScreenRecording. # noqa: E501 :rtype: list[ScreenRecordingPageView] """ return self._page_views @page_views.setter def page_views(self, page_views): """Sets the page_views of this ScreenRecording. :param page_views: The page_views of this ScreenRecording. # noqa: E501 :type: list[ScreenRecordingPageView] """ self._page_views = page_views @property def preferred_language(self): """Gets the preferred_language of this ScreenRecording. # noqa: E501 ISO 3 Letter language code that the customer would prefer # noqa: E501 :return: The preferred_language of this ScreenRecording. # noqa: E501 :rtype: str """ return self._preferred_language @preferred_language.setter def preferred_language(self, preferred_language): """Sets the preferred_language of this ScreenRecording. ISO 3 Letter language code that the customer would prefer # noqa: E501 :param preferred_language: The preferred_language of this ScreenRecording. # noqa: E501 :type: str """ self._preferred_language = preferred_language @property def referrer_domain(self): """Gets the referrer_domain of this ScreenRecording. # noqa: E501 :return: The referrer_domain of this ScreenRecording. # noqa: E501 :rtype: str """ return self._referrer_domain @referrer_domain.setter def referrer_domain(self, referrer_domain): """Sets the referrer_domain of this ScreenRecording. :param referrer_domain: The referrer_domain of this ScreenRecording. # noqa: E501 :type: str """ self._referrer_domain = referrer_domain @property def rrweb_version(self): """Gets the rrweb_version of this ScreenRecording. # noqa: E501 :return: The rrweb_version of this ScreenRecording. # noqa: E501 :rtype: str """ return self._rrweb_version @rrweb_version.setter def rrweb_version(self, rrweb_version): """Sets the rrweb_version of this ScreenRecording. :param rrweb_version: The rrweb_version of this ScreenRecording. # noqa: E501 :type: str """ self._rrweb_version = rrweb_version @property def screen_recording_uuid(self): """Gets the screen_recording_uuid of this ScreenRecording. # noqa: E501 :return: The screen_recording_uuid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._screen_recording_uuid @screen_recording_uuid.setter def screen_recording_uuid(self, screen_recording_uuid): """Sets the screen_recording_uuid of this ScreenRecording. :param screen_recording_uuid: The screen_recording_uuid of this ScreenRecording. # noqa: E501 :type: str """ self._screen_recording_uuid = screen_recording_uuid @property def signed_download_url(self): """Gets the signed_download_url of this ScreenRecording. # noqa: E501 :return: The signed_download_url of this ScreenRecording. # noqa: E501 :rtype: str """ return self._signed_download_url @signed_download_url.setter def signed_download_url(self, signed_download_url): """Sets the signed_download_url of this ScreenRecording. :param signed_download_url: The signed_download_url of this ScreenRecording. # noqa: E501 :type: str """ self._signed_download_url = signed_download_url @property def start_timestamp(self): """Gets the start_timestamp of this ScreenRecording. # noqa: E501 Starting timestamp # noqa: E501 :return: The start_timestamp of this ScreenRecording. # noqa: E501 :rtype: str """ return self._start_timestamp @start_timestamp.setter def start_timestamp(self, start_timestamp): """Sets the start_timestamp of this ScreenRecording. Starting timestamp # noqa: E501 :param start_timestamp: The start_timestamp of this ScreenRecording. # noqa: E501 :type: str """ self._start_timestamp = start_timestamp @property def storefront_oids(self): """Gets the storefront_oids of this ScreenRecording. # noqa: E501 :return: The storefront_oids of this ScreenRecording. # noqa: E501 :rtype: list[int] """ return self._storefront_oids @storefront_oids.setter def storefront_oids(self, storefront_oids): """Sets the storefront_oids of this ScreenRecording. :param storefront_oids: The storefront_oids of this ScreenRecording. # noqa: E501 :type: list[int] """ self._storefront_oids = storefront_oids @property def storefronts(self): """Gets the storefronts of this ScreenRecording. # noqa: E501 :return: The storefronts of this ScreenRecording. # noqa: E501 :rtype: list[ScreenRecordingStoreFront] """ return self._storefronts @storefronts.setter def storefronts(self, storefronts): """Sets the storefronts of this ScreenRecording. :param storefronts: The storefronts of this ScreenRecording. # noqa: E501 :type: list[ScreenRecordingStoreFront] """ self._storefronts = storefronts @property def tags(self): """Gets the tags of this ScreenRecording. # noqa: E501 :return: The tags of this ScreenRecording. # noqa: E501 :rtype: list[str] """ return self._tags @tags.setter def tags(self, tags): """Sets the tags of this ScreenRecording. :param tags: The tags of this ScreenRecording. # noqa: E501 :type: list[str] """ self._tags = tags @property def time_on_site(self): """Gets the time_on_site of this ScreenRecording. # noqa: E501 :return: The time_on_site of this ScreenRecording. # noqa: E501 :rtype: int """ return self._time_on_site @time_on_site.setter def time_on_site(self, time_on_site): """Sets the time_on_site of this ScreenRecording. :param time_on_site: The time_on_site of this ScreenRecording. # noqa: E501 :type: int """ self._time_on_site = time_on_site @property def ucacid(self): """Gets the ucacid of this ScreenRecording. # noqa: E501 :return: The ucacid of this ScreenRecording. # noqa: E501 :rtype: str """ return self._ucacid @ucacid.setter def ucacid(self, ucacid): """Sets the ucacid of this ScreenRecording. :param ucacid: The ucacid of this ScreenRecording. # noqa: E501 :type: str """ self._ucacid = ucacid @property def user_agent(self): """Gets the user_agent of this ScreenRecording. # noqa: E501 :return: The user_agent of this ScreenRecording. # noqa: E501 :rtype: ScreenRecordingUserAgent """ return self._user_agent @user_agent.setter def user_agent(self, user_agent): """Sets the user_agent of this ScreenRecording. :param user_agent: The user_agent of this ScreenRecording. # noqa: E501 :type: ScreenRecordingUserAgent """ self._user_agent = user_agent @property def user_agent_raw(self): """Gets the user_agent_raw of this ScreenRecording. # noqa: E501 :return: The user_agent_raw of this ScreenRecording. # noqa: E501 :rtype: str """ return self._user_agent_raw @user_agent_raw.setter def user_agent_raw(self, user_agent_raw): """Sets the user_agent_raw of this ScreenRecording. :param user_agent_raw: The user_agent_raw of this ScreenRecording. # noqa: E501 :type: str """ self._user_agent_raw = user_agent_raw @property def user_ip(self): """Gets the user_ip of this ScreenRecording. # noqa: E501 :return: The user_ip of this ScreenRecording. # noqa: E501 :rtype: str """ return self._user_ip @user_ip.setter def user_ip(self, user_ip): """Sets the user_ip of this ScreenRecording. :param user_ip: The user_ip of this ScreenRecording. # noqa: E501 :type: str """ self._user_ip = user_ip @property def user_properties(self): """Gets the user_properties of this ScreenRecording. # noqa: E501 :return: The user_properties of this ScreenRecording. # noqa: E501 :rtype: list[ScreenRecordingUserProperty] """ return self._user_properties @user_properties.setter def user_properties(self, user_properties): """Sets the user_properties of this ScreenRecording. :param user_properties: The user_properties of this ScreenRecording. # noqa: E501 :type: list[ScreenRecordingUserProperty] """ self._user_properties = user_properties @property def utm_campaign(self): """Gets the utm_campaign of this ScreenRecording. # noqa: E501 UTM Campaign # noqa: E501 :return: The utm_campaign of this ScreenRecording. # noqa: E501 :rtype: str """ return self._utm_campaign @utm_campaign.setter def utm_campaign(self, utm_campaign): """Sets the utm_campaign of this ScreenRecording. UTM Campaign # noqa: E501 :param utm_campaign: The utm_campaign of this ScreenRecording. # noqa: E501 :type: str """ self._utm_campaign = utm_campaign @property def utm_source(self): """Gets the utm_source of this ScreenRecording. # noqa: E501 UTM Source # noqa: E501 :return: The utm_source of this ScreenRecording. # noqa: E501 :rtype: str """ return self._utm_source @utm_source.setter def utm_source(self, utm_source): """Sets the utm_source of this ScreenRecording. UTM Source # noqa: E501 :param utm_source: The utm_source of this ScreenRecording. # noqa: E501 :type: str """ self._utm_source = utm_source @property def visitor_first_seen(self): """Gets the visitor_first_seen of this ScreenRecording. # noqa: E501 Timestamp this visitor was first seen # noqa: E501 :return: The visitor_first_seen of this ScreenRecording. # noqa: E501 :rtype: str """ return self._visitor_first_seen @visitor_first_seen.setter def visitor_first_seen(self, visitor_first_seen): """Sets the visitor_first_seen of this ScreenRecording. Timestamp this visitor was first seen # noqa: E501 :param visitor_first_seen: The visitor_first_seen of this ScreenRecording. # noqa: E501 :type: str """ self._visitor_first_seen = visitor_first_seen @property def visitor_number(self): """Gets the visitor_number of this ScreenRecording. # noqa: E501 :return: The visitor_number of this ScreenRecording. # noqa: E501 :rtype: int """ return self._visitor_number @visitor_number.setter def visitor_number(self, visitor_number): """Sets the visitor_number of this ScreenRecording. :param visitor_number: The visitor_number of this ScreenRecording. # noqa: E501 :type: int """ self._visitor_number = visitor_number @property def watched(self): """Gets the watched of this ScreenRecording. # noqa: E501 :return: The watched of this ScreenRecording. # noqa: E501 :rtype: bool """ return self._watched @watched.setter def watched(self, watched): """Sets the watched of this ScreenRecording. :param watched: The watched of this ScreenRecording. # noqa: E501 :type: bool """ self._watched = watched @property def window_height(self): """Gets the window_height of this ScreenRecording. # noqa: E501 :return: The window_height of this ScreenRecording. # noqa: E501 :rtype: int """ return self._window_height @window_height.setter def window_height(self, window_height): """Sets the window_height of this ScreenRecording. :param window_height: The window_height of this ScreenRecording. # noqa: E501 :type: int """ self._window_height = window_height @property def window_width(self): """Gets the window_width of this ScreenRecording. # noqa: E501 :return: The window_width of this ScreenRecording. # noqa: E501 :rtype: int """ return self._window_width @window_width.setter def window_width(self, window_width): """Sets the window_width of this ScreenRecording. :param window_width: The window_width of this ScreenRecording. # noqa: E501 :type: int """ self._window_width = window_width def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ScreenRecording, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ScreenRecording): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
31.59775
1,138
0.650227
5,143
44,932
5.402683
0.039277
0.043187
0.151155
0.13496
0.668322
0.515044
0.446124
0.320197
0.232671
0.099655
0
0.017421
0.273102
44,932
1,421
1,139
31.619986
0.833318
0.374299
0
0.08769
1
0
0.105106
0.03577
0
0
0
0
0
1
0.178752
false
0
0.005059
0
0.283305
0.003373
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d8c1b6dc7746f50d73bb6b0da867becc6f435563
793
py
Python
algorithms/leetcode/medium/0075_颜色分类.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
1
2019-11-25T07:23:42.000Z
2019-11-25T07:23:42.000Z
algorithms/leetcode/medium/0075_颜色分类.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
13
2020-01-07T16:09:47.000Z
2022-03-02T12:51:44.000Z
algorithms/leetcode/medium/0075_颜色分类.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。   示例 1: 输入:nums = [2,0,2,1,1,0] 输出:[0,0,1,1,2,2] 示例 2: 输入:nums = [2,0,1] 输出:[0,1,2] 示例 3: 输入:nums = [0] 输出:[0] 示例 4: 输入:nums = [1] 输出:[1]   提示: n == nums.length 1 <= n <= 300 nums[i] 为 0、1 或 2   进阶: 你可以不使用代码库中的排序函数来解决这道题吗? 你能想出一个仅使用常数空间的一趟扫描算法吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-colors 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import doctest from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ pass if __name__ == '__main__': doctest.testmod()
12.790323
65
0.627995
130
793
3.769231
0.607692
0.020408
0.028571
0.032653
0
0
0
0
0
0
0
0.059937
0.200504
793
61
66
13
0.712934
0.721311
0
0
0
0
0.042553
0
0
0
0
0
0
1
0.142857
false
0.142857
0.285714
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
d8d13d5b81321e856bb7820071fa5fbfd97dadfa
278
py
Python
scripts/validate_route.py
katharosada/busshaming
c8d7cd4baf9ff049cda49c92da4d5ca10f68e6a9
[ "MIT" ]
42
2018-01-20T01:12:25.000Z
2022-02-02T01:40:17.000Z
scripts/validate_route.py
katharosada/busshaming
c8d7cd4baf9ff049cda49c92da4d5ca10f68e6a9
[ "MIT" ]
2
2018-01-24T03:58:17.000Z
2018-06-10T01:05:57.000Z
scripts/validate_route.py
katharosada/busshaming
c8d7cd4baf9ff049cda49c92da4d5ca10f68e6a9
[ "MIT" ]
7
2018-01-24T05:49:13.000Z
2018-12-03T08:47:43.000Z
import sys import django django.setup() from busshaming.data_processing import realtime_validator if __name__ == '__main__': if len(sys.argv) != 2: print(f'Usage: {sys.argv[0]} <route_id>') sys.exit(1) realtime_validator.validate_route(sys.argv[1])
18.533333
57
0.68705
39
278
4.564103
0.641026
0.117978
0
0
0
0
0
0
0
0
0
0.017621
0.183453
278
14
58
19.857143
0.76652
0
0
0
0
0
0.140794
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
2
d8d2d5d416e44985fcf456b29776b2640ac83b4a
25,239
py
Python
day5.py
Lajnold/adventofcode2015
cd99969c5701d1afd5ec58afc76d7c03681d0648
[ "MIT" ]
null
null
null
day5.py
Lajnold/adventofcode2015
cd99969c5701d1afd5ec58afc76d7c03681d0648
[ "MIT" ]
null
null
null
day5.py
Lajnold/adventofcode2015
cd99969c5701d1afd5ec58afc76d7c03681d0648
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 strings = [ "sszojmmrrkwuftyv", "isaljhemltsdzlum", "fujcyucsrxgatisb", "qiqqlmcgnhzparyg", "oijbmduquhfactbc", "jqzuvtggpdqcekgk", "zwqadogmpjmmxijf", "uilzxjythsqhwndh", "gtssqejjknzkkpvw", "wrggegukhhatygfi", "vhtcgqzerxonhsye", "tedlwzdjfppbmtdx", "iuvrelxiapllaxbg", "feybgiimfthtplui", "qxmmcnirvkzfrjwd", "vfarmltinsriqxpu", "oanqfyqirkraesfq", "xilodxfuxphuiiii", "yukhnchvjkfwcbiq", "bdaibcbzeuxqplop", "ivegnnpbiyxqsion", "ybahkbzpditgwdgt", "dmebdomwabxgtctu", "ibtvimgfaeonknoh", "jsqraroxudetmfyw", "dqdbcwtpintfcvuz", "tiyphjunlxddenpj", "fgqwjgntxagidhah", "nwenhxmakxqkeehg", "zdoheaxqpcnlhnen", "tfetfqojqcdzlpbm", "qpnxkuldeiituggg", "xwttlbdwxohahwar", "hjkwzadmtrkegzye", "koksqrqcfwcaxeof", "wulwmrptktliyxeq", "gyufbedqhhyqgqzj", "txpunzodohikzlmj", "jloqfuejfkemcrvu", "amnflshcheuddqtc", "pdvcsduggcogbiia", "yrioavgfmeafjpcz", "uyhbtmbutozzqfvq", "mwhgfwsgyuwcdzik", "auqylgxhmullxpaa", "lgelzivplaeoivzh", "uyvcepielfcmswoa", "qhirixgwkkccuzlp", "zoonniyosmkeejfg", "iayfetpixkedyana", "ictqeyzyqswdskiy", "ejsgqteafvmorwxe", "lhaiqrlqqwfbrqdx", "ydjyboqwhfpqfydc", "dwhttezyanrnbybv", "edgzkqeqkyojowvr", "rmjfdwsqamjqehdq", "ozminkgnkwqctrxz", "bztjhxpjthchhfcd", "vrtioawyxkivrpiq", "dpbcsznkpkaaclyy", "vpoypksymdwttpvz", "hhdlruwclartkyap", "bqkrcbrksbzcggbo", "jerbbbnxlwfvlaiw", "dwkasufidwjrjfbf", "kkfxtjhbnmqbmfwf", "vmnfziwqxmioukmj", "rqxvcultipkecdtu", "fhmfdibhtjzkiqsd", "hdpjbuzzbyafqrpd", "emszboysjuvwwvts", "msyigmwcuybfiooq", "druyksfnbluvnwoh", "fvgstvynnfbvxhsx", "bmzalvducnqtuune", "lzwkzfzttsvpllei", "olmplpvjamynfyfd", "padcwfkhystsvyfb", "wjhbvxkwtbfqdilb", "hruaqjwphonnterf", "bufjobjtvxtzjpmj", "oiedrjvmlbtwyyuy", "sgiemafwfztwsyju", "nsoqqfudrtwszyqf", "vonbxquiiwxnazyl", "yvnmjxtptujwqudn", "rrnybqhvrcgwvrkq", "taktoxzgotzxntfu", "quffzywzpxyaepxa", "rfvjebfiddcfgmwv", "iaeozntougqwnzoh", "scdqyrhoqmljhoil", "bfmqticltmfhxwld", "brbuktbyqlyfpsdl", "oidnyhjkeqenjlhd", "kujsaiqojopvrygg", "vebzobmdbzvjnjtk", "uunoygzqjopwgmbg", "piljqxgicjzgifso", "ikgptwcjzywswqnw", "pujqsixoisvhdvwi", "trtuxbgigogfsbbk", "mplstsqclhhdyaqk", "gzcwflvmstogdpvo", "tfjywbkmimyyqcjd", "gijutvhruqcsiznq", "ibxkhjvzzxgavkha", "btnxeqvznkxjsgmq", "tjgofgauxaelmjoq", "sokshvyhlkxerjrv", "ltogbivktqmtezta", "uduwytzvqvfluyuf", "msuckpthtgzhdxan", "fqmcglidvhvpirzr", "gwztkqpcwnutvfga", "bsjfgsrntdhlpqbx", "xloczbqybxmiopwt", "orvevzyjliomkkgu", "mzjbhmfjjvaziget", "tlsdxuhwdmghdyjb", "atoecyjhwmznaewi", "pyxpyvvipbqibiox", "ajbfmpqqobfsmesj", "siknbzefjblnohgd", "eqfhgewbblwdfkmc", "opylbscrotckkrbk", "lbwxbofgjkzdxkle", "ceixfjstaptdomvm", "hnkrqxifjmmjktie", "aqykzeuzvvetoygd", "fouahjimfcisxima", "prkzhutbqsyrhjzx", "qqwliakathnsbzne", "sayhgqtlcqqidqhj", "ygduolbysehdudra", "zricvxhdzznuxuce", "ucvzakslykpgsixd", "udirhgcttmyspgsb", "yuwzppjzfsjhhdzi", "gtqergjiuwookwre", "xvxexbjyjkxovvwf", "mlpaqhnnkqxrmwmm", "ezuqbrjozwuqafhb", "mcarusdthcbsonoq", "weeguqeheeiigrue", "pngtfugozxofaqxv", "copphvbjcmfspenv", "jiyahihykjjkdaya", "gdqnmesvptuyrfwp", "vbdscfywqmfxbohh", "crtrfuxyjypzubrg", "seihvevtxywxhflp", "fvvpmgttnapklwou", "qmqaqsajmqwhetpk", "zetxvrgjmblxvakr", "kpvwblrizaabmnhz", "mwpvvzaaicntrkcp", "clqyjiegtdsswqfm", "ymrcnqgcpldgfwtm", "nzyqpdenetncgnwq", "cmkzevgacnmdkqro", "kzfdsnamjqbeirhi", "kpxrvgvvxapqlued", "rzskbnfobevzrtqu", "vjoahbfwtydugzap", "ykbbldkoijlvicbl", "mfdmroiztsgjlasb", "quoigfyxwtwprmdr", "ekxjqafwudgwfqjm", "obtvyjkiycxfcdpb", "lhoihfnbuqelthof", "eydwzitgxryktddt", "rxsihfybacnpoyny", "bsncccxlplqgygtw", "rvmlaudsifnzhcqh", "huxwsyjyebckcsnn", "gtuqzyihwhqvjtes", "zreeyomtngvztveq", "nwddzjingsarhkxb", "nuqxqtctpoldrlsh", "wkvnrwqgjooovhpf", "kwgueyiyffudtbyg", "tpkzapnjxefqnmew", "ludwccvkihagvxal", "lfdtzhfadvabghna", "njqmlsnrkcfhtvbb", "cajzbqleghhnlgap", "vmitdcozzvqvzatp", "eelzefwqwjiywbcz", "uyztcuptfqvymjpi", "aorhnrpkjqqtgnfo", "lfrxfdrduoeqmwwp", "vszpjvbctblplinh", "zexhadgpqfifcqrz", "ueirfnshekpemqua", "qfremlntihbwabtb", "nwznunammfexltjc", "zkyieokaaogjehwt", "vlrxgkpclzeslqkq", "xrqrwfsuacywczhs", "olghlnfjdiwgdbqc", "difnlxnedpqcsrdf", "dgpuhiisybjpidsj", "vlwmwrikmitmoxbt", "sazpcmcnviynoktm", "pratafauetiknhln", "ilgteekhzwlsfwcn", "ywvwhrwhkaubvkbl", "qlaxivzwxyhvrxcf", "hbtlwjdriizqvjfb", "nrmsononytuwslsa", "mpxqgdthpoipyhjc", "mcdiwmiqeidwcglk", "vfbaeavmjjemfrmo", "qzcbzmisnynzibrc", "shzmpgxhehhcejhb", "wirtjadsqzydtyxd", "qjlrnjfokkqvnpue", "dxawdvjntlbxtuqc", "wttfmnrievfestog", "eamjfvsjhvzzaobg", "pbvfcwzjgxahlrag", "omvmjkqqnobvnzkn", "lcwmeibxhhlxnkzv", "uiaeroqfbvlazegs", "twniyldyuonfyzqw", "wgjkmsbwgfotdabi", "hnomamxoxvrzvtew", "ycrcfavikkrxxfgw", "isieyodknagzhaxy", "mgzdqwikzullzyco", "mumezgtxjrrejtrs", "nwmwjcgrqiwgfqel", "wjgxmebfmyjnxyyp", "durpspyljdykvzxf", "zuslbrpooyetgafh", "kuzrhcjwbdouhyme", "wyxuvbciodscbvfm", "kbnpvuqwmxwfqtqe", "zddzercqogdpxmft", "sigrdchxtgavzzjh", "lznjolnorbuddgcs", "ycnqabxlcajagwbt", "bnaudeaexahdgxsj", "rlnykxvoctfwanms", "jngyetkoplrstfzt", "tdpxknwacksotdub", "yutqgssfoptvizgr", "lzmqnxeqjfnsxmsa", "iqpgfsfmukovsdgu", "qywreehbidowtjyz", "iozamtgusdctvnkw", "ielmujhtmynlwcfd", "hzxnhtbnmmejlkyf", "ftbslbzmiqkzebtd", "bcwdqgiiizmohack", "dqhfkzeddjzbdlxu", "mxopokqffisxosci", "vciatxhtuechbylk", "khtkhcvelidjdena", "blatarwzfqcapkdt", "elamngegnczctcck", "xeicefdbwrxhuxuf", "sawvdhjoeahlgcdr", "kmdcimzsfkdfpnir", "axjayzqlosrduajb", "mfhzreuzzumvoggr", "iqlbkbhrkptquldb", "xcvztvlshiefuhgb", "pkvwyqmyoazocrio", "ajsxkdnerbmhyxaj", "tudibgsbnpnizvsi", "cxuiydkgdccrqvkh", "cyztpjesdzmbcpot", "nnazphxpanegwitx", "uphymczbmjalmsct", "yyxiwnlrogyzwqmg", "gmqwnahjvvdyhnfa", "utolskxpuoheugyl", "mseszdhyzoyavepd", "ycqknvbuvcjfgmlc", "sknrxhxbfpvpeorn", "zqxqjetooqcodwml", "sesylkpvbndrdhsy", "fryuxvjnsvnjrxlw", "mfxusewqurscujnu", "mbitdjjtgzchvkfv", "ozwlyxtaalxofovd", "wdqcduaykxbunpie", "rlnhykxiraileysk", "wgoqfrygttlamobg", "kflxzgxvcblkpsbz", "tmkisflhativzhde", "owsdrfgkaamogjzd", "gaupjkvkzavhfnes", "wknkurddcknbdleg", "lltviwincmbtduap", "qwzvspgbcksyzzmb", "ydzzkumecryfjgnk", "jzvmwgjutxoysaam", "icrwpyhxllbardkr", "jdopyntshmvltrve", "afgkigxcuvmdbqou", "mfzzudntmvuyhjzt", "duxhgtwafcgrpihc", "tsnhrkvponudumeb", "sqtvnbeiigdzbjgv", "eczmkqwvnsrracuo", "mhehsgqwiczaiaxv", "kaudmfvifovrimpd", "lupikgivechdbwfr", "mwaaysrndiutuiqx", "aacuiiwgaannunmm", "tjqjbftaqitukwzp", "lrcqyskykbjpaekn", "lirrvofbcqpjzxmr", "jurorvzpplyelfml", "qonbllojmloykjqe", "sllkzqujfnbauuqp", "auexjwsvphvikali", "usuelbssqmbrkxyc", "wyuokkfjexikptvv", "wmfedauwjgbrgytl", "sfwvtlzzebxzmuvw", "rdhqxuechjsjcvaf", "kpavhqkukugocsxu", "ovnjtumxowbxduts", "zgerpjufauptxgat", "pevvnzjfwhjxdoxq", "pmmfwxajgfziszcs", "difmeqvaghuitjhs", "icpwjbzcmlcterwm", "ngqpvhajttxuegyh", "mosjlqswdngwqsmi", "frlvgpxrjolgodlu", "eazwgrpcxjgoszeg", "bbtsthgkjrpkiiyk", "tjonoglufuvsvabe", "xhkbcrofytmbzrtk", "kqftfzdmpbxjynps", "kmeqpocbnikdtfyv", "qjjymgqxhnjwxxhp", "dmgicrhgbngdtmjt", "zdxrhdhbdutlawnc", "afvoekuhdboxghvx", "hiipezngkqcnihty", "bbmqgheidenweeov", "suprgwxgxwfsgjnx", "adeagikyamgqphrj", "zzifqinoeqaorjxg", "adhgppljizpaxzld", "lvxyieypvvuqjiyc", "nljoakatwwwoovzn", "fcrkfxclcacshhmx", "ownnxqtdhqbgthch", "lmfylrcdmdkgpwnj", "hlwjfbvlswbzpbjr", "mkofhdtljdetcyvp", "synyxhifbetzarpo", "agnggugngadrcxoc", "uhttadmdmhidpyjw", "ohfwjfhunalbubpr", "pzkkkkwrlvxiuysn", "kmidbxmyzkjrwjhu", "egtitdydwjxmajnw", "civoeoiuwtwgbqqs", "dfptsguzfinqoslk", "tdfvkreormspprer", "zvnvbrmthatzztwi", "ffkyddccrrfikjde", "hrrmraevdnztiwff", "qaeygykcpbtjwjbr", "purwhitkmrtybslh", "qzziznlswjaussel", "dfcxkvdpqccdqqxj", "tuotforulrrytgyn", "gmtgfofgucjywkev", "wkyoxudvdkbgpwhd", "qbvktvfvipftztnn", "otckgmojziezmojb", "inxhvzbtgkjxflay", "qvxapbiatuudseno", "krpvqosbesnjntut", "oqeukkgjsfuqkjbb", "prcjnyymnqwqksiz", "vuortvjxgckresko", "orqlyobvkuwgathr", "qnpyxlnazyfuijox", "zwlblfkoklqmqzkw", "hmwurwtpwnrcsanl", "jzvxohuakopuzgpf", "sfcpnxrviphhvxmx", "qtwdeadudtqhbely", "dbmkmloasqphnlgj", "olylnjtkxgrubmtk", "nxsdbqjuvwrrdbpq", "wbabpirnpcsmpipw", "hjnkyiuxpqrlvims", "enzpntcjnxdpuqch", "vvvqhlstzcizyimn", "triozhqndbttglhv", "fukvgteitwaagpzx", "uhcvukfbmrvskpen", "tizcyupztftzxdmt", "vtkpnbpdzsaluczz", "wodfoyhoekidxttm", "otqocljrmwfqbxzu", "linfbsnfvixlwykn", "vxsluutrwskslnye", "zbshygtwugixjvsi", "zdcqwxvwytmzhvoo", "wrseozkkcyctrmei", "fblgtvogvkpqzxiy", "opueqnuyngegbtnf", "qxbovietpacqqxok", "zacrdrrkohfygddn", "gbnnvjqmkdupwzpq", "qgrgmsxeotozvcak", "hnppukzvzfmlokid", "dzbheurndscrrtcl", "wbgdkadtszebbrcw", "fdmzppzphhpzyuiz", "bukomunhrjrypohj", "ohodhelegxootqbj", "rsplgzarlrknqjyh", "punjjwpsxnhpzgvu", "djdfahypfjvpvibm", "mlgrqsmhaozatsvy", "xwktrgyuhqiquxgn", "wvfaoolwtkbrisvf", "plttjdmguxjwmeqr", "zlvvbwvlhauyjykw", "cigwkbyjhmepikej", "masmylenrusgtyxs", "hviqzufwyetyznze", "nzqfuhrooswxxhus", "pdbdetaqcrqzzwxf", "oehmvziiqwkzhzib", "icgpyrukiokmytoy", "ooixfvwtiafnwkce", "rvnmgqggpjopkihs", "wywualssrmaqigqk", "pdbvflnwfswsrirl", "jeaezptokkccpbuj", "mbdwjntysntsaaby", "ldlgcawkzcwuxzpz", "lwktbgrzswbsweht", "ecspepmzarzmgpjm", "qmfyvulkmkxjncai", "izftypvwngiukrns", "zgmnyjfeqffbooww", "nyrkhggnprhedows", "yykzzrjmlevgffah", "mavaemfxhlfejfki", "cmegmfjbkvpncqwf", "zxidlodrezztcrij", "fseasudpgvgnysjv", "fupcimjupywzpqzp", "iqhgokavirrcvyys", "wjmkcareucnmfhui", "nftflsqnkgjaexhq", "mgklahzlcbapntgw", "kfbmeavfxtppnrxn", "nuhyvhknlufdynvn", "nviogjxbluwrcoec", "tyozixxxaqiuvoys", "kgwlvmvgtsvxojpr", "moeektyhyonfdhrb", "kahvevmmfsmiiqex", "xcywnqzcdqtvhiwd", "fnievhiyltbvtvem", "jlmndqufirwgtdxd", "muypbfttoeelsnbs", "rypxzbnujitfwkou", "ubmmjbznskildeoj", "ofnmizdeicrmkjxp", "rekvectjbmdnfcib", "yohrojuvdexbctdh", "gwfnfdeibynzjmhz", "jfznhfcqdwlpjull", "scrinzycfhwkmmso", "mskutzossrwoqqsi", "rygoebkzgyzushhr", "jpjqiycflqkexemx", "arbufysjqmgaapnl", "dbjerflevtgweeoj", "snybnnjlmwjvhois", "fszuzplntraprmbj", "mkvaatolvuggikvg", "zpuzuqygoxesnuyc", "wnpxvmxvllxalulm", "eivuuafkvudeouwy", "rvzckdyixetfuehr", "qgmnicdoqhveahyx", "miawwngyymshjmpj", "pvckyoncpqeqkbmx", "llninfenrfjqxurv", "kzbjnlgsqjfuzqtp", "rveqcmxomvpjcwte", "bzotkawzbopkosnx", "ktqvpiribpypaymu", "wvlzkivbukhnvram", "uohntlcoguvjqqdo", "ajlsiksjrcnzepkt", "xsqatbldqcykwusd", "ihbivgzrwpmowkop", "vfayesfojmibkjpb", "uaqbnijtrhvqxjtb", "hhovshsfmvkvymba", "jerwmyxrfeyvxcgg", "hncafjwrlvdcupma", "qyvigggxfylbbrzt", "hiiixcyohmvnkpgk", "mmitpwopgxuftdfu", "iaxderqpceboixoa", "zodfmjhuzhnsqfcb", "sthtcbadrclrazsi", "bkkkkcwegvypbrio", "wmpcofuvzemunlhj", "gqwebiifvqoeynro", "juupusqdsvxcpsgv", "rbhdfhthxelolyse", "kjimpwnjfrqlqhhz", "rcuigrjzarzpjgfq", "htxcejfyzhydinks", "sxucpdxhvqjxxjwf", "omsznfcimbcwaxal", "gufmtdlhgrsvcosb", "bssshaqujtmluerz", "uukotwjkstgwijtr", "kbqkneobbrdogrxk", "ljqopjcjmelgrakz", "rwtfnvnzryujwkfb", "dedjjbrndqnilbeh", "nzinsxnpptzagwlb", "lwqanydfirhnhkxy", "hrjuzfumbvfccxno", "okismsadkbseumnp", "sfkmiaiwlktxqvwa", "hauwpjjwowbunbjj", "nowkofejwvutcnui", "bqzzppwoslaeixro", "urpfgufwbtzenkpj", "xgeszvuqwxeykhef", "yxoldvkyuikwqyeq", "onbbhxrnmohzskgg", "qcikuxakrqeugpoa", "lnudcqbtyzhlpers", "nxduvwfrgzaailgl", "xniuwvxufzxjjrwz", "ljwithcqmgvntjdj", "awkftfagrfzywkhs", "uedtpzxyubeveuek", "bhcqdwidbjkqqhzl", "iyneqjdmlhowwzxx", "kvshzltcrrururty", "zgfpiwajegwezupo", "tkrvyanujjwmyyri", "ercsefuihcmoaiep", "ienjrxpmetinvbos", "jnwfutjbgenlipzq", "bgohjmrptfuamzbz", "rtsyamajrhxbcncw", "tfjdssnmztvbnscs", "bgaychdlmchngqlp", "kfjljiobynhwfkjo", "owtdxzcpqleftbvn", "ltjtimxwstvzwzjj", "wbrvjjjajuombokf", "zblpbpuaqbkvsxye", "gwgdtbpnlhyqspdi", "abipqjihjqfofmkx", "nlqymnuvjpvvgova", "avngotmhodpoufzn", "qmdyivtzitnrjuae", "xfwjmqtqdljuerxi", "csuellnlcyqaaamq", "slqyrcurcyuoxquo", "dcjmxyzbzpohzprl", "uqfnmjwniyqgsowb", "rbmxpqoblyxdocqc", "ebjclrdbqjhladem", "ainnfhxnsgwqnmyo", "eyytjjwhvodtzquf", "iabjgmbbhilrcyyp", "pqfnehkivuelyccc", "xgjbyhfgmtseiimt", "jwxyqhdbjiqqqeyy", "gxsbrncqkmvaryln", "vhjisxjkinaejytk", "seexagcdmaedpcvh", "lvudfgrcpjxzdpvd", "fxtegyrqjzhmqean", "dnoiseraqcoossmc", "nwrhmwwbykvwmgep", "udmzskejvizmtlce", "hbzvqhvudfdlegaa", "cghmlfqejbxewskv", "bntcmjqfwomtbwsb", "qezhowyopjdyhzng", "todzsocdkgfxanbz", "zgjkssrjlwxuhwbk", "eibzljqsieriyrzr", "wamxvzqyycrxotjp", "epzvfkispwqynadu", "dwlpfhtrafrxlyie", "qhgzujhgdruowoug", "girstvkahaemmxvh", "baitcrqmxhazyhbl", "xyanqcchbhkajdmc", "gfvjmmcgfhvgnfdq", "tdfdbslwncbnkzyz", "jojuselkpmnnbcbb", "hatdslkgxtqpmavj", "dvelfeddvgjcyxkj", "gnsofhkfepgwltse", "mdngnobasfpewlno", "qssnbcyjgmkyuoga", "glvcmmjytmprqwvn", "gwrixumjbcdffsdl", "lozravlzvfqtsuiq", "sicaflbqdxbmdlch", "inwfjkyyqbwpmqlq", "cuvszfotxywuzhzi", "igfxyoaacoarlvay", "ucjfhgdmnjvgvuni", "rvvkzjsytqgiposh", "jduinhjjntrmqroz", "yparkxbgsfnueyll", "lyeqqeisxzfsqzuj", "woncskbibjnumydm", "lltucklragtjmxtl", "ubiyvmyhlesfxotj", "uecjseeicldqrqww", "xxlxkbcthufnjbnm", "lhqijovvhlffpxga", "fzdgqpzijitlogjz", "efzzjqvwphomxdpd", "jvgzvuyzobeazssc", "hejfycgxywfjgbfw", "yhjjmvkqfbnbliks", "sffvfyywtlntsdsz", "dwmxqudvxqdenrur", "asnukgppdemxrzaz", "nwqfnumblwvdpphx", "kqsmkkspqvxzuket", "cpnraovljzqiquaz", "qrzgrdlyyzbyykhg", "opoahcbiydyhsmqe", "hjknnfdauidjeydr", "hczdjjlygoezadow", "rtflowzqycimllfv", "sfsrgrerzlnychhq", "bpahuvlblcolpjmj", "albgnjkgmcrlaicl", "pijyqdhfxpaxzdex", "eeymiddvcwkpbpux", "rqwkqoabywgggnln", "vckbollyhgbgmgwh", "ylzlgvnuvpynybkm", "hpmbxtpfosbsjixt", "ocebeihnhvkhjfqz", "tvctyxoujdgwayze", "efvhwxtuhapqxjen", "rusksgefyidldmpo", "nkmtjvddfmhirmzz", "whvtsuadwofzmvrt", "iiwjqvsdxudhdzzk", "gucirgxaxgcassyo", "rmhfasfzexeykwmr", "hynlxcvsbgosjbis", "huregszrcaocueen", "pifezpoolrnbdqtv", "unatnixzvdbqeyox", "xtawlpduxgacchfe", "bdvdbflqfphndduf", "xtdsnjnmzccfptyt", "nkhsdkhqtzqbphhg", "aqcubmfkczlaxiyb", "moziflxpsfubucmv", "srdgnnjtfehiimqx", "pwfalehdfyykrohf", "sysxssmvewyfjrve", "brsemdzosgqvvlxe", "bimbjoshuvflkiat", "hkgjasmljkpkwwku", "sbnmwjvodygobpqc", "bbbqycejueruihhd", "corawswvlvneipyc", "gcyhknmwsczcxedh", "kppakbffdhntmcqp", "ynulzwkfaemkcefp", "pyroowjekeurlbii", "iwksighrswdcnmxf", "glokrdmugreygnsg", "xkmvvumnfzckryop", "aesviofpufygschi", "csloawlirnegsssq", "fkqdqqmlzuxbkzbc", "uzlhzcfenxdfjdzp", "poaaidrktteusvyf", "zrlyfzmjzfvivcfr", "qwjulskbniitgqtx", "gjeszjksbfsuejki", "vczdejdbfixbduaq", "knjdrjthitjxluth", "jweydeginrnicirl", "bottrfgccqhyycsl", "eiquffofoadmbuhk", "lbqfutmzoksscswf", "xfmdvnvfcnzjprba", "uvugkjbkhlaoxmyx", "wadlgtpczgvcaqqv", "inzrszbtossflsxk", "dbzbtashaartczrj", "qbjiqpccefcfkvod", "hluujmokjywotvzy", "thwlliksfztcmwzh", "arahybspdaqdexrq", "nuojrmsgyipdvwyx", "hnajdwjwmzattvst", "sulcgaxezkprjbgu", "rjowuugwdpkjtypw", "oeugzwuhnrgiaqga", "wvxnyymwftfoswij", "pqxklzkjpcqscvde", "tuymjzknntekglqj", "odteewktugcwlhln", "exsptotlfecmgehc", "eeswfcijtvzgrqel", "vjhrkiwmunuiwqau", "zhlixepkeijoemne", "pavfsmwesuvebzdd", "jzovbklnngfdmyws", "nbajyohtzfeoiixz", "ciozmhrsjzrwxvhz", "gwucrxieqbaqfjuv", "uayrxrltnohexawc", "flmrbhwsfbcquffm", "gjyabmngkitawlxc", "rwwtggvaygfbovhg", "xquiegaisynictjq", "oudzwuhexrwwdbyy", "lengxmguyrwhrebb", "uklxpglldbgqsjls", "dbmvlfeyguydfsxq", "zspdwdqcrmtmdtsc", "mqfnzwbfqlauvrgc", "amcrkzptgacywvhv", "ndxmskrwrqysrndf", "mwjyhsufeqhwisju", "srlrukoaenyevykt", "tnpjtpwawrxbikct", "geczalxmgxejulcv", "tvkcbqdhmuwcxqci", "tiovluvwezwwgaox", "zrjhtbgajkjqzmfo", "vcrywduwsklepirs", "lofequdigsszuioy", "wxsdzomkjqymlzat", "iabaczqtrfbmypuy", "ibdlmudbajikcncr", "rqcvkzsbwmavdwnv", "ypxoyjelhllhbeog", "fdnszbkezyjbttbg", "uxnhrldastpdjkdz", "xfrjbehtxnlyzcka", "omjyfhbibqwgcpbv", "eguucnoxaoprszmp", "xfpypldgcmcllyzz", "aypnmgqjxjqceelv", "mgzharymejlafvgf", "tzowgwsubbaigdok", "ilsehjqpcjwmylxc", "pfmouwntfhfnmrwk", "csgokybgdqwnduwp", "eaxwvxvvwbrovypz", "nmluqvobbbmdiwwb", "lnkminvfjjzqbmio", "mjiiqzycqdhfietz", "towlrzriicyraevq", "obiloewdvbrsfwjo", "lmeooaajlthsfltw", "ichygipzpykkesrw", "gfysloxmqdsfskvt", "saqzntehjldvwtsx", "pqddoemaufpfcaew", "mjrxvbvwcreaybwe", "ngfbrwfqnxqosoai", "nesyewxreiqvhald", "kqhqdlquywotcyfy", "liliptyoqujensfi", "nsahsaxvaepzneqq", "zaickulfjajhctye", "gxjzahtgbgbabtht", "koxbuopaqhlsyhrp", "jhzejdjidqqtjnwe", "dekrkdvprfqpcqki", "linwlombdqtdeyop", "dvckqqbnigdcmwmx", "yaxygbjpzkvnnebv", "rlzkdkgaagmcpxah", "cfzuyxivtknirqvt", "obivkajhsjnrxxhn", "lmjhayymgpseuynn", "bbjyewkwadaipyju", "lmzyhwomfypoftuu", "gtzhqlgltvatxack", "jfflcfaqqkrrltgq", "txoummmnzfrlrmcg", "ohemsbfuqqpucups", "imsfvowcbieotlok", "tcnsnccdszxfcyde", "qkcdtkwuaquajazz", "arcfnhmdjezdbqku", "srnocgyqrlcvlhkb", "mppbzvfmcdirbyfw", "xiuarktilpldwgwd", "ypufwmhrvzqmexpc", "itpdnsfkwgrdujmj", "cmpxnodtsswkyxkr", "wayyxtjklfrmvbfp", "mfaxphcnjczhbbwy", "sjxhgwdnqcofbdra", "pnxmujuylqccjvjm", "ivamtjbvairwjqwl", "deijtmzgpfxrclss", "bzkqcaqagsynlaer", "tycefobvxcvwaulz", "ctbhnywezxkdsswf", "urrxxebxrthtjvib", "fpfelcigwqwdjucv", "ngfcyyqpqulwcphb", "rltkzsiipkpzlgpw", "qfdsymzwhqqdkykc", "balrhhxipoqzmihj", "rnwalxgigswxomga", "ghqnxeogckshphgr", "lyyaentdizaumnla", "exriodwfzosbeoib", "speswfggibijfejk", "yxmxgfhvmshqszrq", "hcqhngvahzgawjga", "qmhlsrfpesmeksur", "eviafjejygakodla", "kvcfeiqhynqadbzv", "fusvyhowslfzqttg", "girqmvwmcvntrwau", "yuavizroykfkdekz", "jmcwohvmzvowrhxf", "kzimlcpavapynfue", "wjudcdtrewfabppq", "yqpteuxqgbmqfgxh", "xdgiszbuhdognniu", "jsguxfwhpftlcjoh", "whakkvspssgjzxre", "ggvnvjurlyhhijgm", "krvbhjybnpemeptr", "pqedgfojyjybfbzr", "jzhcrsgmnkwwtpdo", "yyscxoxwofslncmp", "gzjhnxytmyntzths", "iteigbnqbtpvqumi", "zjevfzusnjukqpfw", "xippcyhkfuounxqk", "mcnhrcfonfdgpkyh", "pinkcyuhjkexbmzj", "lotxrswlxbxlxufs", "fmqajrtoabpckbnu", "wfkwsgmcffdgaqxg", "qfrsiwnohoyfbidr", "czfqbsbmiuyusaqs", "ieknnjeecucghpoo", "cevdgqnugupvmsge", "gjkajcyjnxdrtuvr", "udzhrargnujxiclq", "zqqrhhmjwermjssg", "ggdivtmgoqajydzz", "wnpfsgtxowkjiivl", "afbhqawjbotxnqpd", "xjpkifkhfjeqifdn", "oyfggzsstfhvticp", "kercaetahymeawxy", "khphblhcgmbupmzt", "iggoqtqpvaebtiol", "ofknifysuasshoya", "qxuewroccsbogrbv", "apsbnbkiopopytgu", "zyahfroovfjlythh", "bxhjwfgeuxlviydq", "uvbhdtvaypasaswa", "qamcjzrmesqgqdiz", "hjnjyzrxntiycyel", "wkcrwqwniczwdxgq", "hibxlvkqakusswkx", "mzjyuenepwdgrkty", "tvywsoqslfsulses", "jqwcwuuisrclircv", "xanwaoebfrzhurct", "ykriratovsvxxasf", "qyebvtqqxbjuuwuo", "telrvlwvriylnder", "acksrrptgnhkeiaa", "yemwfjhiqlzsvdxf", "banrornfkcymmkcc", "ytbhxvaeiigjpcgm", "crepyazgxquposkn", "xlqwdrytzwnxzwzv", "xtrbfbwopxscftps", "kwbytzukgseeyjla", "qtfdvavvjogybxjg", "ytbmvmrcxwfkgvzw", "nbscbdskdeocnfzr", "sqquwjbdxsxhcseg", "ewqxhigqcgszfsuw", "cvkyfcyfmubzwsee", "dcoawetekigxgygd", "ohgqnqhfimyuqhvi", "otisopzzpvnhctte", "bauieohjejamzien", "ewnnopzkujbvhwce", "aeyqlskpaehagdiv", "pncudvivwnnqspxy", "ytugesilgveokxcg", "zoidxeelqdjesxpr", "ducjccsuaygfchzj", "smhgllqqqcjfubfc", "nlbyyywergronmir", "prdawpbjhrzsbsvj", "nmgzhnjhlpcplmui", "eflaogtjghdjmxxz", "qolvpngucbkprrdc", "ixywxcienveltgho", "mwnpqtocagenkxut", "iskrfbwxonkguywx", "ouhtbvcaczqzmpua", "srewprgddfgmdbao", "dyufrltacelchlvu", "czmzcbrkecixuwzz", "dtbeojcztzauofuk", "prrgoehpqhngfgmw", "baolzvfrrevxsyke", "zqadgxshwiarkzwh", "vsackherluvurqqj", "surbpxdulvcvgjbd", "wqxytarcxzgxhvtx", "vbcubqvejcfsgrac", "zqnjfeapshjowzja", "hekvbhtainkvbynx", "knnugxoktxpvoxnh", "knoaalcefpgtvlwm", "qoakaunowmsuvkus", "ypkvlzcduzlezqcb", "ujhcagawtyepyogh", "wsilcrxncnffaxjf", "gbbycjuscquaycrk", "aduojapeaqwivnly", "ceafyxrakviagcjy", "nntajnghicgnrlst", "vdodpeherjmmvbje", "wyyhrnegblwvdobn", "xlfurpghkpbzhhif", "xyppnjiljvirmqjo", "kglzqahipnddanpi", "omjateouxikwxowr", "ocifnoopfglmndcx", "emudcukfbadyijev", "ooktviixetfddfmh", "wtvrhloyjewdeycg", "cgjncqykgutfjhvb", "nkwvpswppeffmwad", "hqbcmfhzkxmnrivg", "mdskbvzguxvieilr", "anjcvqpavhdloaqh", "erksespdevjylenq", "fadxwbmisazyegup", "iyuiffjmcaahowhj", "ygkdezmynmltodbv", "fytneukxqkjattvh", "woerxfadbfrvdcnz", "iwsljvkyfastccoa", "movylhjranlorofe", "drdmicdaiwukemep", "knfgtsmuhfcvvshg", "ibstpbevqmdlhajn", "tstwsswswrxlzrqs", "estyydmzothggudf", "jezogwvymvikszwa", "izmqcwdyggibliet", "nzpxbegurwnwrnca", "kzkojelnvkwfublh", "xqcssgozuxfqtiwi", "tcdoigumjrgvczfv", "ikcjyubjmylkwlwq", "kqfivwystpqzvhan", "bzukgvyoqewniivj", "iduapzclhhyfladn", "fbpyzxdfmkrtfaeg", "yzsmlbnftftgwadz" ] def part1(): def contains_three_vowels(x): n = 0 for c in x: if c in "aeiou": n += 1 return n >= 3 def contains_dubble(x): for i in range(len(x) - 1): if x[i] == x[i + 1]: return True return False def contains_forbidden(x): forbidden = ["ab", "cd", "pq", "xy"] for i in range(len(x) - 1): if x[i] + x[i + 1] in forbidden: return True return False n = 0 for x in strings: if contains_three_vowels(x) and contains_dubble(x) and not contains_forbidden(x): n += 1 print("Number of nice strings: {}".format(n)) def part2(): def contains_pairs(x): for i in range(len(x) - 3): if x.find(x[i] + x[i + 1], i + 2) >= 0: return True return False def contains_dubble(x): for i in range(len(x) - 2): if x[i] == x[i + 2]: return True return False n = 0 for x in strings: if contains_pairs(x) and contains_dubble(x): n += 1 print("Number of nice strings: {}".format(n)) part1() part2()
23.877956
89
0.657435
1,179
25,239
14.063613
0.884648
0.000965
0.003619
0.002654
0.022556
0.019661
0.016465
0.0155
0.0155
0.0155
0
0.001114
0.217521
25,239
1,056
90
23.900568
0.838473
0.000832
0
0.021093
0
0
0.63707
0
0
0
0
0
0
1
0.006711
false
0
0
0
0.01534
0.001918
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d8d6931ac65cc6a255b6512843a2e8987070ceab
1,991
py
Python
diapers3ok.py
txt/evil
a08188d16cb983f329b8a0d03565cc108f435eff
[ "Unlicense" ]
1
2016-08-03T03:45:18.000Z
2016-08-03T03:45:18.000Z
diapers3ok.py
txt/evil
a08188d16cb983f329b8a0d03565cc108f435eff
[ "Unlicense" ]
null
null
null
diapers3ok.py
txt/evil
a08188d16cb983f329b8a0d03565cc108f435eff
[ "Unlicense" ]
1
2018-06-22T15:21:57.000Z
2018-06-22T15:21:57.000Z
from __future__ import print_function,division from diapers3 import * #@ok def _o(): x=o(a=1,b=2) #print(x) x.has().update(dict(c=3,b=5)) #print(x) y = x.copy() y.a=10 assert y.a == 10 and x.a==1 y["a"] = y["a"] + 100 assert y.a == 110 #@ok def _thing(): z = Thing("zz",init=91.34233,prec=0,step=3) a = Thing("aa",init=91.34233,prec=0,step=3) assert z.restrain(-10) == 0 t = Time(hi=32) ts = Things(z=z,A=a,T=t) assert sorted(ts.init().has().values()) == [0,91.34233,91.34233] return ts def _log(): ts = _thing() log = Log(ts,steps=5) for dt,t,u,v in sim(ts,spy=8): True #ok def _diapers(): print(222) Diapers().run() # ts 5.73933090614 5.73933090614 # ep 22.4757767473 22.4757767473 # early 67.2864581745 67.2864581745 # late 72.9962277924 72.9962277924 # inc 7.0 11.0 # done! 2015-06-29 08:47:45.962529 """ ts 1.18736297658 1.18736297658 ep 11.6078068745 11.6078068745 early 69.5446699078 69.5446699078 late 73.2893699124 73.2893699124 inc 3.0 4.0 """ @ok def brooks0(): b = BrooksLaw() b.run(10,verbose=True,whatif=dict(ts=6,ep=2,early=67,late=73,inc=20)) #@ok def _brooks1(): seed(1) y = 0 out = None max = -1 for x in xrange(104): b = BrooksLaw() d1 = b.things().any() d1.inc = round(d1.inc) d2 = d1.copy() while d2.inc <= d1.inc: d2.inc = round(d1.inc*3*r()) v1 = b.run(20,verbose=False ,whatif=d1) v2 = b.run(20,verbose=False ,whatif=d2) t1 = v1.T t2 = v2.T if 0.99*t1 <= t2 <= 1.01*t1: if d2.inc - d1.inc > max: max = t2 - t1 out = (d1,d2) y += 1 say(" ",int(100*y/(x+1))) elif t2 > t1: print("\n>>",t1,t2,t2/t1) for k,v in b.things().things.items(): if v.touch: print(k,d1[k],d2[k]) else: print("!!",t2/t1) d1,d2 = out print("") for k,v in b.things().things.items(): if v.touch: print(k,d1[k],d2[k]) print("done!",now())
20.739583
71
0.56002
359
1,991
3.075209
0.350975
0.022645
0.007246
0.027174
0.163043
0.163043
0.119565
0.081522
0.081522
0.081522
0
0.235372
0.244601
1,991
95
72
20.957895
0.49867
0.102963
0
0.123077
0
0
0.01107
0
0
0
0
0
0.061538
1
0.092308
false
0
0.030769
0
0.138462
0.123077
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d8d83bcade61f8cc9866d368b192e1b85e86d4f4
495
py
Python
LeetCode/LeetCode_Python-master/LeetCode_Python-master/Algorithm-Medium/template.py
Sycamore-City-passerby/ML
605cfc70bdda2c99e5f1c16b25812b59c98a72ad
[ "MIT" ]
null
null
null
LeetCode/LeetCode_Python-master/LeetCode_Python-master/Algorithm-Medium/template.py
Sycamore-City-passerby/ML
605cfc70bdda2c99e5f1c16b25812b59c98a72ad
[ "MIT" ]
null
null
null
LeetCode/LeetCode_Python-master/LeetCode_Python-master/Algorithm-Medium/template.py
Sycamore-City-passerby/ML
605cfc70bdda2c99e5f1c16b25812b59c98a72ad
[ "MIT" ]
null
null
null
""" Time Complexity = O(log(N)) Space Complexity = O(1) Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. """
30.9375
99
0.660606
78
495
4.192308
0.576923
0.067278
0.079511
0.091743
0
0
0
0
0
0
0
0.030556
0.272727
495
15
100
33
0.877778
0.892929
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
d8dcc1a8543ac67aa55c99a59bd7458034752d1e
359
py
Python
python_toy_package/python_toy_package.py
marvinmin/python_toy_package
120d1863cbfd9b0e677da286f5ebae5d7bc2b45d
[ "MIT" ]
null
null
null
python_toy_package/python_toy_package.py
marvinmin/python_toy_package
120d1863cbfd9b0e677da286f5ebae5d7bc2b45d
[ "MIT" ]
null
null
null
python_toy_package/python_toy_package.py
marvinmin/python_toy_package
120d1863cbfd9b0e677da286f5ebae5d7bc2b45d
[ "MIT" ]
null
null
null
import numpy as np def sqsum(a): """ Calculate the squared sum of a list Parameters ---------- a: list the list of numbers to be calculated Return ------ float the squared sum Examples -------- >>> a = [1, 2, 3] >>> sqsum(a) 14 """ a = np.array(a) return np.sum(a**2)
14.958333
44
0.456825
46
359
3.565217
0.565217
0.073171
0.158537
0
0
0
0
0
0
0
0
0.027273
0.387187
359
23
45
15.608696
0.718182
0.559889
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d8dd7ab9f8022a1d5d19b99b9dcacfc83e2b21d8
5,254
py
Python
src/somewhat_homomorphic_keygen.py
UMComp4140ATeam/Raymond
2ccff4d15835ab386d3e25b2bb3a7ed03feffe81
[ "MIT" ]
1
2015-10-04T16:19:16.000Z
2015-10-04T16:19:16.000Z
src/somewhat_homomorphic_keygen.py
UMComp4140ATeam/Raymond
2ccff4d15835ab386d3e25b2bb3a7ed03feffe81
[ "MIT" ]
null
null
null
src/somewhat_homomorphic_keygen.py
UMComp4140ATeam/Raymond
2ccff4d15835ab386d3e25b2bb3a7ed03feffe81
[ "MIT" ]
null
null
null
#!/bin/python import logging import math import numpy import simple_error_distribution import rvg ''' Generates the secret keys, the evaluation key, and the public key that will be used in the homomorphic encryption scheme. ''' class SomewhatHomomorphicKeygen(object): def __init__(self, dimension, multiplicative_depth, odd_modulus, matrix_rows, seed=1, log=logging.getLogger(__name__)): self.__dimension = dimension self.__multiplicative_depth = multiplicative_depth self.__odd_modulus = odd_modulus self.__matrix_rows = matrix_rows self.__error_distribution = simple_error_distribution.SimpleErrorDistribution(odd_modulus, seed) self.__random_vector_generator = rvg.RVG(dimension, odd_modulus, seed) self.__log = log def set_error_distribution(self, new_error_distribution): self.__error_distribution = new_error_distribution def set_random_vector_generator(self, new_random_vector_generator): self.__random_vector_generator = new_random_vector_generator def generate_keys(self): secret_keys = self.__generate_secret_key() evaluation_key = self.__generate_evaluation_key(secret_keys) public_key = self.__generate_public_key(secret_keys) return secret_keys[-1], evaluation_key, public_key def __generate_secret_key(self): self.__log.info("Generating Secret Keys") keys = [key for key in self.__random_vector_generator.generate(self.__multiplicative_depth + 1)] self.__log.debug("Generated secrect keys: {keys}".format(keys=keys)) return keys def __generate_evaluation_key(self, secret_keys): self.__log.info("Generating Evaluation Key") evaluation_key = {} # Assume that 0 is not included because the b component of the tuple is calculated using curr_depth - 1 for curr_depth in range(1, self.__multiplicative_depth+1): for j in range(self.__dimension+1): for i in range(j + 1): tau = 0 for coefficient_vector in self.__random_vector_generator.generate(int(math.log(self.__odd_modulus, 2)) + 1): self.__log.debug("Generating Evaluation Key for level={level} i={i} j={j} tau={tau}".format(level=curr_depth, i=i, j=j, tau=tau)) self.__log.debug("Vector Generated = {vector}".format(vector=coefficient_vector)) error = self.__error_distribution.sample_distribution() self.__log.debug("Error Generated = {error}".format(error=error)) # Artifacts of the notations used, see start of section 2 of the paper right near the top of page 9. Don't ask me why this is used # it is incredibly confusing. # Note: These 1 values are also not used in the inner product si = 1 if i != 0: si = secret_keys[curr_depth-1][i-1] sj = 1 if j != 0: sj = secret_keys[curr_depth-1][j-1] self.__log.debug("Calculating b. Inputs: cvector={cvector}, skey={skey}, error={error}, tau={tau}, si={si}, sj={sj}".format(cvector=coefficient_vector, skey=secret_keys[curr_depth], error=error, tau=tau, si=si, sj=sj)) b = (coefficient_vector.dot(secret_keys[curr_depth]) + 2 * error + 2**tau * si * sj) % self.__odd_modulus # For now I will leave this as a list of tuples, may need to exchange for a dictionary indexed by the tuple (curr_depth, i, j, tau). Also # because numpy is stupid and doesn't properly implement == we have to covert the coefficient_vector to a list evaluation_key[(curr_depth, i, j, tau)] = (coefficient_vector, b) self.__log.debug("Evaluation Key Entry={entry}".format(entry=(coefficient_vector, b))) tau += 1 return evaluation_key def __generate_public_key(self, secret_keys): self.__log.info("Generating Public Key") coefficient_vectors = [] for vector in self.__random_vector_generator.generate(self.__matrix_rows): coefficient_vectors.append(vector) coefficient_matrix = numpy.matrix(coefficient_vectors) self.__log.debug("Coefficient Matrix={matrix}".format(matrix=coefficient_matrix)) errors = [] for i in range(self.__matrix_rows): errors.append(self.__error_distribution.sample_distribution()) errors_matrix = numpy.matrix(errors).transpose() self.__log.debug("Errors={errors}".format(errors=errors_matrix)) secret_key_vector = numpy.matrix(secret_keys[0]).transpose() b = numpy.mod(coefficient_matrix.dot(secret_key_vector) + 2 * errors_matrix, self.__odd_modulus) self.__log.debug("B={b}".format(b=b)) return coefficient_matrix, b if __name__=="__main__": print "SomewhatHomomorphicKeygen Class"
55.305263
242
0.633422
637
5,254
4.894819
0.22606
0.041693
0.034638
0.04009
0.133098
0.086273
0.079859
0.039769
0
0
0
0.007376
0.277503
5,254
95
243
55.305263
0.814015
0.109821
0
0
1
0.014286
0.093791
0.005504
0
0
0
0
0
0
null
null
0
0.071429
null
null
0.014286
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
d8e13d9c5c95870299301b3d6907a824b8905ba2
782
py
Python
tests/ibmi/blackrock/test_remote_recording_control.py
sgowda/brain-python-interface
708e2a5229d0496a8ce9de32bda66f0925d366d9
[ "Apache-2.0" ]
7
2015-08-25T00:28:49.000Z
2020-04-14T22:58:51.000Z
tests/ibmi/blackrock/test_remote_recording_control.py
sgowda/brain-python-interface
708e2a5229d0496a8ce9de32bda66f0925d366d9
[ "Apache-2.0" ]
89
2020-08-03T16:54:08.000Z
2022-03-09T19:56:19.000Z
tests/ibmi/blackrock/test_remote_recording_control.py
sgowda/brain-python-interface
708e2a5229d0496a8ce9de32bda66f0925d366d9
[ "Apache-2.0" ]
4
2020-03-06T15:39:00.000Z
2021-05-26T17:03:21.000Z
import comedi import time com = comedi.comedi_open("/dev/comedi0") # start (or resume) recording print('starting recording') # set strobe pin low comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16) # set last data pin ("D15"; 16th pin) high comedi.comedi_dio_bitfield2(com, 0, 1, 1, 15) # set strobe pin high comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16) # set strobe pin low comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16) print('waiting for 5 seconds...') time.sleep(5) # stop recording print('stopping recording') # strobe pin should already be low # set last data pin ("D15"; 16th pin) low comedi.comedi_dio_bitfield2(com, 0, 1, 0, 15) # set strobe pin high comedi.comedi_dio_bitfield2(com, 0, 1, 1, 16) # set strobe pin low comedi.comedi_dio_bitfield2(com, 0, 1, 0, 16)
19.55
45
0.717391
135
782
4.044444
0.281481
0.175824
0.192308
0.307692
0.652015
0.652015
0.652015
0.575092
0.575092
0.575092
0
0.080547
0.158568
782
39
46
20.051282
0.74924
0.323529
0
0.357143
0
0
0.139535
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.214286
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2b05d2bf6c81bbfb7364b65661bcc20fefe0058d
414
py
Python
ipython-7.29.0/docs/sphinxext/configtraits.py
JohnLauFoo/clc_packages_Yu
259f01d9b5c02154ce258734d519ae8995cd0991
[ "MIT" ]
1
2021-11-13T17:21:44.000Z
2021-11-13T17:21:44.000Z
ipython-7.29.0/docs/sphinxext/configtraits.py
JohnLauFoo/clc_packages_Yu
259f01d9b5c02154ce258734d519ae8995cd0991
[ "MIT" ]
null
null
null
ipython-7.29.0/docs/sphinxext/configtraits.py
JohnLauFoo/clc_packages_Yu
259f01d9b5c02154ce258734d519ae8995cd0991
[ "MIT" ]
null
null
null
"""Directives and roles for documenting traitlets config options. :: .. configtrait:: Application.log_datefmt Description goes here. Cross reference like this: :configtrait:`Application.log_datefmt`. """ def setup(app): app.add_object_type('configtrait', 'configtrait', objname='Config option') metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
24.352941
78
0.719807
46
414
6.304348
0.73913
0.151724
0.172414
0.22069
0
0
0
0
0
0
0
0
0.166667
414
16
79
25.875
0.84058
0.521739
0
0
0
0
0.376963
0
0
0
0
0
0
1
0.25
false
0
0
0
0.5
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
2b1b328dfd77ce2fb3d05b965893466405aba2fe
17,460
py
Python
bundle/wsgi/pgwu_sgwu.py
MobileCloudNetworking/epcaas
aa1c4c032790a52617c50a40c22699b7de94edd3
[ "Apache-2.0" ]
null
null
null
bundle/wsgi/pgwu_sgwu.py
MobileCloudNetworking/epcaas
aa1c4c032790a52617c50a40c22699b7de94edd3
[ "Apache-2.0" ]
null
null
null
bundle/wsgi/pgwu_sgwu.py
MobileCloudNetworking/epcaas
aa1c4c032790a52617c50a40c22699b7de94edd3
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2014, Telecom Italia SpA """ Service Orchestrator for OpenEPC. MCN 2014 """ __author__ = 'sruffino' import json import os import requests from interfaces.ServiceAdapter import ServiceAdapter as ABCServiceAdapter class PgwuSgwuAdapter(ABCServiceAdapter): def __init__(self, conf_proxy): """ Initializes a new ServiceAdapter. :return: """ # -------------------------------------------------------# # Parameters for preinit/install # -------------------------------------------------------# self.PGWU_SGWU_ID="3812090105" # (e.g.: 3812090105 ) The unit id generated by orchestrator (or whatever ID generated by you ) self.OFP_DATAPATH_ID="3812090105000000" # (e.g.: $PGWU_SGWU_ID000000) unit id with appended zeros to match length for datapath_id self.UPLOAD_FLOATING_NETWORK_CIDR="193.55.112.80" # (e.g.: 192.168.95.0/24 ) Example from the wall self.PGWU_SGWU_NET_A_IP="4.4.4.10" self.PGWU_SGWU_NET_B_IP="" self.PGWU_SGWU_NET_MGMT_IP="3.3.3.10" self.PGWU_SGWU_NET_D_IP="5.5.5.10" self.ZABBIX_IP="9.9.9.9" self.PGW_U_Upload_Interface_IP=self.PGWU_SGWU_NET_B_IP self.PGW_U_Download_Interface_IP=self.PGWU_SGWU_NET_A_IP # -------------------------------------------------------# # Paramters for gw relation # -------------------------------------------------------# self.GW_NET_A_IP="4.4.4.3" self.PGWU_NET_A_IP_ENDING_NUMBER="10" # The last number from the net_a IP of the pgwu-sgwu self.GW_NET_A_IP_ENDING_NUMBER="3" # The last number from the net_a IP of the gw self.VIRT_NET_A_IP="192.168.77." + self.PGWU_NET_A_IP_ENDING_NUMBER # e.g. 192.168.77.210 when pgwu-sgwu got 172.30.5.210 self.VIRT_NET_A_GW_IP="192.168.77" + self.GW_NET_A_IP_ENDING_NUMBER # e.g. 192.168.77.204 when gw got 172.20.5.204 # -------------------------------------------------------# # Paramters for pgw_c relation # -------------------------------------------------------# self.PGW_C_Openflow_Transport_Protocol="tcp" self.PGW_C_Openflow_IP="3.3.3.30" # The MGMT_IP of pgw_c self.PGW_C_OpenFlow_Port="6634" # -------------------------------------------------------# # Configuration proxy self.proxies = { "http": "http://" + conf_proxy + ":3128", "https": "http://" + conf_proxy + ":3128" } def preinit(self, config): """ sends the preinit method based on the received config parameters curl -X POST -H "Content-Type:application/json" -d \ "{\"parameters\":[\"net_d=$PGWU_SGWU_NET_D_IP,mgmt=$PGWU_SGWU_NET_MGMT_IP,\ net_a=$PGWU_SGWU_NET_A_IP\",\ \"$ZABBIX_IP\"]}" http://$NAT_PUBLIC_IP:8390/pgw_u-sgw_u-5G/preinit :param config: :return: """ parameters = [] networks = "" for net_name, net_ip in config['ips'].items(): networks = networks + ("%s=%s;"%(net_name,net_ip)) parameters.append(networks) parameters.append(config['zabbix_ip']) request = {"parameters":parameters} print "I'm the pgwu-sgwu adapter, preinit pgwu-sgwu service, \ parameters %s, request %s" %(parameters,str(json.dumps(request))) url = 'http://' + config['floating_ips'].get('mgmt') + \ ':8390/pgw_u-sgw_u-5G/preinit' headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, preinit pgwu-sgwu services, \ received resp %s" %response return True def install(self, config): """ Creates a new Service based on the config file. curl -X POST -H "Content-Type:application/json" -d \ "{\"parameters\":[\"PGW-U-$PGWU_SGWU_ID\",\"$PGWU_SGWU_NET_MGMT_IP\",\ \"$PGW_U_Upload_Interface_IP\",\"$PGW_U_Download_Interface_IP\",\ \"$OFP_DATAPATH_ID\",\"true\",\"$UPLOAD_FLOATING_NETWORK_CIDR\"]}" \ http://127.0.0.1:8390/pgw_u-sgw_u-5G/install :params config: :return: """ exp_params = ['PGWU_SGWU_ID', 'PGWU_SGWU_NET_MGMT_IP', 'PGW_U_Upload_Interface_IP', 'PGW_U_Download_Interface_IP', 'OFP_DATAPATH_ID', 'UPLOAD_FLOATING_NETWORK_CIDR'] # pgwu-sgwu for v in exp_params: if v not in config: print "PGWU-SGWU adapter - install _ missing parameter: " + v return False parameters = [] parameters.append('PGW-U-' + config['PGWU_SGWU_ID']) parameters.append(config['PGWU_SGWU_NET_MGMT_IP']) parameters.append(config['PGW_U_Upload_Interface_IP']) parameters.append(config['PGW_U_Download_Interface_IP']) parameters.append(config['OFP_DATAPATH_ID']) parameters.append('true') parameters.append(config['UPLOAD_FLOATING_NETWORK_CIDR']) # create request nat request = {"parameters":parameters} print "I'm the pgwu-sgwu adapter, install pgwu-sgwu service, parameters %s" %(parameters) url = 'http://' + config['floating_ips'].get('mgmt') + \ ':8390/pgw_u-sgw_u-5G/install' headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, installing pgwu-sgwu service, received resp %s" %response return True def pre_start(self, config): """ Pre-start method curl -X POST -H "Content-Type:application/json" -d \ "{\"parameters\":[\"PGW-U-$PGWU_SGWU_ID\",\"$PGWU_SGWU_NET_MGMT_IP\",\ \"$PGW_U_Upload_Interface_IP\",\"$PGW_U_Download_Interface_IP\",\ \"$OFP_DATAPATH_ID\",\"$PGW_C_Openflow_IP\",\"$PGW_C_OpenFlow_Port\"]}" \ http://127.0.0.1:8390/pgw_u-sgw_u-5G/preStart :param config: :return: """ exp_params = ['PGWU_SGWU_ID', 'PGWU_SGWU_NET_MGMT_IP', 'PGW_U_Upload_Interface_IP', 'PGW_U_Download_Interface_IP', 'OFP_DATAPATH_ID', 'PGW_C_Openflow_IP', 'PGW_C_OpenFlow_Port'] # pgwu-sgwu for v in exp_params: if v not in config: print "PGWU-SGWU adapter - preStart _ missing parameter: " + v return False parameters = [] parameters.append('PGW-U-' + config['PGWU_SGWU_ID']) parameters.append(config['PGWU_SGWU_NET_MGMT_IP']) parameters.append(config['PGW_U_Upload_Interface_IP']) parameters.append(config['PGW_U_Download_Interface_IP']) parameters.append(config['OFP_DATAPATH_ID']) parameters.append(config['PGW_C_Openflow_IP']) parameters.append(config['PGW_C_OpenFlow_Port']) # create request nat request = {"parameters":parameters} print "I'm the pgwu-sgwu adapter, preStart pgwu-sgwu service, parameters %s" %(parameters) url = 'http://' + config['floating_ips'].get('mgmt') + \ ':8390/pgw_u-sgw_u-5G/preStart' headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, preStarting pgwu-sgwu service, received resp %s" %response return True def add_dependency(self, config, ext_service): """ Add the dependency between this service and the external one curl -X POST -H "Content-Type:application/json" -d \ "{\"parameters\":[\"$PGWU_SGWU_NET_A_IP\",\"$GW_NET_A_IP\", \ \"$VIRT_NET_A_IP\",\"$VIRT_NET_A_GW_IP\"]}" \ http://127.0.0.1:8390/pgw_u-sgw_u-5G/addRelation/gw curl -X POST -H "Content-Type:application/json" -d \ "{\"parameters\":[\"$PGW_C_Openflow_Transport_Protocol\",\ \"$PGW_C_Openflow_IP\",\"$PGW_C_OpenFlow_Port\"]}" \ http://127.0.0.1:8390/pgw_u-sgw_u-5G/addRelation/pgw_c :return: """ exp_params_gw = ['PGWU_SGWU_NET_A_IP', 'GW_NET_A_IP', 'VIRT_NET_A_IP', 'VIRT_NET_A_GW_IP'] exp_params_pgw_c = ['PGW_C_Openflow_Transport_Protocol', 'PGW_C_Openflow_IP', 'PGW_C_OpenFlow_Port'] parameters = [] if ext_service == 'gw': for v in exp_params_gw: if v not in config: print "PGWU-SGWU adapter - add_relation _ missing parameter: " + v return False # parameters require a specific order parameters.append(config['PGWU_SGWU_NET_A_IP']) parameters.append(config['GW_NET_A_IP']) parameters.append(config['VIRT_NET_A_IP']) parameters.append(config['VIRT_NET_A_GW_IP']) elif ext_service == 'pgw_c': for v in exp_params_pgw_c: if v not in config: print "PGWU-SGWU adapter - add_relation _ missing parameter: " + v return False # parameters require a specific order parameters.append(config['PGW_C_Openflow_Transport_Protocol']) parameters.append(config['PGW_C_Openflow_IP']) parameters.append(config['PGW_C_OpenFlow_Port']) else: print ("PGWU-SGWU adapter - wrong ext_service") request = {"parameters":parameters} print "I'm the pgwu-sgwu adapter, adding " + ext_service + " relation to pgwu-sgwu service, parameters %s" %(parameters) url = 'http://' + config['floating_ips'].get('mgmt')+ \ ':8390/pgw_u-sgw_u-5G/addRelation/' + ext_service headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, adding " + ext_service + " relation to pgwu-sgwu service, received resp %s" %response return True def remove_dependency(self, config, ext_service=None): """ Remove the dependency between this service and the external one 1) For the switch you need to call the relation departed script to the nat : curl -X POST -H "Content-Type:application/json" -d "{\"parameters\":[\"$PGWU_SGWU_NET_A_IP\"]}" http://127.0.0.1:8390/pgw_u-sgw_u-5G/removeRelation/gw :return: """ exp_params = ['PGWU_SGWU_NET_A_IP'] for v in exp_params: if v not in config: print "PGWU-SGWU adapter - " \ "remove_dependency _ missing parameter: " + v return False parameters = [] parameters.append(config['PGWU_SGWU_NET_A_IP']) request = {"parameters": parameters} print "I'm the pgwu-sgwu adapter, " \ "remove_dependency pgwu-sgwu service, parameters %s" % parameters url = 'http://' + config['floating_ips'].get('mgmt') + \ ':8390/pgw_u-sgw_u-5G/removeRelation/gw' headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, " \ "remove_dependency pgwu-sgwu service, received resp %s" % response return True def start(self, config): """ Sending start requests to the different components curl -X POST -H "Content-Type:application/json" \ -d "{\"parameters\":[]}" http://$NAT_PUBLIC_IP:8390/gw/start :return: """ parameters = [] request = {"parameters":parameters} print "I'm the pgwu-sgwu adapter, adding pgwu relation to pgwu-sgwu service, parameters %s" %(parameters) url = 'http://' + config['floating_ips'].get('mgmt') + ':8390/pgw_u-sgw_u-5G/start' headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(request), headers=headers, proxies=self.proxies) print response.content print "I'm the pgwu-sgwu adapter, adding pgwu relation to pgwu-sgwu service, received resp %s" %response return True def terminate(self): """ Terminate the service :return: """ pass if __name__ == '__main__': from utils import * from globals import * # set http_proxy to epc-proxy VM # since we use the proxy, no floating_ip needed conf_proxy = 'FILLME FOR TESTING' #os.environ['http_proxy']='http://130.92.70.187:3128' c = PgwuSgwuAdapter(conf_proxy) # NOTE NOTE: out must be filled with heat output string out = 'FILL ME FOR TESTING' nat_ip = get_ips(out, 'mcn.endpoint.nat') nat_ip_net_a = get_ips(out, 'nat.net_a.ip') pgwu1_ip = get_ips(out, 'mcn.endpoint.pgwu-sgwu-1') pgwu1_ip_net_a = get_ips(out, 'pgwu-sgwu-1.net_a.ip') mme_ip = get_ips(out, 'mcn.endpoint.mme-pgwc-sgwc') mme_ip_net_d = get_ips(out, 'mme-pgwc-sgwc.net_d.ip') pgwu1_ip_net_d = get_ips(out, 'pgwu-sgwu-1.net_d.ip') #pgwu1_ip = '192.168.85.95' # preinit config = {} config['hostname'] = PGW1_VM_NAME # config['ips'] = {'mgmt': '192.168.85.95', 'net_a': '172.19.5.95', # 'net_d': '172.19.8.95'} config['ips'] = {'mgmt': pgwu1_ip, 'net_a': pgwu1_ip_net_a, 'net_d': pgwu1_ip_net_d} config['zabbix_ip'] = '192.168.85.145' config['floating_ips'] = {'mgmt': pgwu1_ip} c.preinit(config) # install config = {} # config = {'OFP_DATAPATH_ID': '3812090105000000', # 'PGWU_SGWU_ID': '3812090105', # 'PGWU_SGWU_NET_MGMT_IP': '192.168.85.95', # 'PGW_U_Download_Interface_IP': '172.19.5.95', #net_a # 'PGW_U_Upload_Interface_IP': '172.19.8.95', # net_d # 'UPLOAD_FLOATING_NETWORK_CIDR': '130.92.70.128/25'} #floating ip subnet cidr config = {'OFP_DATAPATH_ID': '3812090105000000', 'PGWU_SGWU_ID': '3812090105', 'PGWU_SGWU_NET_MGMT_IP': pgwu1_ip, 'PGW_U_Download_Interface_IP': pgwu1_ip_net_a, #net_a 'PGW_U_Upload_Interface_IP': pgwu1_ip_net_d, # net_d 'UPLOAD_FLOATING_NETWORK_CIDR': '130.92.70.128/25'} #floating ip subnet cidr config['floating_ips'] = {'mgmt': pgwu1_ip} c.install(config) # add dependency to gw(nat) config = {} config = { 'PGWU_SGWU_NET_A_IP': pgwu1_ip_net_a, 'GW_NET_A_IP': nat_ip_net_a, # The last number from the net_a IP of the pgwu-sgwu 'PGWU_NET_A_IP_ENDING_NUMBER': pgwu1_ip.split('.')[3], # The last number from the net_a IP of the gw 'GW_NET_A_IP_ENDING_NUMBER': nat_ip_net_a.split('.')[3] } # config = { # 'PGWU_SGWU_NET_A_IP': '172.19.5.95', # 'GW_NET_A_IP':'172.19.5.96', # 'PGWU_NET_A_IP_ENDING_NUMBER':'95', # 'GW_NET_A_IP_ENDING_NUMBER':'96' # } config['VIRT_NET_A_IP'] = '192.168.77.' + config['PGWU_NET_A_IP_ENDING_NUMBER'] # e.g. 192.168.77.210 when pgwu-sgwu got 172.30.5.210 config['VIRT_NET_A_GW_IP'] = '192.168.77.' + config['GW_NET_A_IP_ENDING_NUMBER'] # e.g. 192.168.77.204 when gw got 172.20.5.204 config['floating_ips'] = {'mgmt': pgwu1_ip} c.add_dependency(config, 'gw') # add dependency to pgw_c config = {} config = { 'PGW_C_Openflow_Transport_Protocol':'tcp', #'PGW_C_Openflow_IP': '192.168.85.97', # The MGMT_IP of mme 'PGW_C_Openflow_IP': mme_ip, # The MGMT_IP of mme 'PGW_C_OpenFlow_Port':'6634' } config['floating_ips'] = {'mgmt': pgwu1_ip} c.add_dependency(config, 'pgw_c') # prestart config = {} # config = { # 'PGWU_SGWU_ID': '3812090105', # 'PGWU_SGWU_NET_MGMT_IP': '192.168.85.95', # 'PGW_U_Download_Interface_IP': '172.19.5.95', #net_a # 'PGW_U_Upload_Interface_IP': '172.19.8.95', # net_d # 'OFP_DATAPATH_ID': '3812090105000000', # 'PGW_C_Openflow_IP':'192.168.85.97', # The MGMT_IP of mme # 'PGW_C_OpenFlow_Port':'6634' # } config = { 'PGWU_SGWU_ID': '3812090105', 'PGWU_SGWU_NET_MGMT_IP': pgwu1_ip, 'PGW_U_Download_Interface_IP': pgwu1_ip_net_a, #net_a 'PGW_U_Upload_Interface_IP': pgwu1_ip_net_d, # net_d 'OFP_DATAPATH_ID': '3812090105000000', 'PGW_C_Openflow_IP': mme_ip, # The MGMT_IP of mme 'PGW_C_OpenFlow_Port':'6634' } config['floating_ips'] = {'mgmt': pgwu1_ip} c.pre_start(config) config = {} config['floating_ips'] = {'mgmt': pgwu1_ip} c.start(config)
41.374408
138
0.585223
2,266
17,460
4.219771
0.109885
0.065258
0.023844
0.035348
0.761556
0.717319
0.670153
0.632085
0.615562
0.59841
0
0.050133
0.267698
17,460
421
139
41.472684
0.697716
0.150115
0
0.478448
0
0.008621
0.305677
0.083826
0
0
0
0
0
0
null
null
0.00431
0.025862
null
null
0.103448
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
2b1d8d896f28182ee81f486f437c6eeed50e60d4
635
py
Python
design-patterns/structural/interpreter.py
verthais/exercise-python
d989647e8fbfe8a79b9b5f2c3ab003715d238851
[ "MIT" ]
null
null
null
design-patterns/structural/interpreter.py
verthais/exercise-python
d989647e8fbfe8a79b9b5f2c3ab003715d238851
[ "MIT" ]
null
null
null
design-patterns/structural/interpreter.py
verthais/exercise-python
d989647e8fbfe8a79b9b5f2c3ab003715d238851
[ "MIT" ]
null
null
null
from abc import abstractmethod class AbstractExpression(): @abstractmethod def interpret(self): pass class NonterminalExpression(AbstractExpression): def __init__(self, expression): self._expression = expression def interpret(self): print("Non-terminal expression being interpreted ...") self._expression.interpret() class TerminalExpression(AbstractExpression): def interpret(self): print("Terminal expression being interpreted ...") def main(): ast = NonterminalExpression(NonterminalExpression(TerminalExpression())) ast.interpret() if __name__ == "__main__": main()
18.676471
74
0.724409
56
635
7.964286
0.410714
0.080717
0.107623
0.09417
0
0
0
0
0
0
0
0
0.174803
635
33
75
19.242424
0.851145
0
0
0.157895
0
0
0.156146
0
0
0
0
0
0
1
0.263158
false
0.052632
0.052632
0
0.473684
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
2b2f4de3511c7585c7d5f1527811e554f700b9b7
406
py
Python
assets/tuned/daemon/tuned/profiles/functions/function_strip.py
sjug/cluster-node-tuning-operator
8654d1c9558d0d5ef03d14373c877ebc737f9736
[ "Apache-2.0" ]
53
2018-11-13T07:02:03.000Z
2022-03-25T00:00:04.000Z
assets/tuned/daemon/tuned/profiles/functions/function_strip.py
sjug/cluster-node-tuning-operator
8654d1c9558d0d5ef03d14373c877ebc737f9736
[ "Apache-2.0" ]
324
2018-10-02T14:18:54.000Z
2022-03-31T23:47:33.000Z
assets/tuned/daemon/tuned/profiles/functions/function_strip.py
sjug/cluster-node-tuning-operator
8654d1c9558d0d5ef03d14373c877ebc737f9736
[ "Apache-2.0" ]
54
2018-10-01T16:55:09.000Z
2022-03-28T13:56:53.000Z
import os import tuned.logs from . import base from tuned.utils.commands import commands class strip(base.Function): """ Makes string from all arguments and strip it """ def __init__(self): # unlimited number of arguments, min 1 argument super(strip, self).__init__("strip", 0, 1) def execute(self, args): if not super(strip, self).execute(args): return None return "".join(args).strip()
22.555556
49
0.716749
60
406
4.716667
0.583333
0.070671
0.09894
0
0
0
0
0
0
0
0
0.00885
0.165025
406
17
50
23.882353
0.825959
0.224138
0
0
0
0
0.016393
0
0
0
0
0
0
1
0.181818
false
0
0.363636
0
0.818182
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
2b6022c13c162252331410ea5e544abccc9ad01f
667
py
Python
python-questions-for-pratices/Question-38.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
python-questions-for-pratices/Question-38.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
python-questions-for-pratices/Question-38.py
siddharth-143/Python
293f4643a3a13e3b82d23fd8922db54dbb0f12bc
[ "MIT" ]
null
null
null
""" Question 38 : Define a function which can generated a list where the values are square of numbers between 1 and 20 (both included). Then the function need to print the last 5 elements in the list. Hints : Use ** operator to get power of a number. Use range() for loop. Use list.append() to add values into a list. Use [n1:n2] to slice a list. """ # Solution : num = int(input("Enter a number : ")) def print_value(): l = list() for i in range(1, num + 1): l.append(i**2) print(l[-5:]) print_value() """ Output : Enter a number : 20 [256, 289, 324, 361, 400] Process finished with exit code 0 """
22.233333
68
0.61919
109
667
3.770642
0.614679
0.036496
0.058394
0
0
0
0
0
0
0
0
0.061602
0.269865
667
30
69
22.233333
0.782341
0.568216
0
0
1
0
0.10241
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.142857
0.428571
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
2b648cb256dde1fafc7ef4a4dd375245fc375688
2,272
py
Python
utils/labels.py
Saaaber/urban-segmentation
fc893feb9208d3206d7c5329b1ccf4cfab97ed31
[ "MIT" ]
3
2020-11-16T20:21:25.000Z
2021-06-11T13:09:30.000Z
utils/labels.py
Saaaber/urban-segmentation
fc893feb9208d3206d7c5329b1ccf4cfab97ed31
[ "MIT" ]
null
null
null
utils/labels.py
Saaaber/urban-segmentation
fc893feb9208d3206d7c5329b1ccf4cfab97ed31
[ "MIT" ]
3
2020-11-11T23:43:15.000Z
2022-03-17T09:03:42.000Z
# Copyright (c) Ville de Montreal. All rights reserved. # Licensed under the MIT license. # See LICENSE file in the project root for full license information. CITYSCAPE_LABELS = [ ('unlabeled', 0, 0, 0, 0), ('ego vehicle', 1, 0, 0, 0), ('rectification border', 2, 0, 0, 0), ('out of roi', 3, 0, 0, 0), ('static', 4, 0, 0, 0), ('dynamic', 5, 111, 74, 0), ('ground', 6, 81, 0, 81), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('parking', 9, 250, 170, 160), ('rail track', 10, 230, 150, 140), ('building', 11, 70, 70, 70), ('wall', 12, 102, 102, 156), ('fence', 13, 190, 153, 153), ('guard rail', 14, 180, 165, 180), ('bridge', 15, 150, 100, 100), ('tunnel', 16, 150, 120, 90), ('pole', 17, 153, 153, 153), ('polegroup', 18, 153, 153, 153), ('traffic light', 19, 250, 170, 30), ('traffic sign', 20, 220, 220, 0), ('vegetation', 21, 107, 142, 35), ('terrain', 22, 152, 251, 152), ('sky', 23, 70, 130, 180), ('person', 24, 220, 20, 60), ('rider', 25, 255, 0, 0), ('car', 26, 0, 0, 142), ('truck', 27, 0, 0, 70), ('bus', 28, 0, 60, 100), ('caravan', 29, 0, 0, 90), ('trailer', 30, 0, 0, 110), ('train', 31, 0, 80, 100), ('motorcycle', 32, 0, 0, 230), ('bicycle', 33, 119, 11, 32), ('license plate', 34, 0, 0, 142)] CARLA_LABELS = [ ('void', 0, 0, 0, 0), ('building', 1, 70, 70, 70), ('fence', 2, 190, 153, 153), ('other', 3, 250, 170, 160), ('pedestrian', 4, 220, 20, 60), ('pole', 5, 153, 153, 153), ('road line', 6, 157, 234, 50), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('vegetation', 9, 107, 142, 35), ('car', 10, 0, 0, 142), ('wall', 11, 102, 102, 156), ('traffic sign', 12, 220, 220, 0)] CGMU_LABELS = [ ('void', 0, 0, 0, 0), ('pole', 1, 255, 189, 176), ('traffic sign', 2, 255, 181, 0), ('vehicle', 3, 247, 93, 195), ('vegetation', 4, 83, 145, 11), ('median strip', 5, 255, 236, 0), ('building', 6, 123, 0, 255), ('private', 7, 255, 0, 0), ('sidewalk', 8, 0, 205, 255), ('road', 9, 14, 0, 255), ('pedestrian', 10, 0, 255, 4), ('structure', 11, 134, 69, 15), ('construction', 12, 255, 99, 0)]
32
68
0.487236
348
2,272
3.172414
0.465517
0.047101
0.027174
0.01087
0.07971
0.07971
0.054348
0.054348
0.054348
0.054348
0
0.298624
0.264525
2,272
70
69
32.457143
0.362059
0.066901
0
0.09375
0
0
0.216919
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2b6b4c5cd7977ffb6f16236c51493108bc46a1c8
285
py
Python
create_db.py
danuluma/andela-project
4357948a9c9d3d1328f77dfb1bd9d6c79e458074
[ "MIT" ]
null
null
null
create_db.py
danuluma/andela-project
4357948a9c9d3d1328f77dfb1bd9d6c79e458074
[ "MIT" ]
19
2018-09-25T05:15:46.000Z
2021-09-08T00:28:03.000Z
create_db.py
danuluma/andela-project
4357948a9c9d3d1328f77dfb1bd9d6c79e458074
[ "MIT" ]
3
2018-09-26T20:35:08.000Z
2018-10-05T07:13:19.000Z
import psycopg2 conn = psycopg2.connect(user='postgres', host='localhost', password='postgres') cur = conn.cursor() cur.execute("""CREATE DATABASE mafast1;""") cur.execute("""CREATE DATABASE tfast;""") conn.commit() conn.close() cur.close() print("Congrats!! Danns database created")
25.909091
79
0.726316
35
285
5.914286
0.628571
0.096618
0.154589
0.231884
0
0
0
0
0
0
0
0.011494
0.084211
285
10
80
28.5
0.781609
0
0
0
0
0
0.364912
0
0
0
0
0
0
1
0
false
0.111111
0.111111
0
0.111111
0.111111
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
2b776210057b794534834e3bd49950d8f173cd5d
90
py
Python
mysticweb/__data.py
bentheiii/mystic
04df023a07fc411367a3a8984f9da143596085f0
[ "MIT" ]
null
null
null
mysticweb/__data.py
bentheiii/mystic
04df023a07fc411367a3a8984f9da143596085f0
[ "MIT" ]
null
null
null
mysticweb/__data.py
bentheiii/mystic
04df023a07fc411367a3a8984f9da143596085f0
[ "MIT" ]
null
null
null
__author__ = 'Ben Avrahami' __version__ = '0.6.1' __all__ = ['__author__', '__version__']
22.5
39
0.7
10
90
4.3
0.8
0
0
0
0
0
0
0
0
0
0
0.037975
0.122222
90
3
40
30
0.506329
0
0
0
0
0
0.422222
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2b77bf1f5c09561afefa836926a3f170a220cec7
888
py
Python
split.py
robertbyers1111/python
e87558f2432f0a4a86f17c47c6b19e1345625b83
[ "MIT" ]
null
null
null
split.py
robertbyers1111/python
e87558f2432f0a4a86f17c47c6b19e1345625b83
[ "MIT" ]
null
null
null
split.py
robertbyers1111/python
e87558f2432f0a4a86f17c47c6b19e1345625b83
[ "MIT" ]
null
null
null
#msg1 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" msg = """ \r abcd \n efgh wxyz \n\n 0123abcd \naabcdd \r \n \r \n \r \n \r \n 4567\r\r\n""" #------------------------------------------------------------------------------ # NOTES: # # 1. No args means split on whitespace (but it trims whitespace too) # # 2. The arg is one delimiter as a string, not a list of delimiter chars # # 3. To split and retain leading/trailing whitespace use re.split() # #------------------------------------------------------------------------------ print print '--------- (see note 1)' for line in msg.split('abcd'): print 'line:',line print print '--------- (see note 2)' for line in msg.split(): print 'line:',line print print '--------- (see note 3)' import re for line in re.split('\r|\n', msg): print 'line:', line
20.181818
106
0.531532
108
888
4.37037
0.472222
0.025424
0.019068
0.025424
0.216102
0.144068
0.127119
0
0
0
0
0.100402
0.158784
888
43
107
20.651163
0.531459
0.531532
0
0.428571
0
0.071429
0.435644
0
0
0
0
0
0
0
null
null
0
0.071429
null
null
0.642857
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
1
0
2
991657324e1bb0254e28fe202143c5292de16e44
646
py
Python
basics/8_abstract_decorators.py
pavlovprojects/python_qa_oop
587156bf14499e5e836904ebef37aa3db1933b45
[ "MIT" ]
null
null
null
basics/8_abstract_decorators.py
pavlovprojects/python_qa_oop
587156bf14499e5e836904ebef37aa3db1933b45
[ "MIT" ]
null
null
null
basics/8_abstract_decorators.py
pavlovprojects/python_qa_oop
587156bf14499e5e836904ebef37aa3db1933b45
[ "MIT" ]
null
null
null
from abc import ABC, abstractmethod, abstractproperty class Opener(ABC): @property @abstractmethod def material(self): pass @abstractmethod def open(self): return NotImplemented class Closer(ABC): @abstractmethod def close(self): return NotImplemented class Door(Opener, Closer): material = None def __init__(self, material): self.material = material def close(self): print(f"{self.material} door is opened!") def open(self): print(f"{self.material} door is closed!") glass_door = Door(material="Glass") glass_door.open() glass_door.close()
17
53
0.651703
74
646
5.594595
0.351351
0.115942
0.05314
0.140097
0.135266
0.135266
0.135266
0
0
0
0
0
0.24613
646
38
54
17
0.850103
0
0
0.375
0
0
0.103555
0
0
0
0
0
0
1
0.25
false
0.041667
0.041667
0.083333
0.541667
0.083333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
9916ce285dd636646b8ff2817f3127e28bb6af97
217
py
Python
saas/aiops/api/aiops-server/services/base_service.py
iuskye/SREWorks
a2a7446767d97ec5f6d15bd00189c42150d6c894
[ "Apache-2.0" ]
407
2022-03-16T08:09:38.000Z
2022-03-31T12:27:10.000Z
saas/aiops/api/aiops-server/services/base_service.py
Kwafoor/SREWorks
37a64a0a84b29c65cf6b77424bd2acd0c7b42e2b
[ "Apache-2.0" ]
25
2022-03-22T04:27:31.000Z
2022-03-30T08:47:28.000Z
saas/aiops/api/aiops-server/services/base_service.py
Kwafoor/SREWorks
37a64a0a84b29c65cf6b77424bd2acd0c7b42e2b
[ "Apache-2.0" ]
109
2022-03-21T17:30:44.000Z
2022-03-31T09:36:28.000Z
#!/usr/bin/env python # encoding: utf-8 """ """ __author__ = 'sreworks' from models.db_session import db class BaseService(object): def __init__(self): self.db = db self.db_session = db.session
16.692308
36
0.64977
29
217
4.517241
0.689655
0.206107
0
0
0
0
0
0
0
0
0
0.005882
0.21659
217
12
37
18.083333
0.764706
0.165899
0
0
0
0
0.046512
0
0
0
0
0
0
1
0.166667
false
0
0.166667
0
0.5
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2