text
string
size
int64
token_count
int64
from lib.core.exceptions import AppException class PathError(AppException): """ User input Error """ class EmptyOutputError(AppException): """ Empty Output Error """
194
57
from zpy.api.resource import ZResource, HTTP_METHODS class GreetingResource(ZResource): blocked_methods = [ HTTP_METHODS.POST, HTTP_METHODS.DELETE, HTTP_METHODS.PATCH, HTTP_METHODS.PUT, ] def __init__(self, **kwargs) -> None: super().__init__() def get(self):...
527
178
# coding: utf-8 import os class PyMorphy(object): @property def PYMORPHY_DICTS(self): return { 'ru': { 'dir': os.path.join(self.ROOT_PATH, 'data/pymorphy'), }, }
227
82
import re def separa_palavras(frase): '''A funcao recebe uma frase e devolve uma lista das palavras dentro da frase''' print('lista de palavras: ', frase.split())
172
60
import logging import random from .base.camp import Camp from .base.formation import Formation from .game.janggi_game import JanggiGame from .game.game_log import GameLog from .ui.game_player import GamePlayer from .ui.replay_viewer import ReplayViewer from .proto import log_pb2 logging.basicConfig() logging.root.set...
1,253
423
from data_interface import Dataset, Data_Interface from utils import functions as ufunc import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import os import rasterio as rio import rasterio.mask as riom import shapely from IPython import embed import sys sys.path.append('/home/seba/Projects/swis...
1,762
755
from rest_framework.views import APIView from rest_framework.response import Response class HelloApiView(APIView): """TEST API VIEW""" def get(self, request, format=None): """Returns a list of API features""" an_apiview=[ 'Uses HTTP methods as function (get,post, put, delete, patc...
574
157
# "Database code" for the DB Forum. import psycopg2 import bleach DNAME = "forum" #POSTS = [("This is the first post.", datetime.datetime.now())] def get_posts(): """Return all posts from the 'database', most recent first.""" db = psycopg2.connect(database=DNAME) c = db.cursor() c.execute("select content,...
911
310
#!/usr/bin/env python3 # # IP: HILICS # # 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 i...
19,553
9,036
#!/usr/bin/env python output_name = './build/libs/java.jar' def setup(): import os, datetime, subprocess if os.path.exists(os.path.join(os.getcwd(), "setup.log")): print("'setup.log' exists. Java implementation setup correctly") return print("Watch for Errors - Requires Java SDK and Runti...
1,925
600
""" Tags http://developer.pardot.com/kb/api-version-4/tags/ http://developer.pardot.com/kb/object-field-references/#tag """ tag = [{'name': 'id', 'type': 'integer'}, {'name': 'name', 'type': 'varchar(512)'}, {'name': 'created_at', 'type': 'timestamp'}, {'name': 'updated_at...
353
128
import mykde class Action(mykde.BaseAction): name = "VLC" description = "VLC Media Player" packages = ['vlc']
125
46
hello everyone, fighting~
26
10
import sys from .sitimeunit import SITimeUnit isPython3Compat = (sys.version_info.major == 3) isPython36Compat = (isPython3Compat and (sys.version_info.minor >= 6)) def normalize_frac_seconds(a, b): """Returns 3-tuple containing (normalized frac_seconds for a, normalized frac_seconds for b, most precise (sm...
3,914
1,317
""" An agent representing the (retail) customer behavior following a Poisson distribution for demand. """ import networkx as nx from scse.api.module import Agent import numpy as np import logging logger = logging.getLogger(__name__) class PoissonCustomerOrder(Agent): _DEFAULT_MAX_MEAN = 10 def __init__(self...
1,784
501
import numpy as np import os from utils import MINERL_DATA_ROOT, CUMULATIVE_REWARDS import sys import pandas def time_to_rewards(data_set, trajectory): """ Takes a data_set and a trajectory, and returns times (in ticks) to achieve each cumulative reward (from the last cumulative reward, not from...
2,340
896
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
2,224
679
import typing as t from ....extensions import ExtensionMixin from ...flarum.core.discussions import DiscussionFromBulk class PreventNecrobumpingDiscussionMixin(DiscussionFromBulk): @property def fof_prevent_necrobumping(self) -> t.Optional[int]: """ I have no idea what this does either, ...
634
209
import os import json from copy import copy from subprocess import call, Popen, PIPE, STDOUT import time import numpy as np import pandas as pd from pyproj import Transformer import rasterio import fiona from affine import Affine from shapely.geometry import shape from scipy.ndimage.morphology import binary_erosion fr...
30,988
9,942
# Importing libraries import imaplib, email user = 'vsjtestmail@gmail.com' password = 'TestMa1lPass' imap_url = 'imap.gmail.com' # Function to get email content part i.e its body part def get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) # Functi...
1,147
408
# 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 t...
5,695
1,746
from dataclasses import dataclass @dataclass class Config: """Blockchain configs""" # persistence configs BLOCKS_FILE_NAME = "data/blocks.json" MEMPOOL_FILE_NAME = "data/mempool.json" WALLET_BALANCE_FILE_NAME = "data/balance.json" SEED_WORDS_FILE_NAME = "data/seed_word_list.txt" NODE_LIST...
522
217
import logging import os import argparse from collections import defaultdict logger = logging.getLogger("paddle") logger.setLevel(logging.INFO) def parse_train_cmd(): parser = argparse.ArgumentParser( description="PaddlePaddle text classification example.") parser.add_argument( "--nn_type", ...
3,585
1,041
from .models import Card from .helpers import fetch_unidentified, populate_db from django.shortcuts import render, redirect from django.http import Http404, HttpResponse import json def index(request): next = fetch_unidentified() if next: return redirect('card', card_num=next) else: retur...
2,188
616
"""Calculate opinion perplexity for different numbers of topics Calclulate opinion perplexity for the test set as described in [Fang et al. 2012] section 5.1.1. This script should be run after experiment_number_of_topics.py. Usage: python cptm/experiment_calculate_perplexity.py /path/to/experiment.json. """ import p...
2,439
810
from flask_restful import Resource import app from app.services.healthcheck import HealthApi class HealthApiV1(HealthApi): pass
133
39
#Eulers method import numpy as np def dy(ynew,xnew,y,x,h): dyvalue = y-x return dyvalue #Note: change the derivative function based on question!!!!!! Example: y-x y0 = 0.5 #float(input"what is the y(0)?") h = 0.1 #float(input"h?") x_final = 0.3 #float(input"x_final") #initiating input variables x = 0 y ...
819
330
""" Contains Net and NetDictionary class for creating a random collection of CNN structures or loading a previously created collection. """ from __future__ import division, print_function from random import random import os.path import torch from torch import nn from torch import optim from torch.nn import functional...
18,896
5,357
import asyncio import logging import os from vmshepherd.drivers import Drivers from vmshepherd.http import WebServer from vmshepherd.utils import gen_id, prefix_logging from vmshepherd.worker import Worker class VmShepherd: def __init__(self, config): self.config = config self.root_dir = os.path....
1,917
583
"""Classes to describe different kinds of Slack specific event.""" import json from opsdroid.events import Message class Blocks(Message): """A blocks object. Slack uses blocks to add advenced interactivity and formatting to messages. https://api.slack.com/messaging/interactivity Blocks are provided...
1,762
415
from .object_tracker import ObjectTracker
42
12
from os.path import join import argparse import pickle import warnings import pandas as pd from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.models import load_model import utils from malconv import Malconv from preprocess import preprocess warnings.filterwarnings("ignore") parser = argparse.Argu...
3,449
1,179
'''We will test all routegetter methods in this test suite''' from os.path import join, abspath, sep import unittest import logging import routesparser from faker import Faker LOG_FILE = join(sep.join(sep.split(abspath(__file__))[:-1]), 'log', 'testing', 'testing.log') class RoutesGetterTests(unittest.TestCase): ...
1,870
603
def parse(o, prefix=""): def flatten(lis): new_lis = [] for item in lis: if isinstance(item, list): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis try: return { "str": lambda: (prefix, o...
961
294
from setuptools import setup VERSION = '0.0.4' DESCRIPTION = 'Hello world checking' # Setting up setup( name="hello_world", version=VERSION, author="Kishan Tongrao", author_email="kishan.tongs@gmail.com", description=DESCRIPTION, long_description_content_type="text/markdown", ...
710
224
import hashlib def str_hash(s): return int(int(hashlib.sha224(s.encode('utf-8')).hexdigest(), 16) % ((1 << 62) - 1))
123
59
# -*- coding:utf-8 -*- import certifi import pycurl import requests import os import json import uuid from StringIO import StringIO def byteify(input_data): # convert json to list if isinstance(input_data, dict): return {byteify(key): byteify(value) for key, value in input_data.iteritems(...
4,354
1,397
# CannyStill.py import cv2 import numpy as np import os ################################################################################################### def main(): imgOriginal = cv2.imread("image.jpg") # open image if imgOriginal is None: # if image was not read ...
1,565
428
""" Timeseries from DataFrame ========================= """ import seaborn as sns sns.set(style="darkgrid") gammas = sns.load_dataset("gammas") sns.tsplot(gammas, "timepoint", "subject", "ROI", "BOLD signal")
212
82
from datetime import date import boundaries boundaries.register('British Columbia electoral districts', domain='British Columbia', last_updated=date(2011, 12, 12), name_func=boundaries.attr('edname'), id_func=boundaries.attr('edabbr'), authority='Elections BC', source_url='http://www.elections...
533
195
import logging import magic import os from cms.medias.utils import get_file_type_size from django.conf import settings from django.core.files.uploadedfile import InMemoryUploadedFile from . import settings as app_settings from . utils import to_webp logger = logging.getLogger(__name__) FILETYPE_IMAGE = getattr(sett...
2,228
674
from django_fsu import url from . import views urlpatterns = [ url('login/', views.login, name='login'), url('logout/', views.logout, name='logout'), url('profile/<int:pk>', views.profile, name='profile'), ]
222
77
""" This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['PocLibrary.py'] APP_NAME = "PocLibrary" DATA_FILES = [] OPTIONS = { 'iconfile': 'logo.icns', 'plist': { 'CFBundleName': APP_NAME, 'CFBundleDisplayName': APP_NAME, ...
747
273
# encoding: utf-8 import base64 import hashlib import hmac import re import six from six.moves.urllib.parse import quote from Crypto.Cipher import AES class Url(object): unsafe_or_hash = r'(?:(?:(?P<unsafe>unsafe)|(?P<hash>[^/]{28,}?))/)?' debug = '(?:(?P<debug>debug)/)?' meta = '(?:(?P<meta>meta)/)?' ...
8,840
2,782
""" Config class for training the InvNet """ import argparse from dp_layer.graph_layer.edge_functions import edge_f_dict as d def get_parser(name): """ :param name: String for Config Name :return: parser """ parser = argparse.ArgumentParser(name, formatter_class=argparse.ArgumentDefaultsHelpFo...
4,420
1,314
# -*- coding: utf-8 -*- """ flask-rst.modules.tags ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from math import log from flask import Blueprint, render_template from jinja2 import Markup from flaskrst.modules.blog import posts d...
1,599
550
# coding: utf-8 from __future__ import print_function, unicode_literals import re import pytest import sqlitefts as fts from sqlitefts import fts5, fts5_aux apsw = pytest.importorskip("apsw") class SimpleTokenizer(fts.Tokenizer): _p = re.compile(r"\w+", re.UNICODE) def tokenize(self, text): for m...
12,560
4,152
#!/usr/bin/python # -*- coding: utf-8 -*- """ генератор случайных чисел """ import random print ''.join([random.choice(list('123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')) for x in range(12)])
211
106
import mxnet as mx from mxnet import nd from mxnet import gluon from mxnet.gluon import nn, rnn from config import config nJoints = config.NETWORK.nJoints class MyLSTM(gluon.Block): def __init__(self, cfg, **kwargs): super(MyLSTM, self).__init__(**kwargs) self.hidden_dim = cfg.NETWORK.hidden_dim ...
1,283
444
from math import ceil, floor def k_multiply(a, b): if len(str(a)) == 1 or len(str(b)) == 1: return int(a)*int(b) n = max(len(str(a)), len(str(b))) al = a // 10**(n//2) ar = a % 10**(n//2) bl = b // 10**(n//2) br = b % 10**(n//2) p1 = k_multiply(al, bl) p2 = k_multiply(ar, br) ...
536
280
import sys def print_lights(lights): x = [x for x,y in lights.keys()] y = [y for x,y in lights.keys()] minx, maxx = min(x), max(x) miny, maxy = min(y), max(y) if maxy - miny < 18: result = [] for y in range(miny, maxy+1): for x in range(minx, maxx+1): re...
1,138
437
import re import random import string import os supported_types = ['a', 'n', 's'] count_types = [] def fuzzyfy(types, length): # check type and length parameters for validity try: int(length) except Exception: return None if types == '' or types == "": return None elif ...
1,850
649
import pytest # This function is based upon the example of how to # "[make] test result information available in fixtures" at: # https://pytest.org/latest/example/simple.html#making-test-result-information-available-in-fixtures # and: # https://github.com/pytest-dev/pytest/issues/288 @pytest.hookimpl(tryfirst=True,...
787
252
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
1,236
362
import arcade arcade.open_window(500,750,"Rainbow") arcade.set_background_color(arcade.color.SKY_BLUE) arcade.start_render() arcade.draw_parabola_filled(25,80,500,300,arcade.color.RED,0) arcade.draw_parabola_filled(50,80,470,280,arcade.color.ORANGE,0) arcade.draw_parabola_filled(75,80,440,260,arcade.color.YELLOW ,0) ar...
615
330
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2019-02-13 18:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('portal', '0016_auto_20190213_1645'), ] operations = [ migrations.RemoveField( ...
403
154
#!/usr/bin/env python ''' simple bottle drop module''' import time mpstate = None hold_pwm = 983 release_pwm = 1776 drop_channel = 5 drop_time = 2.0 class drop_state(object): def __init__(self): self.waiting = False self.start_drop = 0 def name(): '''return module name''' return "drop" ...
1,510
525
import pandas as pd import numpy as np from numpy.random import randn from craft_ai.pandas import MISSING_VALUE, OPTIONAL_VALUE from random import random, randint NB_OPERATIONS = 300 NB_MANY_OPERATIONS = 1000 SIMPLE_AGENT_BOOSTING_CONFIGURATION = { "model_type": "boosting", "context": { "a": {"type": ...
9,232
3,950
import tornado.web from content import PAGES def page_controller(handler_instance, path): if path in PAGES: handler_instance.write(PAGES[path].serialize()) else: handler_instance.set_status(404) handler_instance.write({ 'message': 'A resource was not found for this path.' })
305
99
#!/usr/bin/python3 # Copyright (C) 2020 Sam Steele # 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...
3,767
1,392
# Molecule # # This program takes in a molecular formula and creates a Lewis diagram and a 3D # model of the molecule as the output. # # Author: Ved Pradhan # Since: December 31, 2021 import json import matplotlib.pyplot as plt import sys import math # Opens the JSON file for use. with open("elements.json", "r", enc...
7,470
2,649
from flask import Blueprint from flask import render_template, redirect, url_for, request, session, jsonify from flask_login import login_user, logout_user, current_user from app.transaction import bp from app.transaction.model_att import Attendence, AttendenceSchema , CompanySchema from app.employee.model import Emplo...
9,185
2,567
#!/usr/bin/env python3 """ Usage: python monitor.py randopt_results/simple_example/ """ import sys import os import time import curses import randopt as ro USE_MPL = True USE_CURSES = True try: from terminaltables import AsciiTable, SingleTable except: raise('run pip install terminaltables') try: ...
3,385
1,120
from django.contrib import admin from .models import Post, Comment class PostAdmin(admin.ModelAdmin): list_display = ('author','title','created_date','published_date','image') class CommentAdmin(admin.ModelAdmin): list_display = ('post','author','created_date') admin.site.register(Post,PostAdmin) admin.s...
355
104
import os import ray from ray import tune @ray.remote(num_gpus=1) def use_gpu(): print("ray.get_gpu_ids(): {}".format(ray.get_gpu_ids())) print("CUDA_VISIBLE_DEVICES: {}".format(os.environ["CUDA_VISIBLE_DEVICES"])) if __name__ == "__main__": ray.init() print("ray.get_gpu_ids(): {}".format(ray.get_gpu_ids(...
403
185
#!/usr/bin/env python # # Copyright (C) 2006 Huub van Dam, Science and Technology Facilities Council, # Daresbury Laboratory. # All rights reserved. # # Developed by: Huub van Dam # Science and Technology Facilities Council # Daresbury Laboratory # C...
42,230
13,744
from Methods.utils import rmsd, mde from datetime import datetime import logging import json import sys def os_display_call(test_path, main, data, multistart=False): ( filename, num_atom_init, total_atoms_ord, m, prop_dist, convex, fo_non_scaled, fo_...
6,973
2,373
import unittest import sys import helpers sys.path.append('../LODStats') sys.path.append('../src/restriction-types-stats') from A69DisjointProperties import A69DisjointProperties import lodstats from lodstats import RDFStats testfile_path = helpers.resources_path class TestA69DisjointProperties(unittest.TestCase): ...
1,968
647
from kavenegar import KavenegarAPI, APIException, HTTPException from src.core.settings import OTP_API_KEY def send_sms(phone, message): try: api = KavenegarAPI(OTP_API_KEY) response = api.sms_send({ 'sender': '10008663', 'receptor': phone, 'message': message, ...
449
146
from pytaraxa.test import * blockNumber()
43
17
import random import logging import time from datetime import timedelta from pymavlink import mavutil _log = logging.getLogger(__name__) def now(): return int(round(time.time()*1000)) def random_scaled_imu_test(url: str, pause: timedelta): connection = mavutil.mavlink_connection(url) mav = connection.m...
923
328
''' Created on 2020-09-19 @author: wf ''' import os.path import tempfile import unittest from pathlib import Path from lodstorage.storageconfig import StorageConfig import geograpy import getpass from geograpy.locator import Locator, City,CountryManager, Location, LocationContext from collections import Counter from...
12,548
3,732
# example of automatically starting a thread from time import sleep from threading import Thread # custom thread class that automatically starts threads when they are constructed class AutoStartThread(Thread): # constructor def __init__(self, *args, **kwargs): # call the the parent constructor...
685
187
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2015 Marcel Bollmann <bollmann@linguistics.rub.de> # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including ...
4,332
1,317
from typing import Union import matplotlib.pyplot as plt import torch import torchvision def decode_segmap_to_color_image(masks: torch.Tensor, colormap: Union[list, tuple], num_classes: int, ignore_index: int = None, ...
1,851
708
import os import json import logging import argparse from src.common.translate import translate_time_expression_templates, get_client logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def main(): parser = argparse.Argument...
1,373
426
from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.contrib.auth import get_user_model from .forms import DriverSignupForm, RiderSignupForm from driver.models import Driver User = get_user_model() # Create your views here. def index(request): return ...
1,477
429
from manimlib.imports import * from manim_projects.tony_useful.imports import * class Test2DLissajousFromLinesIntersection(Scene): def construct(self): circle_x = Circle(color=RED).shift(UP * 2.5) circle_y = Circle(color=RED).shift(LEFT * 2.5) theta = ValueTracker(0) point_x = Do...
23,485
9,099
import os import subprocess import sys import time import pkg_resources from satella.coding import silence_excs from satella.coding.sequences import smart_enumerate from satella.files import write_to_file, read_in_file from socatlord.parse_config import parse_etc_socatlord def install_socatlord(verbose: bool = Fals...
3,612
1,251
""" Provide a basic set of endpoints for an application to implement OAuth client functionality. These endpoints assume that the ``current_app`` has already been configured with an OAuth client instance from the ``authlib`` package as follows: .. code-block:: python from authutils.oauth2.client import OAuthClien...
2,303
685
import unittest from flower.utils import bugreport from celery import Celery class BugreportTests(unittest.TestCase): def test_default(self): report = bugreport() self.assertFalse('Unknown Celery version' in report) self.assertTrue('tornado' in report) self.assertTrue('humanize' i...
655
189
"""Methods to generate a SINGLE image to represent any ABF. There are several categories which are grossly analyzed. gain function: * current clamp recording where command traces differ by sweep. * must also have something that looks like an action potential * will be analyzed with AP detection information...
4,124
1,338
from dataclasses import dataclass, field from typing import List, Optional from bindings.csw.abstract_general_operation_parameter_ref_type import ( OperationParameterGroup, ) from bindings.csw.actuate_type import ActuateType from bindings.csw.base_unit import BaseUnit from bindings.csw.cartesian_cs import Cartesian...
24,671
7,264
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .package import txt2epub as txt2epub from .package import txt2pdf as txt2pdf import argparse __version__ = "0.1.0" def epub(): parser = argparse.ArgumentParser( prog='txt2epub.exe', description='テキストを電子書籍(epub)化する' ) metadata = parser2m...
2,468
959
from .Scripts import *
22
7
import os import shutil import unittest import bpy from mmd_tools.core import pmx from mmd_tools.core.model import Model TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) SAMPLES_DIR = os.path.join(os.path.dirname(TESTS_DIR), 'samples') class TestFileIoOperators(unittest.TestCase): @classmethod def se...
3,150
965
""" Module for gocdapi Stage class """ from gocdapi.gobase import GoBase class Stage(GoBase): """ Class to hold Go Server Stage information """ def __init__(self, go_server, pipeline, data): """Inits Stage objects. Args: go_server (Go): A Go object which this Stage belon...
1,939
540
import pyaf.tests.exog.test_random_exogenous as testrandexog testrandexog.test_random_exogenous( 32,20);
106
45
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo (pesquisar o princípio matemático que explica a formação de um triangulo). r1 = float(input('Informe o comprimento da primeira reta: ')) r2 = float(input('Informe o comprimento da segunda reta: ')) ...
602
236
from functools import partial from typing import Dict import copy from torch.nn import Module from torchvision.models.resnet import * from .ssd_resnet import SSD300_ResNet from .ssd_vgg import SSD300_VGG16 from .backbones import * __REGISTERED_MODELS__ = { "SSD300_ResNet": SSD300_ResNet, "SSD3...
1,070
427
inp = input("Enter string: ") input_string = ord(inp) print(input_string)
75
29
def no_bool_bubble_sort(unsorted_list): for y in range(1, len(unsorted_list) - 1): for x in range(len(unsorted_list) - y): try: value = \ (((unsorted_list[x] - unsorted_list[x + 1]) // abs( unsorted_list[x + 1] - unsorted_list[x])) + 1)...
533
181
# https://www.codewars.com/kata/5536a85b6ed4ee5a78000035 import math def tour(friends, friend_towns, home_to_town_distances): arr = [] for a in friends: for b in friend_towns: if a in b: arr.append(home_to_town_distances[b[-1]]) dist = arr[0] + arr[-1] i = 1 whi...
430
180
import numpy as np from numba import njit from ._api import * # noqa: F403 from .handle import mkl_h __all__ = [ 'mult_ab', 'mult_abt' ] @njit(nogil=True) def mult_ab(a_h, b_h): if a_h.H and b_h.H: h = lk_mkl_spmab(a_h.H, b_h.H) else: h = 0 return mkl_h(h, a_h.nrows, b_h.ncols, ...
733
398
# Copyright (C) 2021, A10 Networks Inc. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
4,088
1,191
from engine.gameobject import Gameobject objects = [] def create(obj: Gameobject): objects.append(obj) obj.start() def delete(obj: Gameobject): for child in obj.children: delete(child) obj.end() objects.remove(obj) def find(typ): for o in objects: if isinstance(o, typ): return o
310
106
input1str = 'R998,U367,R735,U926,R23,U457,R262,D473,L353,U242,L930,U895,R321,U683,L333,U623,R105,D527,R437,D473,L100,D251,L958,U384,R655,U543,L704,D759,R529,D176,R835,U797,R453,D650,L801,U437,L468,D841,R928,D747,L803,U677,R942,D851,R265,D684,L206,U763,L566,U774,L517,U337,L86,D585,R212,U656,L799,D953,L24,U388,L465,U656,...
4,912
3,744
from django.db import models from django.utils import timezone from django.core.validators import MaxValueValidator, MinValueValidator from django.core.urlresolvers import reverse from django.conf import settings # # # # # # # # # # # # # # # # # # # # # # # # # # # # Level 0: base abstract and infrastructure classes...
13,757
4,252
import os import boto3 from getpass import getpass from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), ".env") load_dotenv(dotenv_path) client = boto3.client("cognito-idp", region_name=os.getenv("REGION_NAME")) username = input("[*] Enter Your Email Address: ") password = getpass("[*]...
953
297
from rest_framework import serializers from .models import VirtualNetwork class NetworkSerializer(serializers.ModelSerializer): # specify model and fields class Meta: model = VirtualNetwork exclude = ['id', 'deactivated', 'account']
259
61