text
string
size
int64
token_count
int64
import re from pathlib import PurePosixPath from typing import TYPE_CHECKING, Optional, Type from lisa.executable import Tool from lisa.tools.ls import Ls from lisa.tools.mkdir import Mkdir from lisa.tools.powershell import PowerShell from lisa.tools.rm import Rm from lisa.util import LisaException, is_valid_url if T...
4,781
1,403
# Load other business attributes and set meta prefix from pandas.io.json import json_normalize flat_cafes = json_normalize(data["businesses"], sep="_", record_path="categories", meta=['name', 'alias', ...
1,787
526
import sys infn = sys.argv[1] outfn = infn.split(".py")[0]+"_INST.py" code = [] for l in open(infn): code.append(l) outf = open(outfn, 'w') outf.write("import covertool\n") ln = 0 inComment = False justEnded = False currentIndent = 0 lineIndent = 0 okChangeIndent = False skipNext = False doNotInstrument = ["cl...
2,310
831
import json import os import sys import time try: from urlparse import urlparse except ImportError: # python3 from urllib.parse import urlparse from django.conf.urls import url from django.conf.urls.static import static from django.http import HttpResponse, Http404 from django.shortcuts import render_to_re...
8,729
2,880
import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, RisingEdge, FallingEdge, NextTimeStep, ReadWrite N = 16 test_input = list(range(N)) async def writer(dut): for i in test_input: busy_check = lambda : not dut.ready_for_input.value while busy_check(): ...
1,528
558
from django.shortcuts import render, redirect from notes.app.forms import ProfileForm, NoteForm, NoteDeleteForm from notes.app.models import Profile, Note def home(request): if request.method == 'GET': profile = Profile.objects.first() if not profile: form = ProfileForm() ...
2,314
672
# -*- coding: utf-8 -*- """ Created on Tue Jul 2 00:56:18 2019 @author: tang """ seed=102 vocab="vocab.bin" train_file="train.bin" dropout=0.3 hidden_size=256 embed_size=100 action_embed_size=100 field_embed_size=32 type_embed_size=32 lr_decay=0.5 beam_size=5 patience=2 lstm='lstm' col_att='affine' model_name='wiki' ...
3,066
1,315
import unittest from django.test import Client class AnnotationDataModelTests(unittest.TestCase): api_url_template = "/api/v1/heritages/#/annotations" xpath_annotation_response = "" heritage_path = "" api_url_set = "" @classmethod def setUpClass(cls): cls.heritage_path = "/api/v1/heri...
3,476
1,075
import unittest from unittest.mock import patch from jc_decrypter.main import process, main class TestMainProcess(unittest.TestCase): @patch("jc_decrypter.main.decrypter") def test_arg_decrypter(self, mk_decrypter): process(["--token", "1234567890"]) mk_decrypter.assert_called_once_with("123...
824
287
import mock def test_setup(ioexpander): from mics6814 import MICS6814 mics6814 = MICS6814() mics6814._ioe.set_pwm_period.assert_called_once_with(5100) mics6814._ioe.set_mode.assert_has_calls(( mock.call(3, ioexpander.PWM), mock.call(7, ioexpander.PWM), mock.call(2, ioexpander...
615
276
import datetime from template_maker.database import db from template_maker.generator.models import DocumentBase, DocumentPlaceholder from template_maker.builder.models import TemplateBase, TemplatePlaceholders from template_maker.data.placeholders import get_template_placeholders def get_all_documents(): ''' R...
3,290
908
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from .config import settings SQLALCHEMY_DATABASE_URL = 'postgresql://{user}:{password}@{host}:{port}/{db}'.format( user=settings.DB_USER, password=settings.DB_PASSWORD, hos...
1,194
387
import scrapy from scrapy.selector import Selector from katph.items import StackItem class katphSpider(scrapy.Spider): name = "stackoverflow" allowed_domains = ["stackoverflow.com"] start_urls = [ "%s/questions?pagesize=50&sort=newest" % "http://stackoverflow.com", ] def parse(self, respo...
716
208
# Generated by Django 4.0.1 on 2022-02-07 17:53 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name...
1,156
352
import numpy as np from walkers import ScalableWalker DEFAULT_SCENE = "scenes/walker.ttt" DEFAULT_WALKER = ScalableWalker N_MRPH_PARAMS = [3, 3, 6] N_CTRL_PARAMS = [4, 8, 8] MORPHOLOGY_BOUNDS = [ [[0.7] * 3, [1.4] * 3], [[0.7] * 3, [1.4] * 3], [[0.7] * 6, [1.4] * 6] ] CONTROLLER_BOUNDS = [ [[1, -np...
501
317
from solid import * from solid.utils import * import util from util import inch_to_mm, tube, ABIT, corners, pipe from fixings import M3 from math import tan, radians """ Sub-miniature analog joy-sticks. There's not much useful in documentation of their measurements. I'm going to treat it like a sphere with a 14mm ...
1,284
485
from typing import List from collections import deque class Line: """ Properties: start_x {0} start_y {1} end_x {2} end_y {3} dots = [dot1, ..., dotN] {4} coords = (start_x, start_y, end_x, end_y) """ def __init__(self, start_x=None, start_y=Non...
2,360
880
from hw_asr.model.baseline_model import BaselineModel, BasicLSTM, BasicGRU from hw_asr.model.QuartzNet import QuartzNet __all__ = [ "BaselineModel", "BasicLSTM", "BasicGRU", "QuartzNet" ]
205
85
'''********************************************** CODE TO IMPLEMENT FISHER'S LDA - Given two dimensional dataset with two classes 0 and 1, Perform Fisher's LDA on the dataset, Perform dimensionality reduction and find the suitable vector to project it onto, Find the threshold value for separation of the two classes **...
4,458
1,675
import matplotlib.pyplot as plt import torch n_input = 1 # n_hidden should be very big to make dropout's effect more clear n_hidden = 100 n_output = 1 EPOCH = 1000 LR = 0.01 torch.manual_seed(1) # reproducible N_SAMPLES = 20 # training data x = torch.unsqueeze(torch.linspace(-1, 1, N_SAMPLES), 1) y = x + 0.3 * torc...
3,071
1,317
""" Twiss module. Compute twiss parameters from amplitude & phase data. Twiss filtering & processing. """ import numpy import torch import pandas from scipy import odr from .util import mod, generate_pairs, generate_other from .statistics import weighted_mean, weighted_variance from .statistics import median, biwei...
72,649
26,210
def escape_assertion(s): """escapes the dots in the assertion, because the expression evaluation doesn't support such variable names.""" s = s.replace("r.", "r_") s = s.replace("p.", "p_") return s def remove_comments(s): """removes the comments starting with # in the text.""" pos = s.find(...
879
293
from multiobj_rationale.fuseprop.mol_graph import MolGraph from multiobj_rationale.fuseprop.vocab import common_atom_vocab from multiobj_rationale.fuseprop.gnn import AtomVGNN from multiobj_rationale.fuseprop.dataset import * from multiobj_rationale.fuseprop.chemutils import find_clusters, random_subgraph, extract_subg...
399
142
import time import datetime from thespian.test import * from thespian.actors import * from thespian.troupe import troupe max_listen_wait = datetime.timedelta(seconds=4) max_ask_wait = datetime.timedelta(seconds=2.5) class Bee(Actor): def receiveMessage(self, msg, sender): if isinstance(msg, tuple): ...
5,445
1,882
from AMPS import Client import random import time import json import sys def main(*args): publish_rate = None # publish as fast as possible by default try: publish_rate = int(args[0]) start = int(args[1]) end = int(args[2]) except Exception: pass # set up the client ...
1,197
373
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime class PlatformApplication(pulumi.CustomResource): """ Provides an SNS platform application...
8,299
2,187
# coding : utf-8 # created by wyj import numpy as np import pandas as pd import math from utils.feature_utils import df_empty # TERMINALNO,TIME,TRIP_ID,LONGITUDE,LATITUDE,DIRECTION,HEIGHT,SPEED,CALLSTATE,Y # 对传入的表按trip_id分组,取每组的海拔的最大连续子数组,对每个人的所有行程的子数组取最大,平均, 方差。 # def max_sub(arr): # sum = 0 # height = -999 ...
4,815
1,970
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import json import windows_utilman import pyAesCrypt import requests from secureCrypt import cryptResult os.system('loadkeys fr') os.system('lsblk > result.txt') if os.path.exists('/mnt/targetDrive'): pass else: os.system('mkdir /mnt/targetDrive') ...
2,850
886
from app import app import os from flask import abort, \ redirect, \ render_template, \ request, \ send_from_directory, \ url_for from .helpers import generate_code, \ is_valid_url, \ is_aut...
2,336
701
# -*- coding: utf-8 -*- from __future__ import unicode_literals import xadmin from django.contrib import admin # from typeidea.custom_site import custom_site from typeidea.custom_admin import BaseOwnerAdmin from .models import Comment # Register your models here. class CommentAdmin(object): list_display = ['ta...
561
170
from .devices import data_parallel, empty_cache, find, move_to_device, CPU, GPU
79
25
from tqdm import tqdm import shutil import os from PIL import Image import warnings src_folder = '../../modified_datasets/cars_flat' dest_folder = '../../modified_datasets/cars_flat_ratio_warnings' if not os.path.exists(dest_folder): os.makedirs(dest_folder) num_kept = 0 num_removed = 0 num_corrupt_EXIF = 0 for...
1,443
463
from mongoengine.queryset.visitor import Q from backend.apps.posts.models import Post from backend.apps.user.signals import check_comment_signal from backend.apps.user.utils import are_friends def _get_two_last_obj_with_path(path_list): size = len(path_list) if not size: raise Exception("path_list ca...
2,548
875
from globus_cli.parsing import group from .list import list_command from .show import show_command @group("timer") def timer_command(): """Schedule and manage jobs in Globus Timer""" timer_command.add_command(list_command) timer_command.add_command(show_command)
272
86
from typing import Any, Dict, List from ....models.models import Projection, Projector from ....permissions.permissions import Permissions from ....shared.filters import And, FilterOperator from ....shared.patterns import Collection, FullQualifiedId, string_to_fqid from ....shared.schema import required_id_schema from...
5,340
1,365
""" sfftk-migrate ============== This is a simple tool to allow users to easily migrate older versions of EMDB-SFF files to the latest (supported version). It has only one dependency: `lxml` which effects part of the migrations. Presently it only works with XML (.sff) EMDB-SFF files. How does it work? --------------...
3,235
1,093
from sys import stdin as s n, k = map(int, s.readline().split()) tree = [0] * 400005 def init(node, s, e): if s == e: tree[node] = 1 return tree[node] mid = (s + e) >> 1 tree[node] = init(2 * node, s, mid) + init(2 * node + 1, mid + 1, e) return tree[node] def query(node, s, e, k)...
802
360
from os import listdir, path def traverse_dir(current_path, files_by_ext): for el in listdir(current_path): if path.isdir(path.join(current_path, el)): traverse_dir(path.join(current_path, el), files_by_ext) else: extension = el.split(".")[-1] if extension not i...
609
203
from rest_framework import serializers from api.models import Letter class LetterSerializer(serializers.ModelSerializer): class Meta: model = Letter fields = ('id', 'subject', 'body', 'created', 'modified', 'sender', 'receiver', 'remarks')
263
74
from django.contrib import admin from .models import Application, ApplicationGroup, ApplicationPeriod class ApplicationAdmin(admin.ModelAdmin): list_display = [ '__str__', ] admin.site.register(Application, ApplicationAdmin) admin.site.register(ApplicationGroup, ApplicationAdmin) admin.site.register(A...
356
87
import ntpath import os from flink_rest_client.common import _execute_rest_request, RestException class JarsClient: def __init__(self, prefix): """ Constructor. Parameters ---------- prefix: str REST API url prefix. It must contain the host, port pair. ...
7,237
1,902
# -*- coding: utf-8 -*- import string from charguana import get_charset punctuations = set(list(string.punctuation) + list(get_charset('Currency_Symbol')) + list(get_charset('Close_Punctuation')) + list(get_charset('Open_Punctuation')) + list(get_cha...
112,962
73,266
from turtle import * from random import * # from random import * def move(x, y): penup() goto(x, y) pendown() def fillpolygon(side, count, color1, color2): pencolor(color2) fillcolor(color1) begin_fill() for i in range(count): forward(side) left(360 / count...
2,320
1,042
from iec_lookup.services.iec_lookup_service import IECLookupService from iec_lookup.tests.fixtures import mongo_test_db_setup, importer_exporter_code_details_as_json, importer_exporter_code_details_as_object, dgft_succes_response_html_string, dgft_error_response_html_string, iec_table_section_list, basic_iec_details_as...
7,156
2,509
"""HTTP Router tests.""" import inspect import typing as t from re import compile as re import pytest @pytest.fixture def router(): from http_router import Router, NotFound, MethodNotAllowed, RouterError # noqa return Router() def test_router_basic(router): assert router assert not router.trim_l...
9,713
3,157
from pathlib import Path import pytest import scrapli from scrapli.channel import Channel from scrapli.transport import Transport from ...test_data.unit_test_cases import TEST_CASES TEST_DATA_DIR = f"{Path(scrapli.__file__).parents[1]}/tests/test_data" def test_init(sync_generic_driver_conn): """Test that all...
4,072
1,360
import datetime from . import create_timesheet def test_regroup_doesnt_regroup_entries_with_different_alias(): contents = """01.04.2013 foo 2 bar bar 2 bar""" t = create_timesheet(contents) entries = list(t.entries.filter(regroup=True).values())[0] assert len(entries) == 2 def test_regroup_doesnt_...
2,301
920
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ import asyncio import logging import struct log = logging.getLogger(__name__) class TcpClientProtocol(asyncio.Protocol): def __init__(self, master): self.master = master def connection_made(self, transport): self.transport = transport ...
5,192
1,693
# -*- coding: utf-8 -*- import mysql.connector import pandas as pd import sys #tablename = str(sys.argv[1]) csvname = "result1232.csv" #総得点を出したいチーム名 target = str(sys.argv[1]) # 接続する conn = mysql.connector.connect( host="localhost", database="toto", user="root", password="root" ) print("connection:...
721
292
import unittest from leanai.core.annotations import RunOnlyOnce class TestAnnotations(unittest.TestCase): def setUp(self) -> None: self.var = 0 def runner(self): return self.var @RunOnlyOnce def run_once(self): return self.var def test_output(self): self.var = 1 ...
629
216
import sys pyversion = sys.version_info if sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] < 7): raise Exception("Professor2 requires Python 2.7 or greater") ## Import Cython wrappings on the C++ core library from professor2.core import * __version__ = version() from professor2.errors...
1,971
688
import boto3 reko = boto3.client('rekognition') s3 = boto3.client('s3') def lambda_handler(event, context): job_id = event['job_id'] reko_client = boto3.client('rekognition') response = reko_client.get_face_detection(JobId=job_id, MaxResults=100) return { "statusCode": 200, "body": ...
558
196
#!/usr/bin/env python import time from pylegos.core import Thread def worker(sleepSec): time.sleep(sleepSec) t = Thread() t.runAndWait(threadName='test', runFunc=worker(10)) print('finished')
201
73
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE from hazelcast.protocol.codec.custom.raft_group_id_codec import RaftGroupIdCodec from hazel...
1,314
506
# Array; Two Pointers # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional ele...
980
373
from unittest import TestCase from .. import capture_buffer as capt_buff from tempfile import mkdtemp import os class TestCaptureBuffer(TestCase): def test_capture_buffer(self): """ Test that the files are written out for instantiation and testbench. :return: """ tmpdir = ...
1,007
314
# coding=utf-8 import mysql.connector import xlsxwriter from query import q, table,columns from letters import letters import string import json import os dir_path = os.path.dirname(os.path.realpath(__file__)) with open(dir_path + '/config.json', "r") as json_data_file: conf = json.load(json_data_file) conn = my...
933
361
from setuptools import setup import os import sys import json sys.path.append("radio_sim") def package_files(package_dir, subdirectory): # walk the input package_dir/subdirectory # return a package_data list paths = [] directory = os.path.join(package_dir, subdirectory) for (path, directories, f...
1,317
450
import asyncio import logging import sys import coloredlogs import signal from oremda.typing import ContainerType from oremda.clients.singularity import SingularityClient from oremda.pipeline.engine.rpc.client import RpcClient from oremda.pipeline.engine.context import pipeline_context from oremda.pipeline.engine.conf...
1,959
639
from pynput import keyboard from pynput.keyboard import Key, Controller from os.path import exists import win32clipboard import os from PIL import Image from pystray import Icon as icon, Menu, MenuItem as item import pystray RECORDING = False WORD = "" keyboard_press = Controller() def send_to_clipboard(...
2,369
782
# File: moloch_connector.py # # Copyright (c) 2019-2022 Splunk 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 a...
27,986
7,879
from flask import * from flask_csp.csp import csp_header, csp_default import imghdr import os import hashlib import subprocess app = Flask(__name__) app.config["UPLOAD_DIRECTORY"] = 'uploads' app.config["ALLOWED_EXTENSIONS"] = ["jpg", "jpeg", "png", "gif"] # Remove report-uri from default CSP header h = csp_default(...
2,600
824
import os import cv2 import json import time import shutil import argparse import numpy as np import PIL.Image from copy import deepcopy import mmcv from mmdet.apis import init_detector, inference_detector, show_result # install mmdet v1 in https://github.com/open-mmlab/mmdetection # download correspongdi...
8,767
3,391
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-29 23:11 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0001_initial'), ] operations = [ migrations.RenameField( mode...
563
189
import numpy as np import scipy.linalg as la from auxiliary import * a = np.matrix([ [+0.35, +0.45, -0.14, -0.17], [+0.09, +0.07, -0.54, +0.35], [-0.44, -0.33, -0.03, +0.17], [+0.25, -0.32, -0.13, +0.11], ], dtype=float) w, vl, vr = la.eig(a, left=True, right=True) vprintC('w', w) print for i in ran...
415
234
import pygame from pygame.locals import * from util import * from constants import FPS, VERSION, SCREEN_WIDTH, SCREEN_HEIGHT from ui.button import * from ui.font import * from media.paths import bg, logo, body_font, title_font class Main: def __init__(self): """ It's the abstract class for all sc...
9,969
2,917
import requests import json import os from bs4 import BeautifulSoup as bs import random import time import base64 import m3u8 treinaweb_sessions = requests.Session() class Downloader(): def index(self): escolha = input('Qual plataforma voce deseja baixar?\n1 - TreinaWeb\n2 - AvMakers\n3 - Freelae\nRe...
15,155
4,962
import gmpy2 import itertools import subprocess import math import time from collections import defaultdict from factordb.factordb import FactorDB START = 2 STOP = 5000 # Also see A056938 def product(factors): temp = 1 for factor in factors: temp *= factor return temp def factordb_format(number): ...
10,724
3,801
#Samuel Jero <sjero@purdue.edu> #vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import os import sys import time from datetime import datetime import re import pprint from types import NoneType import ast import manipulations import fields system_home = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0...
14,541
4,440
#!coding:utf-8 import os import sys import pymysql def connetc2mysql(): try: conn = pymysql.connect( host = '10.15.50.100', port = 3306, user= 'root', password = 'Zhaolab@C809!!', db = 'CORdbPro', charset = 'utf8', use_unicode=True) except Exception as e: print(e) else: print("connect s...
1,212
537
#!/usr/bin/env python # # Copyright 2019 Rickard Armiento # # This file is part of a Python candidate reference implementation of # the optimade API [https://www.optimade.org/] # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "...
2,478
796
import os import argparse import cv2 import numpy as np import tensorflow as tf from nart import opr, aopr from nart.model import VGG16 from nart.logconf import logger LEARNING_RATE = 1.5 JITTER = 32 as_netin = lambda x: x[np.newaxis, :] def make_step(sess, net, end): ''' iter only one step, providing end ''' ...
2,609
934
import re text = '' with open('5input1.txt', 'r') as ifile: text = ifile.read().strip() def find_length(text): text = list(text) t0 = '' t1 = '' restart = True while (restart): restart = False loop = len(text) - 1 i = 0 # print(text) while (i < loop): ...
1,079
383
from board import Node from metrics import * parent = Node(None, np.zeros((5,5)), 1) parent.nb_free_three = 0 def test_node1(): g = np.array([ [1, -1, -1], [1, -1, -1], [1, 1, 0] ]) n = Node(parent, g, BLACK) next_mv = n.generate_next_moves() assert (next_mv[0].grid ...
2,903
1,394
""" 08-function-calls.py - Using custom algorithms with python function calls. **EventCall** :: EventCall(function, *args, occurrences=inf, stopEventsWhenDone=True) EventCall calls a function, with any number of arguments (\*args) and uses its return value for the given parameter. The example below use a functio...
1,122
377
import requests import json import pandas as pd from datetime import datetime def GetEpidemicWeek(curr_date): ''' Parameters ---------- curr_date: (str) Date in yyyy-mm-dd Return ------ (int) Week number of year ''' _aux = datetime.strptime(curr_date, '%Y-%m-%d') return _aux.is...
1,824
605
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' print ('Task1') for i in range(5): i+=1 print(i,'00000') ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' print ('Task2') count=0 for i in range(10):...
2,048
883
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'aboutdialog.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, ...
1,836
623
import requests import datetime from db import convert_code from pycountry_convert import country_name_to_country_alpha2 from pprint import pprint import json url = r'https://pomber.github.io/covid19/timeseries.json' response = requests.get(url) if response.status_code != 200: print("Failed to connect to pomber") ...
5,351
1,715
import datetime from functools import total_ordering from typing import Tuple, Any, Dict, Optional from . import change_index @total_ordering class ParsedRow(object): def __init__(self, table_fq_name: str, row_kind: str, operation_name: str, event_db_time: datetime.datetime, change_idx: Optional...
2,398
735
import pandas as pd def read_xyz(filename): # try: df = pd.read_csv(filename, sep="\t", header=None) if df.shape[1] == 1: df = pd.read_csv(filename, sep=" ", header=None) ncol = df.shape[1] names = ["x", "y", "z", "name"] df.columns = names[0:ncol] return df def dataframe_to_...
446
176
import pytest def pytest_addoption(parser): parser.addoption("--include_performance_tests", action="store_true", help="Will run the performance tests which do full model testing. This could take a few" "days to fully accomplish.") @pytest.fixture() def include_pe...
646
174
from robomaster import robot import time ep_robot = robot.Robot() xy_speed = 1/2 # m/s z_speed = 90/2 # m/s if __name__ == '__main__': #ep_robot.initialize(conn_type="sta", sn="3JKDH6U0011J02") ep_robot.initialize(conn_type="ap") ep_chassis = ep_robot.chassis for i in range(4): # 1 Meter...
534
240
def setup (): size (500, 500) smooth () background (255) noStroke () colorMode(HSB) flug = bool(True) i=0 j=0 def draw (): global i, j, flug if(flug): for i in range (10): for j in range (5): fill (10, random (0, 255) , random (10, 250)) re...
447
200
#!/usr/bin/env python ########## import web from handlers.front import FrontPage from handlers.home import HomePage ########## urls = ('/home', 'HomePage', '/', 'FrontPage') app = web.application(urls, globals()) ########## if __name__ == "__main__": app.run()
280
92
import ass import subdigest import subprocess import os def dump_subs(subsfile: str, subsdata: subdigest.Subtitles): """ Exports subsdata to subsfile manually over using dump_file() to avoid the utf-8 encode warning. """ with open(subsfile, "w", encoding="utf_8_sig") as f: for section in subsd...
3,758
1,310
import logging from tbot.twitch_bot.var_filler import fills_vars, Send_error from tbot import config @fills_vars('faceit.username', 'faceit.elo', 'faceit.level', 'faceit.next_level_points', 'faceit.next_level') async def faceit_elo(bot, channel, args, var_args, **kwargs): if not var_args or \ not 'fac...
1,955
689
import setuptools with open('README.md', 'r', encoding='utf-8') as fh: long_description = fh.read() setuptools.setup( name='BaiduSpider', version='0.0.6', author='Sam Zhang', author_email='samzhang951@outlook.com', description='BaiduSpider,一个爬取百度的利器', long_description=long_description, ...
740
271
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : reward.py # @Author: zixiao # @Date : 2019-03-28 # @Desc : def get_reward(info, last_info): re = info['coins'] - last_info['coins'] + info['time'] - last_info['time'] + ( info['lives'] - last_info['lives']) * 10 + info['score'] - last_info['sc...
411
175
# Given two strings a and b, return true if you can swap two letters in a so the result is equal to b, otherwise, return false. # Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at a[i] and b[j]. For example, swapping at indices 0 and 2 in "abcd" resul...
1,270
389
print("NOOP")
14
7
import cloudmesh print cloudmesh.shell("cloud list")
54
18
from .constants import ( ROBOTHOR_ORIGINAL_CLASS_LIST ) import re import os import json import networkx import h5py import numpy as np scene_types = ['FloorPlan_Train1', 'FloorPlan_Train2', 'FloorPlan_Train3', 'FloorPlan_Train4', 'FloorPlan_Train5', 'FloorPlan_Train6', 'FloorPlan_Trai...
3,583
1,241
import pyqrcode from pyqrcode import QRCode # String which represent the QR code s = "https://www.youtube.com/channel/UCeO9hPCfRzqb2yTuAn713Mg" # Generate QR code url = pyqrcode.create(s) # Create and save the png file naming "myqr.png" url.svg("myyoutube.svg", scale = 8)
288
124
import pytest import packerlicious.post_processor as post_processor class TestDockerImportPostProcessor(object): def test_required_fields_missing(self): b = post_processor.DockerImport() with pytest.raises(ValueError) as excinfo: b.to_dict() assert 'required' in str(excinfo....
979
305
'''Module main''' import json import os from rabbitmq import RabbitMQ from pika import exceptions from parameter import Parameter from send_grid import SendGrid from traceability import Traceability from transform import Transform import uuid class App: '''class Application''' @classmethod def __init__(cl...
3,017
793
class_name = 'organizations_tab' from qtpy import QtCore, QtGui, QtWidgets, uic import os from logzero import logger import pathlib import json from modules.sumologic_orgs import SumoLogic_Orgs class CreateOrUpdateOrgDialog(QtWidgets.QDialog): def __init__(self, deployments, org_details=None, trials_enabled=Fals...
26,488
7,798
#Code # python code # script_name: hello # # author: Siddharth # description: composition # # set up from earsketch import * # Initialized init() setTempo(120) # varible chord = RD_UK_HOUSE__5THCHORD_2 secondarybeat = HIPHOP_BASSSUB_001 mainbeat = HOUSE_MAIN_BEAT_003 # Music fitMedia(chord, 1, 1, 16) se...
562
297
import codecs import os codecs.register_error('none', lambda e: ('?', e.end)) def utf8_to_sjis(files, in_dir, out_dir): os.makedirs(out_dir, exist_ok=True) for f in files: utf8_to_sjis_one(f, in_dir, out_dir) def utf8_to_sjis_one(file, in_dir, out_dir): with open(f'{in_dir}/{file}', mode='r', encoding='ut...
575
282
from django.apps import AppConfig from mavweb.mavlink_arbiter.main import Main class ServerConfig(AppConfig): """ Django Server configurations. """ name = 'server' class MavlinkArbiter(AppConfig): """ Mavlink arbiter used for application pairing with mavlink functions. """ name = 'ma...
363
117