text
string
size
int64
token_count
int64
import os import numpy as np import matplotlib.pyplot as plt import utils.io as io from global_constants import misc_paths def get_infonce_data(infonce_dir,layers): infonce_data = io.load_json_object( os.path.join( infonce_dir, f'infonce_{layers}_layer.json')) iters = [] lo...
3,785
1,467
import sys sys.path.append("../../") from skimage.data import astronaut, camera from sciwx.canvas import ICanvas from sciapp.action import Tool import wx class TestTool(Tool): def __init__(self): Tool.__init__(self) def mouse_down(self, image, x, y, btn, **key): print( "x:%d y:%d...
889
315
import os from aif360.datasets import BinaryLabelDataset from aif360.metrics import ClassificationMetric import numpy as np import argparse import pandas as pd import boto3 import botocore import json from flask import Flask, request, abort from flask_cors import CORS app = Flask(__name__) CORS(app) def dataset_wrap...
5,416
1,628
# Copyright (c) Niall Asher 2022 from os import remove, path, mkdir from socialserver.util.output import console from socialserver.util.config import config from socialserver import application from werkzeug.serving import make_server from threading import Thread class TestingServer(Thread): def __init__(self, ...
1,352
405
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-07-17 03:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0257_auto_20190717_1034'), ] operations = [ migration...
484
178
#!/usr/bin/env python # -*- coding: utf-8 -*- # #@created: 08.09.2011 #@author: Aleksey Komissarov #@contact: ad3002@gmail.com from PyExp import AbstractModel class ChomosomeModel(AbstractModel): ''' Chromosome model. Dumpable attributes: - "chr_genome", - "chr_number", - "chr_tax...
1,739
660
import os from dotenv import load_dotenv load_dotenv() class Config(): DEBUG = True ENV = 'dev' JWT_SECRET = os.getenv('JWT_SECRET', 'secret') SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DB_URI', 'sqlite://') SQLALCHEMY_TRACK_MODIFICATIONS = False TESTING = False class TestingConfig(Config): ...
448
177
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-04-18 14:07 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('DevicesAPP', '0002_auto_20180404_1557'), ] operations = [ migrations....
724
255
# -*- coding: utf-8 -*- ############################################################################# # # Copyright © Dragon Dollar Limited # contact: contact@dragondollar.com # # This software is a collection of webservices designed to provide a secure # and scalable framework to build e-commerce websites. # # This s...
7,395
2,106
import heapq def solution(scoville, K) : heapq.heapify(scoville) count = 0 while scoville : try : first = heapq.heappop(scoville) second = heapq.heappop(scoville) combine = first + second * 2 count += 1 heapq.heappush(scoville, combine)...
478
166
from x_rebirth_station_calculator.station_data.station_base import Module from x_rebirth_station_calculator.station_data.station_base import Production from x_rebirth_station_calculator.station_data.station_base import Consumption from x_rebirth_station_calculator.station_data import wares names = {'L044': 'Valley For...
587
204
"""empty message Revision ID: e424d03ba260 Revises: ace8d095a26b Create Date: 2017-10-12 11:25:11.775853 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e424d03ba260' down_revision = 'ace8d095a26b' branch_labels = None depends_on = None def upgrade(): # ...
652
264
from setuptools import setup setup( name='smiegel', version='0.0', long_description=__doc__, packages=['smiegel'], include_package_data=True, author='Erik Price', description='Self hosted SMS mirroring service', license='MIT', install_requires=open('requirements.txt').readlines(), ...
428
134
from buycoins.client import BuyCoinsClient from buycoins.exceptions import AccountError, ClientError, ServerError from buycoins.exceptions.utils import check_response class NGNT(BuyCoinsClient): """The NGNT class handles the generations of virtual bank deposit account.""" def create_deposit_account(self, acc...
1,558
367
"""App Signals """ import logging from django.db.models.signals import post_save from django.dispatch import receiver from vision_on_edge.azure_training_status.models import TrainingStatus from vision_on_edge.notifications.models import Notification logger = logging.getLogger(__name__) @receiver(signal=post_save,...
1,510
396
import json import brilleaux_settings import flask from flask_caching import Cache from flask_cors import CORS import logging import sys from pyelucidate.pyelucidate import async_items_by_container, format_results, mirador_oa app = flask.Flask(__name__) CORS(app) cache = Cache( app, config={"CACHE_TYPE": "filesyst...
2,526
797
from typing import Optional from aiohttp.web import AppRunner # TODO fix import from aioros.graph_resource import get_local_address from .master_api_server import start_server from .param_cache import ParamCache from .registration_manager import RegistrationManager class Master: def __init__(self): se...
1,253
340
from db import db class AgentModel(db.Model): __tablename__ = 'agents' id = db.Column(db.Integer, primary_key=True) agent_id = db.Column(db.Integer, db.ForeignKey('users.id'), unique=True) customers = db.relationship("CustomerModel", backref='agent') name = db.Column(db.String(80)) email = db.C...
1,344
439
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-10-23 09:47 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('oa', '0003_auto_20171023_1746'), ] operations = [ migrations.RenameField( ...
421
161
import time import subprocess import sys import logging class GitDirectoryError(Exception): """Directory not a git repository""" def generate(directory=".") -> str: commitDate = 0 try: commitDate = int( subprocess.check_output( "git show -s --format='%ct'", shell=True...
836
247
MAX_CONSOLE_LINE_LENGTH = 79 class CliReport: def __init__(self): self.is_initialized = False def print(self, string='', length=MAX_CONSOLE_LINE_LENGTH, end='\n'): if self.is_initialized: number_of_spaces = 0 if length > len(string): number_of_spaces = ...
520
172
# -*- coding: utf-8 -*- import typing import pandas as pd import smart_open import awswrangler as wr from .helpers import ( check_enumeration_s3_key_string, get_key_size_all_objects, group_s3_objects_no_larger_than, ) from .options import ZFILL def merge_csv( s3_client, source_bucket: str, so...
5,138
1,715
# Supress warnings caused by tensorflow import warnings warnings.filterwarnings('ignore', category = DeprecationWarning) warnings.filterwarnings('ignore', category = PendingDeprecationWarning) import pytest from .. import Marabou import numpy as np import os # Global settings TOL = 1e-4 ...
5,316
1,644
# Generated by Django 3.2.12 on 2022-04-24 14:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_jalali.db.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
2,703
870
import os from dotenv import load_dotenv import pandas as pd import psycopg2 from psycopg2.extras import execute_values import json import numpy as np load_dotenv() DB_NAME = os.getenv("DB_NAME") DB_USER = os.getenv("DB_USER") DB_PASSWORD = os.getenv("DB_PASSWORD") DB_HOST= os.getenv("DB_HOST") conn = psycopg2.con...
6,825
2,305
import json from flask import Flask, render_template, redirect, Response, jsonify,request from flask_cors import CORS from Kerberos import Server,Server_Error app = Flask(__name__, static_folder='./static', static_url_path='/') cors = CORS(app) #! This server uses distinct routes for different type of requests #? We ...
2,530
774
import sys, glob from os import listdir, remove from os.path import dirname, join, isfile, abspath from io import StringIO import numpy as np import utilsmodule as um script_path = dirname(abspath(__file__)) datasetPath = join(script_path,"data/") e = 'shrec' ### Compute the dice coefficient used in Table 1, # E Mo...
3,050
1,124
from firebase import *
23
6
import logging from random import randint, random from mlflow import ( active_run, end_run, get_tracking_uri, log_metric, log_param, start_run, ) from mlflow.tracking import MlflowClient from dbnd import task logger = logging.getLogger(__name__) @task def mlflow_example(): logger.info...
1,094
396
from .channelpad import channelpad from .conv2d_same import conv2d_same from .padding import get_same_padding, pad_same from .shakedrop import shakedrop from .sigaug import signal_augment from .sigmoid import h_sigmoid from .stack import adjusted_concat, adjusted_stack from .swish import h_swish, swish
312
104
#Conditional Tests HW - Due Monday # 13 Tests --> 1 True and 1 False for each #If Statements #Simplest structure of an if statement: # if conditional_test: # do something <-- Instructions/commands #my_age = 13 #if my_age >= 18: # print("You are old enough to vote.") # print("Are you registered to vote?...
2,673
844
#!/usr/bin/env python # BCET Workflow __author__ = 'Sam Brooke' __date__ = 'September 2017' __copyright__ = '(C) 2017, Sam Brooke' __email__ = "sbrooke@tuta.io" import os import georasters as gr import matplotlib.pyplot as plt import numpy as np from optparse import OptionParser import fnmatch import re from scipy....
3,798
1,643
from pandas import DataFrame import os def frame_to_csv(frame:DataFrame,output_file:str,decimal_format=',', float_format=None,date_format=None,quote_char='"',no_data_repr='',sep=';'): """ Converts a pandas dataframe to a csv file Parameters ---------- output_file -> path to file to write to d...
1,989
631
''' Integration Test for HA mode with UI stop on one node. @author: Quarkonics ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoo...
1,562
578
# This code is licensed under the MIT License (see LICENSE file for details) import ctypes import atexit # import all the autogenerated functions and definitions # note: also pulls in common which provides AndorError and several other constants from . import wrapper from .wrapper import * # Provided for reference pu...
4,736
1,534
from app.validation.error_messages import error_messages from tests.integration.integration_test_case import IntegrationTestCase class TestSaveSignOut(IntegrationTestCase): def test_save_sign_out_with_mandatory_question_not_answered(self): # We can save and go to the sign-out page without having to fill ...
3,718
1,133
import torch import torch.nn as nn, torch.nn.functional as F from torch.nn.parameter import Parameter import math from torch_scatter import scatter from torch_geometric.utils import softmax # NOTE: can not tell which implementation is better statistically def glorot(tensor): if tensor is not None: s...
16,479
5,852
#!/bin/env python3 # import os # os.environ['PYTHONASYNCIODEBUG'] = '1' # import logging # logging.getLogger('asyncio').setLevel(logging.DEBUG) from datetime import datetime import traceback import atexit import argparse import os from os import path import sys import logging from struct import pack import random fro...
23,515
7,166
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys def main(options): # test parameter handling print options.infile, options.traml_in, options.outfile def handle_args(): import argparse usage = "" usage += "\nOpenSwathFeatureXMLToTSV −− Converts a featureXML to a mProphet tsv." parse...
799
260
import kanjigrid gridder = kanjigrid.Gridder("Kanji", 40, "Header", 52) grading = kanjigrid.Jouyou() with open("test.txt", "r", encoding="utf-8") as f: data = f.read() gridder.feed_text(data) grid = gridder.make_grid(grading, outside_of_grading=True, stats=True, bar_graph=True) grid.save("test.png") if "𠮟" in g...
487
216
import torch import numpy as np import time from spectrl.util.rl import get_rollout, test_policy class NNParams: ''' Defines the neural network architecture. Parameters: state_dim: int (continuous state dimension for nn input) action_dim: int (action space dimension for nn output) ...
12,738
3,909
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import subprocess def get_execution_parallism(): return 1 def do_native_translation_v2(codeset, **kwargs): kernel_name, in_args, out_args, body = codeset expand_args = ' '.join([f'{x[0]}* {x[1]} = ({x[0]}*)__args[{i}];' for i, x in enu...
640
253
import sys from pymod import index from pymod.index import modules from pymod.mappings import url out = lambda s: sys.stdout.write(s) out('{ ') dom = index.domof('https://docs.python.org/2/library/exceptions.html') for el in (el for el in dom.findAll('a', {'class': 'headerlink'}) if '-' not in el.attrs['...
408
148
import sqlite3 from collections import namedtuple from functional import seq with sqlite3.connect(':memory:') as conn: conn.execute('CREATE TABLE user (id INT, name TEXT)') conn.commit() User = namedtuple('User', 'id name') seq([(1, 'pedro'), (2, 'fritz')]).to_sqlite3( conn, 'INSERT INTO user...
878
339
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Settings for launch_jobs.py Test settings for automated tests. To test run with job scheduler @author: Matthias Göbel """ from run_wrf.configs.test.config_test import * from copy import deepcopy params = deepcopy(params) params["vmem"] = 500
298
109
s1 = "I am a beginner in python \nI will study the concepts to be familiar with this language.\nIt is a very user friendly language" print("The long string is: \n" + s1) # -- L1 s2 = """The long string is: I am a beginner in python I will study the concepts to be familiar with this language. It is a very user ...
362
112
#!/usr/bin/env python # $Id: setup.py 8864 2021-10-26 11:46:55Z grubert $ # Copyright: This file has been placed in the public domain. from __future__ import print_function import glob import os import sys try: from setuptools import setup except ImportError: print('Error: The "setuptools" module, which is r...
5,177
1,618
"""Tests the ``remove`` plugin.""" from unittest.mock import patch import pytest import moe @pytest.fixture def mock_rm(): """Mock the `remove_item()` api call.""" with patch("moe.plugins.remove.remove_item", autospec=True) as mock_rm: yield mock_rm @pytest.fixture def tmp_rm_config(tmp_config): ...
3,171
1,012
#Tyler Sorensen #February 15, 2012 #University of Utah #PyBool_builder.py #The interface to build recursive style boolean expressions #See README.txt for more information def mk_const_expr(val): """ returns a constant expression of value VAL VAL should be of type boolean """ return {"type" : "con...
2,089
716
#!/usr/bin/env python2 ''' A simple script to get the playback status of spotify. This script needs ``dbus-python`` for spotify communication To run simply:: ./spotify-monitor.py <command> Where command is one of the following:: ``playback`` ``playing`` ''' # pylint: disable=W0703 import dbus from db...
2,595
831
import sys sys.path.insert(0, '../Pyro4-4.17') import Pyro4 from time import clock """ log = open('pyro.log', 'w') times = [] proxy = Pyro4.Proxy("PYRO:example.service@localhost:54642") for i in range(100) : local = [] begin = clock() for files in proxy.getFiles(proxy.getcwd()) : for file in file...
787
303
from nose.tools import assert_equal from tests.fixtures import WebTest class TestDemoController(WebTest): pass
117
34
import sys import matplotlib import numpy as np # Avoid errors when running on headless servers. matplotlib.use('Agg') import matplotlib.pyplot as plt if len(sys.argv) != 6: print "Usage plot.py <data file port 1> <min size> <step size> <max size> <num packets sent>" sys.exit(1) width = 20 data_file = sys.ar...
1,358
487
import os import ssl from six.moves import urllib import torch import numpy as np import dgl from torch.utils.data import Dataset, DataLoader def download_file(dataset): print("Start Downloading data: {}".format(dataset)) url = "https://s3.us-west-2.amazonaws.com/dgl-data/dataset/{}".format( dataset) ...
2,678
990
# -*- coding: utf-8 -*- import string import random import logging import urllib2 from os import path from django.test import TestCase from django.core.files.base import ContentFile from s3 import upload from s3.storage import S3Storage from settings import BOTO_S3_BUCKET logger = logging.getLogger(__name__) local...
1,552
503
# -*- coding: utf-8 -*- # http://wiki.ros.org/Bags/Format/2.0 __all__ = ("BagPlayer",) import subprocess import threading from types import TracebackType from typing import Optional, Type import dockerblade from loguru import logger from ... import exceptions class BagPlayer: def __init__( self, ...
4,060
1,080
from functools import wraps from flask import request, make_response from .exceptions import ApiError from .schemas import create_schema, ma_version_lt_300b7 def request_schema(schema_or_dict, extends=None, many=None, cache_schema=True, pass_data=False): schema_ = create_schema(schema_or_dict, extends) def...
3,120
903
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.urls import path # Uncomment the next two lines to enable the admin: from django.contrib import admin from drf_yasg.views im...
1,447
502
# -*- coding: utf-8 -*- """ datagator.rest.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2015 by `University of Denver <http://pardee.du.edu/>`_ :license: Apache 2.0, see LICENSE for more details. """ import base64 from django.contrib.auth import authenticate, login from django.core.exceptions imp...
2,043
573
from getpass import getpass import socket COLORS = {"green" : "\33[92m", "red" : "\33[91m", "yellow" : "\33[93m", "endc" : "\33[0m" } def print_green(msg): """Prints msg in green text.""" print("{0}{1}{2}".format(COLORS["green"], msg, COLORS["endc"])) def print_yellow(ms...
2,836
879
import pandas as pd import numpy as np from collections import Counter data = pd.read_csv('out/negex_all.txt', sep="\t", header=None) print(data.shape) data.columns = ['PAT_DEID','NOTE_DEID','NOTE_DATE','ENCOUNTER_DATE','NOTE_CODE','TEXT_SNIPPET','lower_text','STATUS'] df = data.groupby(['PAT_DEID','NOTE_DEID','NOTE_...
1,244
499
from flask import Flask from flask import request from flask import jsonify from os import environ import query app = Flask(__name__) if 'MONGODB_HOST' in environ: mongodb_host = environ['MONGODB_HOST'] else: mongodb_host = "localhost" if 'MONGODB_PORT' in environ: mongodb_port = environ['MONGODB_PORT']...
821
281
from stack.m_decoded_string import DecodeString class TestDecodeString: def test_lc_data_1(self): ds = DecodeString() ans = ds.valueAtIndex_bf("leet2code3", 15) assert ans == "e" ans = ds.valueAtIndex_opm("leet2code3", 15) assert ans == "e" ans = ds.valueAtIndex_...
972
412
from pylab import plot, show, legend from numpy import array from h5py import File data = File("data.h5") iter = 2 R = array(data["/%04d/R" % iter]) rho = array(data["/%04d/rho" % iter]) Vtot = array(data["/%04d/V_tot" % iter]) Zeff = -Vtot * R #for i in range(1, 19): # P = array(data["/%04d/P%04d" % (iter, i)])...
534
248
# Generated by Django 3.1 on 2020-08-18 13:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.AddField( model_name='address', name='default_add', ...
379
124
class KACLValidationError(): def __init__(self, line="", line_number=0, start_character_pos=None, end_character_pos=None, error_message=""): self.__line_number = line_number self.__start_character_pos = start_character_pos self.__end_character_pos = end_character_pos self.__error_mes...
2,029
528
#!/usr/bin/python3 # Fabfile to delete out-of-date archives. import os from fabric.api import * env.hosts = ['104.196.116.233', '54.165.130.77'] def do_clean(number=0): """Delete out-of-date archives. """ number = 1 if int(number) == 0 else int(number) archives = sorted(os.listdir("versions")) [...
692
261
from tfrec.utils.model_utils import cross_validate from tfrec.utils.model_utils import preprocess_and_split __all__ = [ 'cross_validate', 'preprocess_and_split', ]
173
58
""" A threaded shared-memory scheduler for dask graphs. This code is experimental and fairly ugly. It should probably be rewritten before anyone really depends on it. It is very stateful and error-prone. That being said, it is decently fast. State ===== Many functions pass around a ``state`` variable that holds t...
17,316
5,502
# Generated by Django 3.1.1 on 2020-09-01 18:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('todoapp', '0002_auto_20200719_2021'), ] operations = [ migrations.AlterField( model_name='todo'...
495
187
from django.core.management.base import LabelCommand from yachter.courses.utils import export_static_html class Command(LabelCommand): help = "Export a static HTML/JSON website for browsing the courses." args = "exportPath" label = 'path to export dir' def handle_label(self, export_path, **options): ...
360
103
############################################################### # cms set host='juliet.futuresystems.org' # cms set user=$USER # # pytest -v --capture=no tests/test_01_job_cli.py # pytest -v tests/test_01_job_cli.py # pytest -v --capture=no tests/test_01_job_cli.py::TestJob::<METHODNAME> #############################...
6,163
1,924
import argparse import time from pathlib import Path from logger import get_logger from csv_reader import CSVReader from utils import infer_type, clear_console from sql_generator import SQLGenerator if __name__ == "__main__": ## Clear console clear_console() ## get logger logger = get_logger('pysql...
3,370
1,042
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if intervals is None or l...
854
254
from tkinter import * import mariadb root = Tk() root.title('SCHOOL MANAGEMENT') root.geometry("900x700") counter=2 for i in range(1,20): label=Entry(root).grid(row=counter,column=0) counter += 2 root.mainloop()
221
97
import flopy.mt3d as mt class SftAdapter: _data = None def __init__(self, data): self._data = data def validate(self): # should be implemented # for key in content: # do something # return some hints pass def is_valid(self): # should be im...
2,742
872
import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter from collections import namedtuple from typing import Dict from src.visualization import diminishing_reward_colors, PLOT_DPI StateAction = namedtuple('StateAction', 'id state action') def get_all_state_action(state_to...
2,089
771
class MOD: def __init__(self, Globals): """ This adds additional message categories to the player detection algorithm """ # data transfer variables self.Globals = Globals self.G = self.Globals self.ModData = Globals.ModData["Chatpp"] self.backend = Globals.ui_backend ...
5,626
1,526
import time import sys import threading import asyncio # fly from .ModelBootstrap import ModelBootstrap from . import ModelManager def bootstrap(_filename,): #Model Bootstrap runForEver = threading.Event() mb = ModelBootstrap(filename=_filename,) runForEver.wait() #runForEver = threading.E...
520
176
import feedparser def parseRSS(rss_url): return feedparser.parse(rss_url) def getHeadLines(rss_url): headlines = [] feed = parseRSS(rss_url) for newitem in feed['items']: headlines.append(newitem['title']) return headlines allheadlines = [] newsurls={'googlenews': 'https://news.goo...
569
208
from behave import when, then from application.models import Member @when(u'I request \'{page}\'') def step_impl(context, page): context.response = context.test.client.get(page) @when(u'there are no members') def step_impl(context): Member.objects.all().delete() @then(u'I see \'{content}\'') def step_imp...
664
228
""" Displaying the fields in an xy cross section of the sphere (x polarized light, z-propagating) """ import numpy as np import matplotlib.pyplot as plt import miepy from mpl_toolkits.mplot3d import Axes3D import matplotlib.cm as cm Ag = miepy.materials. Ag() # calculate scattering coefficients, 800 nm illumination ...
2,824
1,398
import datetime import dateutil.parser import xml import xml.etree.ElementTree from pya2a.utils import parseRemark class Entity: NAMESPACE = {"a2a": "http://Mindbus.nl/A2A"} class Person(Entity): """ """ def __init__(self, element: xml.etree.ElementTree.Element): self.id = element.attrib...
13,616
4,004
import numpy as np min, max = -0.8777435, 0.57090986 M = np.asmatrix([ [0.02355068, -0.50542802, 0.16642167, -0.44872788, -0.05130898, 0.13320047, 0.41464597, -0.55703336, 0.52567458, 0.23784444, 0.15049535, 0.16599870, -0.28757980, 0.22277315, 0.56460077, -0.70838273, -0.61990398, -0.39724344, -0.09969769, 0.4583...
4,059
3,748
# Aula 09 - Manipulando de cadeias de texto (Strings) """ Técnica de Fatiamento Frase = Curso em Video Python Frase [9]: letra específica Frase [9:13]: Vai pegar do 9 ao 12 (menos um no final) Frase [9:21:2]: Pula de 2 em 2 Frase [:5]: Irá começar no primeiro caracter e terminar no 4 (excluindo o número 5) Frase [15:...
3,391
1,228
import optuna from {{cookiecutter.repo_name}}.utils import check_args_num, \ read_config, set_random_seed, str_hash, file_hash from {{cookiecutter.repo_name}}.settings import optuna_db_path def read_inp_file(filepath): raise NotImplementedError def write_output(out, filepath): raise NotImplementedError ...
2,575
863
# - *- coding: utf- 8 - *- """ Bot to suggest music from Spotify based on your mood. """ import spotipy, os from spotipy.oauth2 import SpotifyClientCredentials from telegram.ext import Updater, CommandHandler, MessageHandler, Filters #from access_token import AUTH_TOKEN, CLIENT_ID, CLIENT_SECRET # Intialise spotipy cl...
2,221
696
# Copyright (c) 2019, Danish Technological Institute. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # -*- coding: utf-8 -*- """ Utility code to locate tracker projects """ from tracker.tracker_file import Tra...
1,544
479
""" Python API for Hacker News. @author Karan Goel @email karan@goel.im """ __title__ = 'hackernews' __author__ = 'Karan Goel' __license__ = 'MIT' __copyright__ = 'Copyright 2014 Karan Goel' from .hn import HN, Story
220
92
ACCURACY = 0 MATTHEWS_CORRELATION_COEFFICIENT = 1 AUC = 2
57
36
''' Advent of Code 2017 Day 6: Memory Reallocation ''' import unittest TEST_BANKS = ('0 2 7 0', 5, 4) INPUT_BANKS = '0 5 10 0 11 14 13 4 11 8 8 7 1 4 12 11' def findInfiniteLoop(memoryBanks): ''' Finds the number of iterations required to detect an infinite loop with the given start condition. memoryBa...
2,580
826
""" Utility Methods for Authenticating against and using Indiana University CAS. """ import httplib2 from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.conf import settings def validate_cas_ticket(casticket, casurl): """ Takes a CAS Ticket and makes th...
1,757
530
# -*- coding: utf-8 -*- from django.http import JsonResponse from decimal import Decimal from datetime import datetime, timedelta import re import logging from disqusapi import DisqusAPI from django.contrib import messages from django.apps import apps from django.core.mail import mail_admins from django.core.urlresolv...
20,460
5,976
import serial import string import math from itertools import chain class robot: address = "/dev/cu.HC-05-DevB" speed = 0; current_position = [0,0,0] target_position = [0, 0] distance = 0; angle_diff = 0; compliment = 0; colorLower = [0,0,0] colorUpper = [0,0,0] ID = 0 # def __init__ (self): # pass #...
3,177
1,334
from discord import TextChannel, User from discord.ext.commands import Bot from .configuration import CONF0 from tqdm.asyncio import tqdm # class LogMe: # """This is a complicated logger I came up with.\n # Feel free to insult me whilst readding it.""" # _std = { # "LS": "|-----------------Log_ ST...
4,054
1,114
""" test_django-oci api ------------------- Tests for `django-oci` api. """ from django.urls import reverse from django.contrib.auth.models import User from django_oci import settings from rest_framework import status from rest_framework.test import APITestCase from django.test.utils import override_settings from tim...
13,930
4,231
#LCST Plotter #Author: ESTC import numpy import streamlit import matplotlib.pyplot as plt import pandas def launch_app(): streamlit.title("LCST Plotter") global cation, anion, mw_cat, mw_an, datafile cation = streamlit.text_input("Enter the abbreviation of the cation:") # mw_cat = streaml...
1,492
602
#!/usr/bin/env python3 from flask import Flask, render_template, app, url_for,request import tweepy # To consume Twitter's API import pandas as pd # To handle data import numpy as np # For number computing from textblob import TextBlob import re import pandas as pa from sklearn.tree import DecisionTr...
13,039
4,388
import torch def save_param(model, pth_path): ''' save the parameters of the model Args: model: the model to which the params belong pth_path: the path where .pth file is saved ''' torch.save(model.state_dict(), pth_path) def load_param(model, pth_path): ''' load t...
529
171
#Project Euler Problem-77 #Author Tushar Gayan #Multinomial Theorem import math import numpy as np def mod_list(pow,terms): m = [] for i in range(terms): if i%pow == 0: m.append(1) else: m.append(0) return m[::-1] def prime_check(num): i...
1,348
516