text
string
size
int64
token_count
int64
from abc import ABC from typing import List, Type from reamber.base.lists.notes.NoteList import NoteList class BMSNoteList(NoteList, ABC): def data(self) -> List[Type]: pass def samples(self) -> List[float]: return self.attribute('sample')
261
81
import os import sys import re import json import logging ###from pylons import request, response, session, app_globals, tmpl_context, url as c, config from pylons import request, response, session, app_globals, tmpl_context as c, config, url from pylons.controllers.util import abort, redirect from pylons.decorators ...
25,785
8,096
import flair import numpy as np import spacy import tensorflow_hub as hub import torch from flair.data import Sentence from flair.models import SequenceTagger from nltk.tokenize.treebank import TreebankWordDetokenizer from sklearn.metrics.pairwise import cosine_similarity from string import punctuation from transformer...
5,305
1,962
# Insert Interval class Solution: def insert(self, intervals, newInterval): ans = [] [nst, nen] = newInterval for index, [st, en] in enumerate(intervals): if en < nst: ans.append(intervals[index]) elif nen < st: # can return now ...
765
249
# encoding: UTF-8 """" 基于布林带的交易策略 观察周期:1min 策略周期:5min 策略逻辑: 1. 信号:突破上轨、下轨 2. 过滤:均线多头、空头排列 3. 出场:分级止盈;固定止损 """ import talib import numpy as np from cyvn.trader.vtObject import VtBarData from cyvn.trader.vtConstant import EMPTY_STRING from cyvn.trader.app.ctaStrategy.ctaTemplate import CtaTemplate, BarGenerator, Arr...
25,595
9,083
# -*- coding: utf-8 -*- import os import re from selenium import webdriver from xvfbwrapper import Xvfb from cabu.exceptions import DriverException from cabu.utils.headers import Headers from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium import webdriver try: from urllib....
4,577
1,392
import pygame as pg display = pg.display.set_mode((900,600)) clock = pg.time.Clock() jump = 10 step = 0 img = 0 left = [pg.image.load('images/character/l1.png'),pg.image.load('images/character/l2.png'),pg.image.load('images/character/l3.png'),pg.image.load('images/character/l4.png'),pg.image.load('images/character/l5.p...
3,256
1,254
#!/usr/bin/env python3 import picamera import file_utils import os class PiCam: """ Uses Raspberry Pi camera. http://picamera.readthedocs.org/en/release-1.9/api.html """ def __init__(self): self.camera = picamera.PiCamera() """ PiCamera properties default values camera....
1,721
561
_base_ = [ '../_base_/models/flownets.py', '../_base_/datasets/flyingchairs_384x448.py', '../_base_/schedules/schedule_s_long.py', '../_base_/default_runtime.py' ]
176
84
from CalibTracker.SiStripCommon.shallowTree_test_template import * process.TFileService.fileName = 'test_shallowRechitClustersProducer.root' process.load('RecoTracker.TrackProducer.TrackRefitters_cff') process.load('CalibTracker.SiStripCommon.ShallowRechitClustersProducer_cfi') process.testTree = cms.EDAnalyzer( "S...
559
209
from typing import Sequence import numpy as np import h5py from easistrain.EDD.io import ( create_info_group, peak_dataset_data, save_fit_data, ) from easistrain.EDD.utils import fit_detector_data, run_from_cli def fitEDD( fileRead: str, fileSave: str, sample: str, dataset: str, scanNu...
10,468
3,032
from sys import argv script, filename = argv print "We are going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print ...
2,082
765
# Generated by Django 2.0.6 on 2018-11-01 14:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='verify_code', fie...
408
134
from django.test import TestCase from filler.plain_classes.teams_data import TeamsData class TestTeamsData(TestCase): def test_participants_none(self): with self.assertRaises(AssertionError): TeamsData(participants=None, actions=['Action'], dates=['Date']) def test_actions_none(self): ...
599
181
from dungeon_model import Monsters, Players import re import math def initiative_sort(init_order): """sorts all the characters for a given combat by initiative""" print("passed into sort function: ", init_order) for i in range(len(init_order)): check = init_order[i] print("the check is: ",...
2,784
866
def infoGAN_encoder(params,is_training): is_training = tf.constant(is_training, dtype=tf.bool) def encoder(x): with tf.variable_scope('model/encoder',['x'], reuse=tf.AUTO_REUSE): net = lrelu(conv2d(x, 64, 4, 4, 2, 2, name='conv1', use_sn=True)) net = conv2d(net, 128, 4, 4, 2...
2,306
861
# administrative username and password for development ADMIN_USERNAME = 'admin' ADMIN_PASSWORD = 'password' ADMIN_TYPE = 'admin' # for production # ADMIN_USERNAME = 'environ.get('ADMIN_USERNAME') # ADMIN_PASSWORD = 'environ.get('ADMIN_PASSWORD') # ADMIN_TYPE = 'environ.get('ADMIN_TYPE')
288
97
from agents.agent import Agent from models.actor_critic_mlp import ActorCriticMLP import numpy as np import torch import torch.optim as optim from utils import plot_grad_flow class A2C(Agent): def __init__( self, state_size, action_size, hidden_size, memory, lr, ...
2,344
743
from common import google_cloud class GANTrainParameters(): def __init__(self): self.num_epochs = 2000 self.batch_size = 10000 self.num_steps = 1 self.lr_d = 0.01 self.lr_g = 0.001 if not google_cloud: self.batch_size = 1 training_param = GANTrainPara...
329
124
#!/usr/bin/env python # -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen, based on code from Ross Girshick # -------------------------------------------------------- """ Demo script showing detections...
8,672
3,212
# pylint:disable=too-many-lines import os import time from faker import Faker from unittest.mock import patch import pytest from hestia.internal_services import InternalServices from rest_framework import status import conf import stores from api.experiments import queries from api.experiments.serializers import (...
107,563
33,015
import pygame import speech_recognition as sr from time import sleep import events import objects as obj_types from settings import SPEECH_CRED_FILE from speech_helpers import correct_text, either_side, get_after, get_position, get_positions, get_size, is_in_objects, process_relative, select_obj_type # A variable lis...
6,705
1,951
class OacensusError(Exception): pass class UserFeedback(OacensusError): """ An exception which was caused by user input or a runtime error and which should be presented nicely. """ class ConfigFileFormatProblem(UserFeedback): """ A problem with config files. """ pass class APIErro...
403
112
import gin from colosseum.loops import human_loop from colosseum.mdps import EpisodicMDP from colosseum.mdps.river_swim.river_swim import RiverSwimMDP @gin.configurable class RiverSwimEpisodic(EpisodicMDP, RiverSwimMDP): @property def _graph_layout(self): return {node: tuple(node) for node in self.G}...
600
235
# How to add a test: # Copy this file # Rename TestTemplate to TestWhatever in line 9 # Rename machine path and config file in lines 11 and 14 from mpfmc.tests.MpfMcTestCase import MpfMcTestCase class TestTemplate(MpfMcTestCase): def get_machine_path(self): return 'tests/machine_files/test_template' ...
428
139
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: proto/availability-msgs.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _m...
3,366
1,374
import numpy as np import pandas as pd import datetime from okokyst_metadata import surveys_lookup_table import os import re import glob import gsw from okokyst_tools import pressure_to_depth encoding = "ISO-8859-1" __author__ = 'Elizaveta Protsenko' __email__ = 'Elizaveta.Protsenko@niva.no' __created__ = datet...
16,780
5,924
import pytest from tartiflette.language.ast import InterfaceTypeExtensionNode def test_interfacetypeextensionnode__init__(): interface_type_extension_node = InterfaceTypeExtensionNode( name="interfaceTypeExtensionName", directives="interfaceTypeExtensionDirectives", fields="interfaceTypeE...
5,250
1,062
'''Given two arrays, write a function to compute their intersection. ''' class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ m,n=len(nums1),len(nums2) l=[] if len(nums1)...
715
246
from collections import defaultdict import json from pandas.core import frame import torch import pandas as pd import os import pickle as pkl import numpy as np import cv2 import h5py import tqdm import functools import lmdb class EGTEA_GAZE_DATASET(torch.utils.data.Dataset): def __init__(self, logger, config, ro...
5,609
1,748
''' Merge Two Sorted Lists Asked in: Microsoft Yahoo Amazon Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists, and should also be sorted. For example, given following linked lists : 5 -> 8 -> 20 4 -> 11 -> 15 The merged ...
1,092
354
v = int(input('Digite um valor: ')) validador = 0 contador = 1 while contador < v: if v % contador == 0: validador += 1 contador +=1 if validador > 1: print(f'Esse número NÃO é primo, pois é divisível por {validador+1} números diferentes ') else: print('Esse número é primo')
299
113
"""Testing methods that need Handle server read access""" import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import requests import json import mock import b2handle from b2handle.handleclient import EUDATHandleClient from b2handle.handleexceptions import * # Load some...
13,906
3,889
# !/usr/bin/env python # -*- coding: utf-8 -*- # # Filename: models.py # Project: core # Author: Brian Cherinka # Created: Saturday, 12th September 2020 12:55:22 pm # License: BSD 3-clause "New" or "Revised" License # Copyright (c) 2020 Brian Cherinka # Last Modified: Saturday, 12th September 2020 12:55:22 pm # Modifie...
10,819
3,070
import re import html import pandas as pd re1 = re.compile(r' +') def imdb(fold_id: int, split_size: int): df = pd.read_pickle('df_train.pkl') df = df.reindex(columns=['sentiment', 'text']) df['text'] = df['text'].apply(fixup) # Split the data into k-folds. df_val = df[split_size * fold_id:split...
1,458
528
from .core import Config def simple(): from optparse import OptionParser op = OptionParser(usage="\n %prog\n %prog -c config.yaml") op.add_option('-c', '--config', metavar="FILENAME", help="Configuration file to parse", dest="configfile", default=None, type="string") op.add_option...
1,136
337
from xd.build.core.data.namespace import * from xd.build.core.data.expr import Expression from xd.build.core.data.string import String from xd.build.core.data.list import List from xd.build.core.data.dict import Dict from xd.build.core.data.func import Function from xd.build.core.data.num import * import unittest cla...
22,597
8,562
from google.appengine.ext import ndb from protorpc import messages from google.appengine.ext.ndb import msgprop from csvmodel import CsvModel class Stop(CsvModel): class LocationType(messages.Enum): STOP = 0 STATION = 1 class WheelchairBoarding(messages.Enum): UNKNOWN = 0 POSSI...
869
307
##*** ##class Base: ## def methodBase(self): ## print("In base class") ##class child(Base): ## def methodchild(Base): ## print("In child class") ##c1=child() ##c1.methodBase() ##c1.methodchild() ##*** ##class Base: ## def ___init__(self): ## print('base') ##class child(Base): ## pass ...
1,314
499
from ._bounding_box import * from ._user_IDs import * from ._user_points import *
82
30
import appdaemon.plugins.hass.hassapi as hass # # Listen for presence sensor change state and change alarm control panel state. # # Args: # sensor - home presence 'sensor' # ha_panel - alarm control panel entity (to arm and disarm). # constraint - (optional, input_boolen), if turned off - alarm panel will be n...
1,701
587
from random import randint import datetime lvl = 10 base_rounds = 10 rounds = lvl * base_rounds print("You have", rounds, "rounds to try to get through.") for i in range(rounds): r = randint(1, 100) print(r) if r >= 96: break print("Number of rounds:", i) if i == rounds - 1: print("Nothing ...
398
153
from ._version import get_versions from .contexts import cd from .prompting import error, prompt, status, success from .unix import cp, ln_s __all__ = ["prompt", "status", "success", "error", "cp", "cd", "ln_s"] __version__ = get_versions()["version"] del get_versions
272
91
"""Test Trotter Hamiltonian methods from `qibo/core/hamiltonians.py`.""" import pytest import numpy as np import qibo from qibo import hamiltonians, K from qibo.tests.utils import random_state, random_complex, random_hermitian @pytest.mark.parametrize("nqubits", [3, 4]) @pytest.mark.parametrize("model", ["TFIM", "XXZ...
5,566
2,143
import asyncio async def sleep(delay): for i in range(delay): await asyncio.sleep(0)
99
35
import warnings import torch.nn as nn def conv1x1_group(in_planes, out_planes, stride=1, groups=1): """ 1x1 convolution with group, without bias - Normal 1x1 convolution when groups == 1 - Grouped 1x1 convolution when groups > 1 """ return nn.Conv2d(in_channels=in_planes, ...
6,186
1,964
from sanic import Sanic from sanic.response import json from sanic_openapi import doc, swagger_blueprint from util import authorized app = Sanic(__name__) app.config["API_TITLE"] = "My-DataHub-OpenAPI" app.config["API_VERSION"] = "0.1.0" app.config["API_DESCRIPTION"] = "An example Swagger from Sanic-OpenAPI" app.co...
1,073
415
# -*- coding: utf-8 -*- import contextlib import sqlalchemy import sqlalchemy.orm from twisted.application.service import Service from zope.interface.declarations import implementer from bouser.helpers.plugin_helpers import Dependency, BouserPlugin from .interfaces import IDataBaseService __author__ = 'mmalkov' @i...
1,323
389
# -*- coding: utf-8 -*- from pydub import AudioSegment import sys import glob if __name__ == "__main__": args = sys.argv folder = glob.glob(args[1] + "/*.wav") initial = False for file in folder: soundfile = AudioSegment.from_file(file, "wav") if initial == False: soundfil...
581
187
import numpy as np import pandas as pd from utils import calculate_q from scipy import stats def calculate_deg_fold_change(data1_df, data2_df, fc_cutoff=1, alternative='two-sided'): """ This function calculates differentially expressed genes (DEGs) between two DataFrames or Series...
3,996
1,408
""" This is a test that we're using to gather example data from our two example models. This is passed a list of image names, image numbers, and the vector representing the face in the photo, and this script takes that and a split of testing vs training data to determine how accurate the model was by simply checking wh...
6,326
2,037
import numpy as np def save_list_to_file(z_list, z_file): with open(z_file, 'w') as fw: fw.writelines(z_list) def random_split_train_test(train_file, out_train_file, out_test_file, train_percentage=0.8): with open(train_file) as fr: lines = fr.readlines() np.random.shuffle(lines) t...
792
304
""" Functions and classes for interacting with the CodeRED data format """ from dataclasses import dataclass from typing import List, Optional, Union import pandas as pd from .types import FilenameType # The required headers for CodeRED EXCEL_HEADERS = ( "Command", "CustomKey", "ContactId", "First Na...
3,596
1,085
from imagekit.admin import AdminThumbnail from django.contrib.admin import TabularInline from core.admin.forms import LimitedInlineFormSet from core.admin.utils import ( get_change_view_link, get_changelist_view_link ) from ..models import PremierProduct class PremierManufacturerProductsTabularInline(Tabula...
2,516
794
import unittest from src.cumulator.base import Cumulator class TestBase(unittest.TestCase): def test_run(self): cumulator = Cumulator() # Test without parameters def foo(): return 1 output = cumulator.run(foo) self.assertEqual(1, output) # Tests with ...
629
204
#!/usr/bin/python3 import argparse import logging as log from aiohttp import web from api.databasemanager import DictionaryDatabaseManager from api.dictionary import \ entry, \ definition, \ translation, \ configuration from api.dictionary import \ get_dictionary, \ get_dictionary_xml, \ g...
4,191
1,378
from output.models.nist_data.list_pkg.any_uri.schema_instance.nistschema_sv_iv_list_any_uri_enumeration_1_xsd.nistschema_sv_iv_list_any_uri_enumeration_1 import ( NistschemaSvIvListAnyUriEnumeration1, NistschemaSvIvListAnyUriEnumeration1Type, ) __all__ = [ "NistschemaSvIvListAnyUriEnumeration1", "Nists...
360
150
import torch import numpy as np import re import itertools from textwrap import wrap import matplotlib.pyplot as plt def padding_mask(lengths, batch_size, time_size=None): """ Computes a [batch_size, time_size] binary mask which selects all and only the non padded values in the input tensor :param t...
3,578
1,339
from faq_module.storage import FAQManager # , FAQConfig, FAQData # from faq_module.commands import text # from discord.ext import commands # import faq_module.text # import logging import discord # import typing import re async def faq_on_message(faq_manager: FAQManager, message: discord.Message): embed = discor...
1,642
557
from tests.utils import hass_mock, get_instances import devices as devices_module from core import Controller from core import type as type_module def _import_modules(file_dir, package): pkg_dir = os.path.dirname(file_dir) for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]): if ispkg: ...
2,298
660
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='iocfg', version='0.1', description='Configuration for IO modules on Novus IHM', author='Thomas Del Grande', author_email='tgrande@pd3.com.br', packages=find_packages(), scripts=[ 'scripts/diocfg',...
521
168
# Import pandas using the alias pd import pandas as pd # Print the head of the homelessness data print(homelessness.head()) # Print the values of homelessness print(homelessness.values) # Print the column index of homelessness print(homelessness.columns) # Print the row index of homelessness print(homelessness.i...
1,912
655
import aiohttp from time import time import json from hashlib import sha512 import hmac from .fetcher import Fetcher class BittrexAPI(Fetcher): _URL = 'https://bittrex.com/api/v1.1/' _KEY = None _SECRET = None def __init__(self, key, secret): if key is None or secret is None: rai...
1,599
439
import time import pytest from tango.common.logging import initialize_logging from tango.common.testing import TangoTestCase from tango.executors.multicore_executor import MulticoreExecutor from tango.step_graph import StepGraph from tango.workspaces import LocalWorkspace from test_fixtures.package.steps import Sleep...
8,509
2,438
import cv2 import numpy as np face_classifier=cv2.CascadeClassifier('HaarCascade/haarcascade_frontalface_default.xml') def face_extractor(img): gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces=face_classifier.detectMultiScale(gray,1.3,5) if faces is(): return None for(x,y,w,h) in face...
1,051
433
import time import torch from torch import nn from transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Config import lightseq.inference as lsi from lightseq.training.ops.pytorch.quantization import ( qat_mode, QuantLinear, TensorQuantizer, weight_quant_config, ) from lightseq.training.ops.pytorch.t...
8,611
3,083
# Copyright (C) 2015-2021 Regents of the University of California # # 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 app...
1,748
516
""" 1. Clarification 2. Possible solutions - Cheat - Binary search II 3. Coding 4. Tests """ # T=O(n), S=O(1) class Solution: def findMin(self, nums: List[int]) -> int: if not nums: return int(-inf) return min(nums) # T=O(lgn), S=O(1) class Solution: def findMin(self, nums: List[int]...
623
223
import time from unittest import TestCase import grpc_testing from grpc import StatusCode from grpc.framework.foundation import logging_pool from cowsay_client import CowsayClient from cowsay_pb2 import DESCRIPTOR as COWSAY_DESCRIPTOR, QuoteRequest, QuoteResponse from cowsay_pb2_grpc import CowsayStub target_service...
1,766
586
SPEC = 'swagger.yaml' IMPLEMENTATION = 'flask' OUTPUT = 'build' FLASK_SERVER_NAME = 'my_flask_server'
102
47
# coding: utf-8 """ Web API Swagger specification No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import ...
4,792
1,552
from dataclasses import dataclass from typing import List from source.device_manager.database import get_database_connection,release_database_connection @dataclass class ScriptInfo: id: int name: str fileName: str user: int @dataclass class Script: id: int name: str fileName: str use...
4,088
1,149
#! /usr/bin/env python3 import sys import math import argparse as ap from json import dumps as jdumps from random import choices class LevelNotFoundException(Exception): pass def checkLevel(taxon, level): if level == 'species': return ('s__' in taxon) and ('t__' not in taxon) elif level == 'gen...
5,140
1,677
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import image_collection.models class Migration(migrations.Migration): dependencies = [ ('image_collection', '0003_auto_20160113_0445'), ] operations = [ migrations.RemoveField( ...
1,061
310
# Copying Holly Grimm's solution https://github.com/hollygrimm/cs294-homework/blob/master/hw1/bc.py # Copy and pasting and merging it into a copy of my behavior_cloner.py code. import argparse import pickle import os import sys import tensorflow.compat.v1 as tf import numpy as np from sklearn.model_selection import tr...
7,913
2,763
from __future__ import print_function import argparse import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image import numpy as np parser = argparse.ArgumentParser(description='VAE MNIST ...
4,397
1,658
# Author: Gheorghe Postelnicu from datetime import date import pandas as pd from io import BytesIO from urllib.request import urlopen class Yahoo(object): # Taken from http://www.jarloo.com/yahoo_finance/ yahoo_query_params = { 'ticker': 's', 'average_daily_volume': 'a2', 'dividend_yie...
4,760
1,574
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms', '0001_initial'), ] operations = [ migrations.CreateModel( name='SelfRegistrationInvitation', fields=[ ('id', models.AutoField(verbose_name='ID'...
1,192
334
""" Definition of the :class:`PersonNameTestCase` class. """ from dicom_parser.data_elements.person_name import PersonName from tests.test_data_element import DataElementTestCase class PersonNameTestCase(DataElementTestCase): """ Tests for the :class:`~dicom_parser.data_elements.person_name.PersonName` ...
397
127
"""Fixtures for models module.""" from physalia.models import Measurement import numpy def create_measurement(use_case='login', app_pkg='com.package', duration=2, energy_consumption=30): """Fake data for measurement.""" return Measurement( ...
1,627
472
import tensorflow as tf from config import config from utils.utils import * import logging from DL_Models.tf_models.ConvNet import ConvNet class XCEPTION(ConvNet): """ The Xception architecture. This is inspired by Xception paper, which describes how 'extreme' convolutions can be represented as separable ...
1,621
466
from __future__ import print_function from __future__ import absolute_import from __future__ import division import scriptcontext as sc import compas_rhino from compas_3gs.rhino import SettingsForm from compas_3gs.rhino import ForceVolMeshObject from compas_3gs.rhino import FormNetworkObject __commandname__ = "TGS...
909
264
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="xdcc", version="0.0.3", author="Thiago T. P. Silva", author_email="thiagoteodoro501@gmail.com", description="A simple XDCC downloader written in python3", long_description=long_descrip...
786
273
"""Modified code from https://developers.google.com/optimization/routing/tsp#or-tools """ # Copyright Matthew Mack (c) 2020 under CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/ from __future__ import print_function import math from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_sol...
9,319
2,924
import pytest import payload as pl from .fixtures import Fixtures @pytest.fixture() def billing_schedule(processing_account, customer_account): billing_schedule = pl.BillingSchedule.create( start_date="2019-01-01", end_date="2019-12-31", recurring_frequency="monthly", type="subsc...
1,162
386
import numpy as np from pydrake.all import * class BasicTrunkPlanner(LeafSystem): """ Implements the simplest possible trunk-model planner, which generates desired positions, velocities, and accelerations for the feet, center-of-mass, and body frame orientation. """ def __init__(self, frame_id...
5,415
1,927
import os import shadercompiler def spv_folder_to_glsl_folder(spv_folder): return os.path.join(spv_folder, '../../toy/shader') def glsl_from_spv(spv): spv_folder, spv_name = os.path.split(spv) glsl_folder = spv_folder_to_glsl_folder(spv_folder) glsl_name = spv_name[:-4] + '.glsl' glsl = os.path....
1,027
374
# Generated by Django 2.2.13 on 2021-01-22 17:41 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account'...
4,060
1,140
import urllib.request import cv2 import numpy as np import time URL = "http://192.168.1.3:8080/shot.jpg" while True: img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()),dtype=np.uint8) img = cv2.imdecode(img_arr,-1) cv2.imshow('IPWebcam',img) q = cv2.waitKey(1) if q == ord("q"...
373
159
import sys import time import arcpy import traceback import GeneralizeDEM if __name__ == '__main__': # SET PARAMETERS HERE # -------------------------------------------------------------------- demdataset = 'X:/Work/Scripts & Tools/MY/DEMGEN/mistral' marine = 'X:/Work/Scripts & Tools/MY/DEMGEN/DEMGENE...
2,046
710
#! /usr/bin/python3 # -*- coding: utf-8 -*- # # json_python_read.py # # Jul/25/2014 # # --------------------------------------------------------------------- import sys sys.path.append ("/var/www/data_base/common/python_common") # from file_io import file_to_str_proc # # --------------------------------------------...
559
187
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('reports', '0096_auto_20170920_1521'), ] operations = [ migrations.AlterField( model_name='reporttype', ...
534
166
from math import radians, cos, sin, asin, sqrt, floor, pow import math lat1 = 11.00461011 lon1 = 76.95691543 lat2 = 11.0070471 lon2 = 76.96110704 lon1 = radians(lon1) lon2 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(...
513
260
from slixmpp.exceptions import XMPPError from ..conf import settings mechanisms = {} def sasl_mech(): def register(mech): mechanisms[mech.name] = mech return mech return register class Mechanism(object): name = None def __init__(self, auth): self.auth = auth @staticmetho...
3,106
936
from django.http import HttpResponse def index(request): return HttpResponse(request.get_full_path())
108
31
class Player: def __init__(self, id, rating=1000, win_count=0, lose_count=0, win_streak=0, best_win_streak=0): self.id = id self.rating = rating self.win_count = win_count self.lose_count = lose_count self.win_streak = win_streak self.best_win_streak = best_win_streak...
1,258
444
""" Sprite Rotation With A Tank. Vehicles or tower defense turrets can have parts that can rotate toward targets. These parts are usually represented with separate sprites drawn relative to attachment points on the main body. Because these sprites are usually asymmetrical, we have to rotate them around their attachme...
7,625
2,340
import datetime import requests import requests_cache from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from api.commonresponses import DOWNSTREAM_ERROR_RESPONSE from api.modules.github import constants from api.modules.github.github_response...
4,913
1,276
import os # import pygame from mutagen.mp3 import MP3 import time from classuiui import MyFrame1 import wx # import thread import threading import multiprocessing from playsound import playsound from test001 import MyFrame1 # file="cd&&cd music&&cd&&StarSky.mp3" # os.system(file) # pygame.mixer.init() # audio = MP3("...
1,574
607
import mmcv import os import numpy as np from mmcv.runner import load_checkpoint from mmdet.models import build_detector from mmdet.apis import init_detector, inference_detector import torch # device = torch.device("cpu") # os.environ["CUDA_VISIBLE_DEVICES"]="" # import pdb; pdb.set_trace() config_file = '../configs/...
787
318