text
string
size
int64
token_count
int64
import unittest from flipper.conditions.operators.set_membership_operator import SetMembershipOperator class TestCompare(unittest.TestCase): def test_returns_true_when_expected_is_in_actual(self): operator = SetMembershipOperator() self.assertTrue(operator.compare(1, [1, 2, 3])) def test_re...
471
156
from collections import namedtuple from typing import Tuple, List, NewType, Optional, Dict from pangtreebuild.mafgraph.graph import Block from pangtreebuild.mafgraph.graph.Arc import Arc from pangtreebuild.mafgraph.mafreader import start_position from pangtreebuild.pangenome import graph from pangtreebuild.pangenome i...
19,801
5,885
from launchable.utils.gzipgen import compress import gzip from unittest import TestCase class GzippenTest(TestCase): def test_compress(self): """Basic sanity test of """ encoded = b''.join(compress([b'Hello', b' ', b'world'])) msg = gzip.decompress(encoded) print(msg) self....
353
111
from django.urls import path from .views import project_list_view urlpatterns = [ path('', project_list_view, name='project_list'), ]
138
43
# -*- coding: UTF-8 -*- import talib as ta import numpy as np from util import StockUtil as su from tech import StockTechIndicator class CCI(StockTechIndicator): def __init__(self): StockTechIndicator.__init__(self) def calculate(self, stock_code, date, time_period=14): cci = 0.0 data...
847
328
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 21:22:33 2018 @author: vangi """ from timeit import timeit setup = ''' import numpy as np np.random.seed(0) N_array = 200000 a_np = np.random.randn(N_array) b_np = np.random.randn(N_array) c_np = np.empty(N_array) def no_ufunc(a_np, b_np, c_np): c_np = a_np * ...
938
471
# # ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property # # 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 # # ...
2,451
659
from urllib.parse import urlencode as _urlencode, quote as _quote from urllib.request import urlopen as _urlopen from hashlib import md5 as _md5 from ast import literal_eval as _literal_eval from collections import OrderedDict as _OrderedDict _DEBUG = False class GameJoltDataRequired(Exception): """ Exception ra...
32,310
8,620
import os import inspect import torch import numpy as np import numbers def get_data_path(fn, subfolder='data'): """Return path to filename ``fn`` in the data folder. During testing it is often necessary to load data files. This function returns the full path to files in the ``data`` subfolder by def...
3,243
1,130
import asyncio import time import socket import argparse import aiohttp class MyConnector(aiohttp.TCPConnector): def __init__(self, ip): self.__ip = ip super().__init__() async def _resolve_host( self, host: str, port: int, traces: None = None, ): return [{ 'hostname': host, 'host': s...
5,109
2,187
#!/usr/bin/env python """ CREATED AT: 2021/8/28 Des: https://leetcode.com/problems/longest-uncommon-subsequence-ii/ GITHUB: https://github.com/Jiezhi/myleetcode """ from typing import List class Solution: def findLUSlength(self, strs: List[str]) -> int: pass def test(): assert Solution().findLUSle...
467
188
# Advent of Code 2020 Day # https://adventofcode.com/2020/ import cProfile import itertools import math import numpy as np from collections import namedtuple from pprint import pformat, pprint from typing import List, Optional from numpy.typing import ArrayLike USE_EXAMPLE1 = False # example input or full input D...
23,732
7,754
import socket import select from server_info import ServerInfo from client_handler.client_thread import ClientThread from server_handler.server_thread import ServerThread from server_handler.server_thread_proxy import ServerThreadProxy from logger import Logger class ServerMainLoop: def __init__(self): sel...
1,870
547
# 1. Peça a idade do usuário e imprima se ele é maior ou menor de 18 anos; idade = int (input ('Digite sua idade:')) if idade < 18: print ('Você tem menos de 18 anos') else: print ('Você tem 18 anos ou mais') # 2. Peça um número e mostre se ele é positivo ou negativo; numero = float (input ('Digite um número ...
8,838
3,714
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 2 20:41:01 2021 @author: marina Interesting: - T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-08-51: Really smooth and contained between (-3,3) - T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-25-20 """ # Set absolute package path i...
2,023
1,017
#!/bin/python3 # The Captain's Room # https://www.hackerrank.com/challenges/py-the-captains-room/problem from collections import Counter if __name__ == '__main__': k = int(input()) room_captain = Counter(map(int, input().split())).most_common()[:-2:-1] print(room_captain[0][0])
293
109
from __future__ import absolute_import from __future__ import unicode_literals # Registry from transformer_2.data.processing._registry import PROCESSOR_REGISTRY, \ BaseProcessor, register_processor, Compose, make_processor_from_list # Generic processors from transformer_2.data.processing.general import HtmlUnesca...
1,536
490
""" PyDMC API Client """ import requests class DMC: def __init__(self,user,pwrd,host,v=5,content='json',accept='json'): self.user = user self.pwrd = pwrd self.host = "%s/api/rest/v%d" % (host,v) self.content = content self.accept = accept self.headers = { ...
7,223
2,114
from .archery_range import ArcheryRange from .barrack import Barrack from .building import Building from .dock import Dock from .farm import Farm from .granary import Granary from .market import Market from .military_building import MilitaryBuilding from .stable import Stable from .storage_building import StorageBuildi...
832
261
#: Okay True and False #: E271 True and False #: E272 True and False #: E271 if 1: #: E273 True and False #: E273 E274 True and False #: E271 a and b #: E271 1 and b #: E271 a and 2 #: E271 E272 1 and b #: E271 E272 a and 2 #: E272 this and False #: E273 a and b #: E274 a and b #: E273 E274 this and Fal...
323
201
from threading import Thread,Lock from api.GIS.config import GIS_mgdb_config from api.GIS.database.mongoDB import MGO import json from api.GIS.GISStaticsFun import GisStaticsFun class TheadFun(): def __init__(self): pass # self.param = param def queryQBByIds(self,ids): DBConfig = []...
8,973
2,546
import pygame class Cell: def __init__(self, pos, dimensions, color): self.pos = pos self.dimensions = dimensions self.color = color def draw(self, screen): pygame.draw.rect(screen, self.color, ((self.pos), (self.dimensions)))
268
79
from django import template register = template.Library() # 문자열 변수 생성 가능 class SetVarNode(template.Node): def __init__(self, new_val, var_name): self.new_val = new_val self.var_name = var_name def render(self, context): context[self.var_name] = self.new_val return ...
1,845
657
#!/bin/env python3 import sys import plac import webcolors import os _COLOR_FILTERS = { '#': '', '(': '', ')': '', } LIGHT_CONTROLS = { 'left': '/sys/class/leds/system76::kbd_backlight/color_left', 'center': '/sys/class/leds/system76::kbd_backlight/color_center', 'right': '/sys/class/leds/sys...
2,194
765
from .field import Field from .re_field import ReField from .matrix import Matrix inf = Field(is_inf=True) IDM = Matrix(1, 0, 0, 1) G0 = Matrix(0, -1, 1, 0) G1 = Matrix(0, 1, -1, 1) G1_2 = G1 ** 2 G0_ = Matrix(0, 1, -1, 0) G1_ = Matrix(1, 1, -1, 0) G1_2_ = G1_ ** 2 G_ = Matrix(1, -1, 0, 1) G__ = Matrix(1, 0, -1, 1)...
420
235
import unittest import unittest.mock as mock from unittest.mock import patch __all__ = ['unittest','mock','patch']
116
35
#!/usr/bin/env python ''' Reporte búsqueda de alquileres de Inmuebles --------------------------- Autor: Inove Coding School Version: 1.0 Descripcion: Este script realiza reportes de los datos adquiridos de alquileres de inmuebles Reporte Nº 0: Visualizar todos los reportes juntos de estudio por ambientes y...
5,972
2,288
""" Read voyage data emails. """ import email from imaplib import IMAP4_SSL import logging OK = 'OK' logger = logging.getLogger(__name__) class EmailCheckError(Exception): pass class EmailServer: def __init__(self, server, username, password): self.password = password self.server = server self.username...
3,043
1,167
from common import get_file_contents def most_common(index, items, total): if int(items[index]) >= total / 2: return "1" else: return "0" def least_common(index, items, total): # if our number is bigger than half our total lines # then we know that 1 is the more common value # so we return 0 if int(items[...
1,991
872
import os import redis from urllib.parse import urlparse def connect_to_redis(url=None): """Return a connection to Redis. If a URL is supplied, it will be used, otherwise an environment variable is checked before falling back to a default. Since we are generally running on Heroku, and configuring S...
670
196
# # Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved. # class ThisAccess(object): const = 0 mutable = 1 static = 2
139
58
from . import modules def init_app(app, **kwargs): modules.init_app(app, **kwargs)
88
32
# -*- coding: utf-8 -*- """ Created on Thu Sep 2 03:02:57 2021 @author: sgaa_ """ print ("for loop") for i in range (1,20): print (i) print ("while loop") i=1 while i<12: print (i) i+=1 if 1 in range(2,5): print ("Yes 1 is in the range") elif 3 in range (3,5): print ("Yes 1 is in range 2") el...
366
169
import json import re import os import logging from abc import ABC from typing import Dict, Any, List, Tuple from utils.constants import pascal_train_size, pascal_val_size logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def preprocess_caption(caption: str) -> str: """Basic method us...
12,684
3,582
# coding: utf-8 """ Genomic Data Store Service No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import im...
26,474
7,022
import math from typing import Tuple import jax import jax.numpy as jnp import numpy as np from einops import repeat def factor_int(n: int) -> Tuple[int, int]: f1 = int(math.ceil(math.sqrt(n))) while n % f1: f1 -= 1 f2 = n // f1 return min(f1, f2), max(f1, f2) def compute_channel_change_mat...
5,545
2,485
# Author: @dourgey # Create Time: 2019/12/27: 18:06 # 主要知识点: # argparse的使用 # 检查文件路径是否存在 # PILLOW读取图片并处理 # 文件写入 import argparse import os import sys from PIL import Image parser = argparse.ArgumentParser() parser.add_argument("-i", "--image", help="主人要转换的图片路径喵,默认在当前路径下读取喵~") parser.add_argument("-f", "--file", help="...
1,210
695
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import ray.numbuf import ray.pickling as pickling def check_serializable(cls): """Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class t...
6,536
1,948
from numpy import sqrt import numpy as np #from util import sphinx_compat_jit as jit from numba import jit ORDER_L=50 @jit def alpha(l,m): return sqrt((3*(l-m)*(l+m))/(4*np.pi*(2*l-1)*(2*l+1))) @jit def alpha_plus(l,m): return sqrt((3*(l+m)*(l+m+1))/(8*np.pi*(2*l-1)*(2*l+1))) @jit def Alm(l,m): retu...
3,729
1,585
#!/usr/bin/env python import logging import json import os import os.path as path from collections import OrderedDict import argparse import tweepy from tweepy import Stream import twitter_config from tweet_writer_listener import TweetWriterListener CITIES = ['San Francisco', 'New York', 'Boston', 'Los Angeles', '...
2,694
918
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------- # This is a sample controller # this file is released under public domain and you can use without limitations # ------------------------------------------------------------------------- import json from datetime import d...
9,283
2,791
#!/usr/bin/env python3 from markdownify import markdownify as md import argparse import re import os import sys parser = argparse.ArgumentParser() parser.add_argument('input_file', help='file to convert') args = parser.parse_args() input_file = args.input_file print(input_file) if not re.search('.dist.php', input_...
2,200
871
import io, os import argparse from timeit import default_timer as timer parser = argparse.ArgumentParser(description="File Performance Testing Util") parser.add_argument("command",help="Test to perform",choices=['read','write','readany']) parser.add_argument("dir",help="Directory to use") args = parser.parse_args() ...
1,957
895
import webbrowser url = 'http://www.wsb.com/Assignment2/case15.php?videourl=" onerror="alert(document.cookie)' new = 2 webbrowser.open(url, new=new)
151
63
import types from typing import Iterable, Union from .call_frame import CallFrame __all__ = ['CallStack'] class CallStack: """ Represents the call stack - a series of :class:`CallFrame` instances. This class can be used like a read-only list. It supports iteration, indexing, membership testing, etc. ...
2,238
615
from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from products.models import Product def productList(request, productName): """产品的列表页""" submenu = productName if productName == 'robot': productName = '家用机器人' elif p...
2,728
942
import json import os from dataclasses import dataclass, field from typing import Dict, Optional @dataclass class AnimationClipData: name: str startTime: float stopTime: float id: Optional[int] = field(init=False) duration: float = field(init=False) def __post_init__(self): self.durat...
1,545
496
import base64 import fnmatch import logging import os import tempfile from ssl import SSLContext, create_default_context from typing import Dict, List, Optional, Sequence import yaml from kube.tools.repr import disp_secret_blob, disp_secret_string class ExecCmd: def __init__(self, *, command: str, args: List[st...
14,431
4,227
from PyQt5.QtCore import QThread, pyqtSignal, QDateTime, QObject from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit import time import sys class BackendThread(QObject): # 通过类成员对象定义信号 update_date = pyqtSignal(str) # 处理业务逻辑 def run(self): while True: data = QDateTime.curre...
1,256
458
from __future__ import annotations from typing import List, Tuple, OrderedDict as OrderedDictType, DefaultDict, Optional from collections import OrderedDict, defaultdict from metric import MusicNote, TimePointSequence from model.base import MidiModel, MidiModelState from model.beat import TatumTrackingModelState, Tatu...
13,098
3,911
global plus global minus minus = ["ASP","GLU"] plus = ["ARG","HIS","LYS"] def find_charge(residues): """ Takes a list of residues and returns the number of plus and minus charged residues. This function uses the global plus and minus variables """ global plus global minus plus_charge = sum([res in plu...
1,029
363
# imports import csv # open the file with open("example.csv") as file: reader = csv.reader(file) # prep to store names of columns titleRow = reader.next() #rest = [row for row in reader] columnList = {} for row in reader: iterator = 0 cellList = [] for cell in row: if cell == "": cellList.app...
632
239
import some_mod def functione(b): a = some_mod.some_class() print(b) print("othermod calling in " + str(a.hello))
124
49
from flask import Flask from application.blueprints.user.routes import users def init_app(app: Flask): app.register_blueprint(users)
140
45
from collections import namedtuple import torch NONLINEARITIES = { "tanh": torch.nn.Tanh, "relu": torch.nn.ReLU, } TimeDerivative = namedtuple("TimeDerivative", ["dq_dt", "dp_dt"]) StepPrediction = namedtuple("StepPrediction", ["q", "p"])
249
96
>>> S = 'Susceptible' >>> print(S) >>> E = 'Exposed' >>> print(E) >>> I = 'Infectious' >>> print(I) >>> R = 'Removed' >>> print(R) >>> N = 'Total Population' >>> print(N) >>> C = 'Living with COVID19' >>> print(C) >>> D = 'Living with Diabetes' >>> print(D) >>> Susceptible = input('Enter number of Susceptible Individua...
1,213
467
from typing import _GenericAlias # type: ignore from typing import ClassVar from typing_extensions import Protocol # Single-sourcing the version number with poetry: # https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094 try: __version__ = __import__("importlib.metadata").metadata.version(__na...
2,396
695
from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import altair as alt import pandas as pd from sklearn.metrics import ( accuracy_score, classification_report, f1_score, precision_score, recall_score, ) from gobbli.util import ( as_mult...
13,818
3,908
#!/usr/bin/env python import rospy from victor_fake_hardware_interface.minimal_fake_arm_interface import MinimalFakeGripperInterface def main(): rospy.init_node("minimal_fake_arm_interface") interfaces = {} arm_names = ["left_arm", "right_arm"] for arm in arm_names: interfaces[arm + "/gripp...
791
263
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import networkx as nx import pandas as pd import copy from numba import njit from numba.typed import Dict, List from numba.core import types from concurrent.futures import ThreadPoolExecutor np.seterr(over='ignore') def pi(setlist, i): ...
11,647
4,589
"""odin.http.server - ODIN HTTP Server class. This module provides the core HTTP server class used in ODIN, which handles all client requests, handing off API requests to the appropriate API route and adapter plugins, and defining the default route used to serve static content. Tim Nicholls, STFC Application Engineer...
3,403
875
# @file Valid Parentheses # @brief Given a string containing just the characters '(', ')', '{', '}', # '[' and ']', determine if the input string is valid. # https://leetcode.com/problems/valid-parentheses/ import collections ''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de...
1,382
392
#!/usr/bin/env python from __future__ import print_function from collections import deque def parse_and_sort_topics(topics): topic_deque = deque(tuple(topic.split(' ')) for topic in topics) word0s = [item[0] for item in topic_deque] word1s = [item[1] for item in topic_deque] topic_deque = deque(sorted...
3,746
1,296
from .core import _train, train, predict, XGBClassifier, XGBRegressor # noqa __version__ = '0.1.7'
101
40
#! /usr/bin/env python # -*- coding: utf-8 -*- #################### # Copyright (c) 2021 ryanbuckner # https://github.com/ryanbuckner/life360-plugin/wiki # # Based on neilk's Solcast plugin ################################################################################ # Imports #####################################...
12,963
4,659
from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.views import generic, View class SignUp(generic.CreateView): form_class = UserCreationForm success_url = revers...
699
200
import requests from bs4 import BeautifulSoup class Pais: name = '' casos = {} def __init__(self, name, infectados=None, recuperados=None, fallecidos=None, activos = None): self.name = name self.casos['infectados'] = infectados self.casos['recuperados'] = recuperados self.casos['fallecidos'] = fallecidos ...
3,306
1,344
import pyblish.api from openpype.pipeline import PublishXmlValidationError from openpype.hosts.tvpaint.api import lib class RepairStartFrame(pyblish.api.Action): """Repair start frame.""" label = "Repair" icon = "wrench" on = "failed" def process(self, context, plugin): lib.execute_georg...
947
283
import board import neopixel import time pixels = neopixel.NeoPixel(board.D21, 1) GREEN = (255, 0, 0) # RED = (0,255,0) # BLUE = (0,0,255) # YELLOW = (255,255,0) # CYAN = (255,0,255) # VIOLET = (0,127,255) # WHITE = (255,255,255) # OFF = (0,0,0) # def off(): pixels[0] = OFF def startup(): pixels[0] = GREEN time....
1,304
774
import torch import pretrainedmodels as PM import torch.nn as nn from .Mobilenet import MobileNetV2 device = 'cuda' if torch.cuda.is_available() else 'cpu' def Model_builder(configer): model_name = configer.model['name'] No_classes = configer.dataset_cfg["id_cfg"]["num_classes"] model_pretra...
3,548
1,341
from erised.proxy import Proxy class Dog: def bark(self, loud: bool): sound = "woof-woof" if loud: return sound.upper() return sound class Person: def __init__(self, dog: Dog = None): self.dog = dog if __name__ == "__main__": person = Person() person.dog...
828
263
# Generated by Django 2.1.7 on 2019-03-23 00:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ontask', '0055_action_nrows_all_false'), ] operations = [ migrations.AlterField( model_name='action', name='nrows_al...
480
158
from __future__ import division from builtins import str from builtins import range import proteus import sys import numpy from proteus import Profiling #it should probably be associated with the PUMI domain somehow #The current implementation assumes we're using NS, VOF, LS, RD, MCorr setup with lagging and Backwards...
6,863
2,054
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-02-02 14:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('vocabs', '0002_auto_20170202_1030'), ('lunch', '0001...
596
228
""" REAM: REAM Ain't Markdown ~~~~~~~~~~~~~~~~~~~~~~~~~ This file is part of the ream package :copyright: Copyright 2020 by Chih-Ming Louis Lee :license: MIT, see LICENSE for details """ import sys import os import re import json import pandas as pd from ream.transformer import Ream2Dict from ream.grammar import REA...
2,634
818
### get all the blocked raw datafiles from ARC and convert to nifti's ### #rsync -avz ndcn0180@arcus.arc.ox.ac.uk:/data/ndcn-fmrib-water-brain/ndcn0180/EM/M3/M3_S1_GNU/testblock/m000_?????-?????_?????-?????_?????-?????.h5 /Users/michielk/oxdata/P01/EM/M3/M3_S1_GNU/ for f in `ls m000_?????-?????_?????-?????_?????-?????....
444
237
import sys print(sum([int(x) for x in sys.argv[1]]))
53
23
# Copyright 2020 Intel, 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,...
1,549
454
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-09-08 16:33 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reviews', '0015_auto_20180908_1626'), ] operations = [ migrations.RemoveField( ...
621
214
from constants import ALIGNMENT, STRIKE_THROUGH, UNDERLINE def assert_bool(val): assert isinstance(val, (bool, None)), f'Can only be True, False, or None. {val} was given instead.' class Markup: """ A Markup for a range of MarkedUpText. """ def __init__(self): from placer.templates import ...
2,796
816
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np import svirl.config as cfg from svirl.storage import GArray from . import FixedVortices class Params(object): """This class contains setters and getters for parameters""" def __init__(self, mesh, vars): self...
10,476
3,401
from hashlib import sha256 from helpers import load_dataset import numpy as np import os import pandas as pd import requests import sys import time import urllib.request CSV_PATH = sys.argv[1] URL_COLUMN = sys.argv[2] PATH = sys.argv[3] def download_image(url, file_path): try: if 'imgur.com' in url: ...
1,570
559
from abc import ABCMeta, abstractmethod from dataclasses import dataclass from typing import Any, List, Type, TypeVar from lf3py.lang.dsn import DSN from lf3py.serialization.serializer import DictSerializer, Serializer T_OBJ = TypeVar('T_OBJ') class Command(metaclass=ABCMeta): @property @abstractmethod ...
1,169
371
from . import aggregative from . import base from . import meta from . import non_aggregative EXPLICIT_LOSS_MINIMIZATION_METHODS = { aggregative.ELM, aggregative.SVMQ, aggregative.SVMAE, aggregative.SVMKLD, aggregative.SVMRAE, aggregative.SVMNKLD } AGGREGATIVE_METHODS = { aggregative.CC, ...
801
336
def prime_num(n): if n>1: for i in range (2,n): if n%i==0: return False return True lst_prime=list(filter(prime_num,range(1,2500))) print(len(lst_prime))
208
81
from EM_Algorithm.gen_gauss import gen_gauss from EM_Algorithm.gen_poisson import gen_poisson import numpy as np import matplotlib.pyplot as plt x = gen_gauss([8],[2],[1000]) y = gen_poisson([1],[1000]) fig = plt.figure(figsize=(8, 8)) # Add a gridspec with two rows and two columns and a ratio of 2 to 7 between # th...
916
375
import os from threading import Thread from typing import List from aiExchangeMessages_pb2 import SimulationID, TestResult def _handle_vehicle(sid: SimulationID, vid: str, requests: List[str]) -> None: vid_obj = VehicleID() vid_obj.vid = vid i = 0 while i < 3: i += 1 print(sid.sid + ...
2,114
688
# PHS3350 # Week 2 - wave packet and RFAP - # "what I cannot create I cannot understand" - R. Feynman. # Ana Fabela Hinojosa, 13/03/2021 import os from pathlib import Path import numpy as np import matplotlib import matplotlib.pyplot as plt import physunits from scipy.fft import fft, ifft plt.rcParams['figure.dpi'] =...
1,916
911
""" run with nosetests -v --nocapture or nosetests -v """ from builtins import object from cloudmesh_base.util import HEADING class Test_pass(object): def setup(self): pass def tearDown(self): pass def test_dummy(self): HEADING() assert True
295
104
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test record permissions.""" from __future__ import unicode_literals import uuid import pytest from flas...
3,725
1,166
from .components.Head import Head from .components.NavIcons import Hamburger from .components.Screens import HomeScreen, AboutScreen, ProjectsScreen from .components.Footer import Footer from .utils import JSON_DIR from json import load import os def Index(): with open(os.path.join(JSON_DIR, 'home_data....
945
316
# Copyright (c) 2021-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import logging from typing import Dict, List import gym import numpy as np from dm_control import mujoco from dm_control.mujoco.wrapper.mjbinding...
5,190
1,951
#!/usr/bin/python # # identify the DNS servers used on the WAN interface. # # Tries to find the owner of the DNS as well. # # DNS spoofing is one of the entry points for malware. I haven't seen it since I dumped # Windows at home but in past have seen malware that would change the DNS config on # the router. Kind of ...
1,124
369
from hs_restclient import HydroShare, HydroShareAuthBasic # Download LCZO sesnor database from Hydroshare # link to the Hydroshare resource https://www.hydroshare.org/resource/b38bc00887ec45ac9499f9dea45eb8d5/ auth = HydroShareAuthBasic(username="miguelcleon", password = "x") hs = HydroShare(auth = auth) hs.getResour...
398
168
""" Game fix for Toybox Turbos """ #pylint: disable=C0103 from protonfixes import util from protonfixes.logger import log def main(): """ Changes the proton argument from the launcher to the game """ log('Applying fixes for Toybox Turbos') # Fix infinite startup screen util.set_environment('PROT...
339
111
""" The strategies module provides utilities for designing trading strategies Notes ------ All strategies should inherit from BaseStrategy, and provide a get_order_list method. For details of the requirements of this method, see its docstring in base/BaseStrategy, or in the method within SimpleStrategy in this module....
4,035
1,008
# Create your migrations here. # WILL USE THIS LATER IF/WHEN YOU CREATE A DATABASE AND USER ACCOUNTS - THIS MAY BE IN A DIFFERENT APP AS WELL!!!
144
54
import numpy as np def run(self,Inputs): if self.x != 0.0: self.ans = self.y/self.x else: self.ans = np.array([float('inf')])
140
61
""" Provides example of how I would like `enum` to be used. Implementation details: (1) Uses Metaclass for two reasons: (1.1) So that the subclasses can be iterable (we want class objects, not instance objects) (1.2) To automatically collect Enumeratee enum.Enumerator EnumSet, Partition, Basis Produc...
1,955
618
#!/usr/bin/env python '''Generally useful bits and bobs.''' import queue # For PrintThread and exe_run from time import sleep, time, gmtime, strftime # For lock timeout, exe_run timeout and logging import threading # For PrintThread import os # For ChangeDir, ...
38,079
10,157