text
string
size
int64
token_count
int64
import sys from setuptools import setup, find_packages setup( name='pynomial', version='0.0.0', packages=find_packages(), author='Paul M Dodd', author_email='pdodd@umich.edu', description="python package for combinatorial problems", url="https://github.com/PaulDodd/pynomial.git", instal...
377
120
"""empty message Revision ID: 35099fc974d2 Revises: ae00e7974dca Create Date: 2017-05-19 17:01:48.878196 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '35099fc974d2' down_revision = 'ae00e7974dca' branch_labels = None depends_on = None def upgrade(): op...
830
341
from randomSets import * import numpy as np winners = [1,5,10] candidates = range(100, 1100, 500) Nmin = np.zeros((len(winners),len(candidates))) for i in range(len(winners)): for j in range(len(candidates)): print("Nwinner: %i, Ncandidates: %i" % (winners[i], candidates[j])) #alpha = findMinAlpha(...
658
310
from drs4Calibration.drs4Calibration_version_0.constants import NRCELL, ROI # Dont shuffle drsValueTypes # The order have to be the same as the of the 'RUNIDs' # in the drsFiles drsValueTypes = ['Baseline', 'Gain', 'TriggerOffset'] renamedDrsValueTypes = ['Baseline', ...
894
319
class Player(object): """Player class Attributes: name (str): Player name """ def __init__(self, name): """Initialize player Args: name (str): Player name """ self.name = name def place_troops(self, board, n_troops): """Plac...
1,854
494
n=int(input("Nhap vao mot so:")) d=dict() for i in range(1, n+1): d[i]=i*i print(d)
91
48
"""GUI for taking tests based on quizme-xxx.json files. """ import os import sys import json from random import randint import tkinter as tk from tkinter import font from tkinter import ttk from tkinter import filedialog from tkinter import messagebox from widgetrefs import widgets def center_window(window): """...
18,085
5,644
"""``AppendableExcelDataSet`` loads/saves data from/to a local Excel file opened in append mode. It uses pandas to handle the Excel file. """ from copy import deepcopy from pathlib import Path, PurePosixPath from typing import Any, Dict import pandas as pd from kedro.io.core import AbstractDataSet, DataSetError cla...
5,448
1,581
def test_import(): import std_system
42
14
#!/usr/bin/env python # Copyright 2008-2010 Isaac Gouy # Copyright (c) 2013, 2014, Regents of the University of California # Copyright (c) 2017, 2018, Oracle and/or its affiliates. # All rights reserved. # # Revised BSD license # # This is a specific instance of the Open Source Initiative (OSI) BSD license # template h...
3,360
1,210
from .makeFullPdf import makeFullPdf from .parseImage import parseImage from .makePdf import makePdf import requests,os,os.path,sys,time,json from bs4 import BeautifulSoup def readComicsOnlineRu(): while True: try: with open('config.json', 'r', encoding="utf-8") as f: books = json.load(f) library=[*books[...
3,150
1,341
from . import subnetCal from . import functions from random import randint def IP(cidr): arr=subnetCal.simpleCalculate(cidr) min_host=arr[3] smin_host=min_host.split(".") max_host=arr[4] smax_host=max_host.split(".") ip="" for i in range(4): if(smin_host[i]==smax_host[i]): ...
828
333
# -*- coding: utf-8 -*- # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
1,182
371
import sys import pickle from krips_alpha import krippendorff_alpha, nominal_metric def get_model_labels(model_output): model_labels = [] for x in model_output: try: if x['pos_score'] > x['neg_score']: model_labels.append('0') elif x['neg_score'] > x['pos_score']: model_labels.append('1') else: ...
940
383
__all__ = [ 'ServoController', 'TimeoutError', 'SERVO_ERROR_OVER_TEMPERATURE', 'SERVO_ERROR_OVER_VOLTAGE', 'SERVO_ERROR_LOCKED_ROTOR', ] from serial.serialutil import * from functools import partial import threading import logging SERVO_ID_ALL = 0xfe SERVO_MOVE_TIME_WRITE = 1 SERVO_MOVE_TIME_R...
10,392
3,726
# Problem: Student Attendance Record I # Difficulty: Easy # Category: String # Leetcode 551: https://leetcode.com/problems/student-attendance-record-i/#/description # Description: """ You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : ...
1,223
487
#!/usr/bin/env python import argparse import os import platform import re import shutil import subprocess import sys SUPPORTED_VERSIONS = ('3.6', '3.7') IS_DEBIAN = platform.system() == 'Linux' and os.path.exists('/etc/debian_version') IS_OLD_UBUNTU = (IS_DEBIAN and os.path.exists('/etc/lsb-release') ...
10,454
3,255
import numpy as np from sklearn.metrics import average_precision_score as ap from sklearn.metrics import roc_auc_score """ each row is an instance each column is the prediction of a class """ def _score_to_rank(score_list): rank_array = np.zeros([len(score_list)]) score_array = np.array(score_list) idx_so...
3,463
1,269
""" :filename transformations.py :author Tibor Kubik :email xkubik34@stud.fit.vutbr.cz from Classes of custom transformations that are applied during the training as additional augmentation of the depth maps. """ import torch import random import numpy as np import torch.nn.functional as F from random...
6,114
1,882
class Solution: def bitwiseComplement(self, N: int, M = 0, m = 0) -> int: return N ^ M if M and M >= N else self.bitwiseComplement(N, M + 2 ** m, m + 1)
164
65
import random import shutil import sys from argparse import ArgumentParser from os import path from pathlib import Path from threading import Thread from PySide6 import __version__ as PySideVer from PySide6.QtCore import (Property, QCoreApplication, QObject, Qt, QTimer, Signal, Slot) from P...
5,691
1,816
import astropy.units as u import numpy as np from lofti_gaia.loftitools import * from lofti_gaia.cFunctions import calcOFTI_C #from loftitools import * import pickle import time import matplotlib.pyplot as plt # Astroquery throws some warnings we can ignore: import warnings warnings.filterwarnings("ignore") '''This mo...
48,459
16,289
from src.data_curation.dataset_manager import get_meta import pandas as pd def view_all(): return get_meta() def get_docs(id): df = get_meta() docs = df[df["id"] == id]["docs"].iloc[0] df = pd.read_json(docs) return df
243
92
from .gradient_reversal import GradientReversal from .noise import Noise, AdditiveNoise, MultiplicativeNoise
109
35
# -*- coding: utf-8 -*- """ 查看 django.db.backends.mysql.base.by 源码发现 django 连接 mysql 时没有使用连接池, 导致每次数据库操作都要新建新的连接并查询完后关闭,更坑的是按照 django 的官方文档设置 CONN_MAX_AGE 参数是为了复用连接,然后设置了 CONN_MAX_AGE 后,每个新连接查询完后并不 会 close 掉,而是一直在那占着。如果在高并发模式下,很容易出现 too many connections 错误。故重写 mysql 连接库,实现连接池功能。 """ from django.core.exceptions import I...
2,344
925
# flowbyfunctions.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Helper functions for flowbyactivity and flowbysector data """ import pandas as pd import numpy as np from esupy.dqi import get_weighted_average import flowsa from flowsa.common import fbs_activity_fields, US_FIPS, get_state_FIPS, \ get_county...
34,758
10,626
import numpy as np # gradient descent는 tensorflow에 이미 구현이 되어있다. # 확률적 선형 뉴런 분석기는 각 훈련 샘플에 대해서 조금씩 가중치를 업데이트 한다. class AdalineSGD(object): """Adaptive Linear Neuron 분류기 매개변수 ------------ eta : float 학습률 (0.0과 1.0 사이) n_iter : int 훈련 데이터셋 반복 횟수 shuffle : bool (default ...
3,553
2,145
#2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. time = int(input("Введите время в секундах ")) hours = time // 3600 minutes = (time - hours * 3600) // 60 seconds = time - (hours * 3600 + minutes * 60) print...
383
176
from toee import * import char_class_utils ################################################### def GetConditionName(): return "Archmage" def GetSpellCasterConditionName(): return "Archmage Spellcasting" def GetCategory(): return "Core 3.5 Ed Prestige Classes" def GetClassDefinitionFlags(): return CDF_CoreClass...
2,259
898
from rest_framework import status from rest_framework.exceptions import APIException class PreconditionFailed(APIException): status_code = status.HTTP_412_PRECONDITION_FAILED default_detail = "An HTTP precondition failed" default_code = "precondition_failed" class BadRequest(APIException): status_co...
427
126
"""Train a video classification""" import torch import sesame.models.losses as losses import sesame.models.optimizer as optim import sesame.utils.distributed as du import sesame.utils.misc as misc import sesame.utils.metrics as metrics import sesame.utils.logger as logger from sesame.datasets.mixup import MixUp log ...
11,749
3,666
import os import setuptools VERSION = "1.0.0a1+dev" INSTALL_REQUIRES = [ 'pip-licenses', ] CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research' ] def read(fname): return open(os.path.join(os.path.dirname(__file__), fname))....
846
305
from django.contrib import admin from parents.models import Guardian admin.site.register(Guardian)
101
28
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: missingdata.py # # Tests: missing data # # Programmer: Brad Whitlock # Date: Thu Jan 19 09:49:15 PST 2012 # # Modifications: # # ------------------------------------------------------------...
1,912
732
from pathlib import Path current_path = Path(".") datafolder = current_path / "data" imagefolder = current_path / "images" if not datafolder.exists(): print(f"Creating {datafolder}/...") datafolder.mkdir() if not imagefolder.exists(): print(f"Creating {imagefolder}/...") imagefolder.mkdir() print("S...
540
175
import falcon.testing import pytest import json from displacy_service.server import APP, MODELS model = MODELS[0] @pytest.fixture() def api(): return falcon.testing.TestClient(APP) def test_deps(api): result = api.simulate_post( path='/dep', body='{{"text": "This is a test.", "model": "{m...
4,521
1,552
#!/usr/bin/env python import random import argparse def generate_passwords(password_file_path): password_file = open(password_file_path, 'w') chars = 'abcdefghijklmnopqrstuvxyz01234567890_-!*' secret_key = ''.join(random.SystemRandom().choice(chars) for _ in range(50)) password_file.write("SECRET_KEY ...
606
212
import sys import torch import numpy as np from torch import optim from util import args class CarliniL2: def __init__(self, targeted=True, search_steps=None, max_steps=None, cuda=True, debug=False, num_classes=14): self.debug = debug self.targeted = targeted self.num_classes = num_class...
13,354
4,042
# Generated by Django 3.2.5 on 2022-02-18 08:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("dataset", "0001_initial"), ("cueSearch", "0004_auto_20220217_0217"), ] operations = [ migrations.Ad...
639
206
""" Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the followin...
629
225
from __future__ import annotations from django.template.loader import render_to_string from .conf import settings def django_sys_indicator_tag() -> str: template_name = 'django_sys_indicator/system_indicator.html' try: color, border_color = settings.SYSTEM_INDICATOR_COLORS[ settings.SYS...
675
209
n1 = int(input('Digite um número entre 0 e 9999: ')) u = n1 // 1 % 10 d = n1 // 10 % 10 c = n1 // 100 % 10 m = n1 // 1000 % 10 print(f'Analisando o número {n1}') print(f'unidade: {u}') print(f'dezena: {d}') print(f'centena: {c}') print(f'milhar: {m}')
262
153
from typing import List, Dict from aiohttp import web from openapi_server.models.edr_feature_collection_geo_json import EdrFeatureCollectionGeoJSON from openapi_server.models.exception import Exception from openapi_server.models.one_ofobjectobject import OneOfobjectobject from openapi_server import util async def li...
3,366
969
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import os # In[2]: #function to get current directory def getCurrentDirectory(): listDirectory = os.listdir('../') return listDirectory # In[3]: #function to read csv file def readCsvFile(path): crimes_original =...
904
310
from microtbs_rl.algorithms.common.agent import AgentLearner from microtbs_rl.algorithms.common.loops import run_policy_loop
125
41
import sys from collections.abc import Mapping import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use a service account cred = credentials.Certificate('./service-account-key.json') firebase_admin.initialize_app(cred) db = firestore.client() for row in sys.stdin: ...
806
272
from BaseHandler import BaseHandler, user_required class ManageSubscriptionHandler(BaseHandler): @user_required def get(self): self.render_template('manage_subscription.html')
192
52
import torch import torch.nn as nn class SpaceTime(nn.Module): def __init__(self, opts): # TODO: Add things like no. of hidden layers to opts pass class LSTM(nn.Module): # This class is largely derived from # https://stackabuse.com/time-series-prediction-using-lstm-with-pytorch-in-python...
1,228
405
#!/usr/bin/env python """ Commands related to syncing copytext from Google Docs. """ from fabric.api import task from termcolor import colored import app_config from etc.gdocs import GoogleDoc @task(default=True) def update(): """ Downloads a Google Doc as an Excel file. """ if app_config.COPY_GOOGL...
934
313
import tensorflow as tf import numpy as np import math # Parameter order_num=2; class Program: def __init__(self,sess,state_dim,obj_num,fea_size,Theta,program_order,postfix): self.sess = sess; self.state_dim = state_dim; self.fea_size=fea_size; self.obj_num=obj_num; self.order_num=order_num; ...
4,699
2,013
#!/usr/bin/env python import sys import matplotlib import numpy as np import random import itertools import socket import sklearn.metrics from scipy.optimize import minimize from scipy.optimize import Bounds from sklearn import preprocessing from sklearn.preprocessing import OneHotEncoder from sklearn.utils.random im...
3,161
1,660
# # CAMP # # Copyright (C) 2017, 2018 SINTEF Digital # All rights reserved. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # from unittest import TestCase from camp.commands import Command, Generate class DefaultValuesAreCorrect(TestCase...
2,645
782
#!/usr/bin/env python # =========================================================================== # Copyright 2017 `Tung Thanh Le` # Email: ttungl at gmail dot com # Heterogeneous Architecture Configurations Generator for Multi2Sim simulator # (aka, `HeteroArchGen4M2S`) # `HeteroArchGen4M2S` is free software, which...
4,757
1,936
""" """ import os from flask import current_app from canvasapi import submission, requester from app.wall_e.models.requester import Requester from app.settings import settings class Canvas(Requester): """ Model class for wall_e.fetch """ def __init__(self, base_url, api_token, course_id, course_name)...
7,475
2,234
from django.shortcuts import render # Create your views here. # chat/views.py from django.shortcuts import render from django.utils.safestring import mark_safe import json from chat.models import Room def index(request): # from channels.layers import get_channel_layer # from asgiref.sync import async_to_sync ...
908
343
import os from sqlalchemy import (Column, DateTime, Integer, MetaData, String, Text, Table, create_engine) from sqlalchemy.sql import func from databases import Database DATABASE_URL = os.getenv("DATABASE_URL") # SQLAlchemy engine = create_engine(DATABASE_URL) metadata = MetaData() movies =...
806
236
from ctypes import cdll, c_char_p, c_size_t, c_void_p, Union,\ LittleEndianStructure, c_char, POINTER,\ c_int, byref, CFUNCTYPE, create_string_buffer class greshunkel_var(Union): _fields_ = [ ("str", c_char * 513), ("arr", c_void_p), ("sub_c...
3,224
1,253
from collections import OrderedDict from asyncio import TimeoutError, wait from concurrent.futures import FIRST_COMPLETED import time from discord import TextChannel, DMChannel from discord.errors import Forbidden, NotFound from objects.context import Context class PaginatorABC: def __init__(self, bot, looped...
11,443
3,247
from __future__ import unicode_literals import os import boto3 import sure # noqa from freezegun import freeze_time from unittest import SkipTest from moto import mock_managedblockchain, settings from . import helpers @mock_managedblockchain def test_vote_on_proposal_one_member_total_yes(): conn = boto3.clien...
21,362
6,892
""" 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ # %% class Solution: def twoSum(self, nums, target): S = set(nums) for num in S: pre = ...
752
384
from __future__ import print_function import numpy as np def rebin_xyz(arr, bin_factor, fill_value=None): """ Function to rebin masked 3d array. Parameters ---------- arr : ndarray Masked or unmasked 3d numpy array. Shape is assumed to be (nz, ny, nx). bin_factor : int bin...
3,306
1,258
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2018. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """Function implementation""" import os import logging import time import shlex import subprocess import json import chardet import winrm import re from resilient_circuits import Resilien...
9,095
2,269
# Generated by Django 2.0.1 on 2018-07-26 12:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0009_auto_20180726_1214'), ] operations = [ migrations.AddField( model_name='project', name='email', ...
428
156
from games import (GameState, Game, query_player, random_player, alphabeta_player, play_game, minimax_decision, alphabeta_full_search, alphabeta_search) class Othello(Game): """Juega Othello en un tablero 8 x 8, con Max (primer jugador) jugando con las fichas negras....
5,512
1,797
import time import re from FileLogger import FileLogger as FL import datetime class GetCommentTask: def __init__(self, task, name="extract-comment"): self.task = task self.name = name self.comments = [] self.log = FL('Extracted Comments {:%Y-%m-%d %H:%M:%S}.txt'.format(datetime.da...
2,165
686
""" script to run mc sims on the three associations techniques when the tracks origin are equal. Used to calculate the total number of correctly associating tracks and total # falsly not associating tracks from the same target. """ import numpy as np from stonesoup.types.state import GaussianState from data_associati...
4,981
1,527
""" Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: c4-system-manager This project is licensed under the MIT License, see LICENSE """ from abc import ABCMeta, abstractmethod class DeviceHistory(object): """ Device manager history """ __metaclass__ = ABCMeta @abstractmethod def...
4,405
1,135
class SerialNumber: def __init__(self, serialNumber): if not (len(serialNumber) == 6): raise ValueError('Serial Number must be 6 digits long') self._serialNumber = serialNumber def __str__(self): return 'S/N: {}'.format(self._serialNumber) def __repr__(self): ...
1,060
331
import json import operator import logging import re import time from socket import socket, AF_INET, SOCK_DGRAM from functools import reduce logger = logging.getLogger(__name__) def ip(): """Find default IP""" ip = None s = socket(AF_INET, SOCK_DGRAM) try: s.connect(('239.255.0.0', 9)) ...
5,876
1,809
#!/usr/bin/env python3 # import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import argparse import Libraries.arguments as ar import Libraries.tools.general as gt import Libraries.tools.zabbix as zt import Classes.AppConfig as AppConfig import requests import copy def r...
6,168
1,967
from firebase_admin import firestore from google.cloud.firestore_v1.base_client import BaseClient from ..core.app import App class DBConnection(App): def __init__(self) -> None: super().__init__() self.__db: BaseClient = firestore.client() def getDBInstance(self) -> BaseClient: retur...
332
98
if __name__ == '__main__': a, b, m = int(input()),int(input()),int(input()) print(pow(a,b)) print(pow(a,b,m))
124
56
from test_autolens.integration.tests.imaging.lens_only import lens_light__hyper_bg_noise from test_autolens.integration.tests.imaging.runner import run_a_mock class TestCase: def _test__lens_light__hyper_bg_noise(self): run_a_mock(lens_light__hyper_bg_noise)
273
101
from numpy import exp, pi, cos, sin, tan from ....Functions.Geometry.inter_line_circle import inter_line_circle def _comp_point_coordinate(self): """Compute the point coordinates needed to plot the Slot. Parameters ---------- self : HoleM51 A HoleM51 object Returns ------- point_...
3,047
1,451
print("\n") print("PythonExercises-v2 by David Bochan") print("\n") print("=== EXERCISE 1 ===") print("\n") print("(a) 5 / 3 = " + str(5 / 3)) print("=> with python3 you can receive a float even if you divide two \ integers") print("\n") print("(b) 5 % 3 = " + str(5 % 3)) print("=> % is the modulus which divides lef...
8,700
3,449
"""Plot USGS geomag data.""" import argparse import pathlib as pl import datetime as dt import matplotlib; matplotlib.use('cairo') import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mticker import requests import pandas as pd import funcs funcs.check_cwd(pl.Path.cwd()) DTG_F...
5,774
2,387
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck class PodSecurityContext(BaseResourceCheck): def __init__(self): # CIS-1.5 5.7.3 name = "Apply security context to your pods and containers" ...
2,178
582
from machine import I2C # i2c = I2C(I2C.I2C0, freq=100000, scl=28, sda=29) # hardware i2c i2c = I2C(I2C.I2C3, freq=100000, scl=28, sda=29) # software i2c devices = i2c.scan() print(devices) for device in devices: i2c.writeto(device, b'123') i2c.readfrom(device, 3) # tmp = bytearray(6) # i2c.readfrom_...
345
184
from leapp.models import fields, Model from leapp.topics import SystemInfoTopic, TransactionTopic class SELinuxModule(Model): """SELinux module in cil including priority""" topic = SystemInfoTopic name = fields.String() priority = fields.Integer() content = fields.String() # lines removed due ...
1,431
398
__author__ = 'jeffrey.starr@ztoztechnologies.com' from .infer import infer
76
30
#!/usr/bin/python3 # -*- coding: utf-8 -*- import argparse import base64 from bson import ObjectId import datetime from flask import Flask, Markup, Response, abort, escape, flash, redirect, \ render_template, request, url_for from flask_login import LoginManager, UserMixin, current_user, login_requir...
21,902
6,392
from .meta import Interface from .release import version as __version__
72
17
import dash import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html import pandas as pd import plotly.express as px import plotly.graph_objs as go from datetime import date import dash_loading_spinners as dls from dash.dependencies import Input, Output, ClientsideF...
11,934
3,691
import sys import os import glob import pprint import numpy as np try: import PyQt4.QtGui as QtGui from PyQt4.QtGui import QFileDialog except: import PyQt5.QtGui as QtGui from PyQt5.QtWidgets import QFileDialog from ibeatles.utilities.load_files import LoadFiles, LoadTimeSpectra from ibeatles.utilitie...
9,755
2,816
# Copyright 2021 Touca, Inc. Subject to Apache-2.0 License. from ._types import IntegerType, VectorType, ToucaType from datetime import datetime, timedelta from enum import Enum from typing import Dict, Tuple class ResultCategory(Enum): """ """ Check = 1 Assert = 2 class ResultEntry: """ Wrapp...
10,719
2,884
from datetime import datetime import sqlalchemy as sa from flask_sqlalchemy import Model from sqlalchemy import ForeignKey from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship from app.main.extensions import db class BaseMixin(Model): def save_to_db(self): try: ...
1,376
421
#------------------------------------------------------------------------------- # This function defines the sea level change timeseries for marine ice sheet problem. # *Default = sinusoidal tidal cycle if 'tides' with 1m amplitude if 'tides' turned 'on', OR... # = zero if 'tides' turned 'off' #---------------...
759
204
#Usage: python nucleotidefrequencies.py <fasta file> <output file> #Output is tab delimited frequencies of A, G, C, U from Bio import SeqIO import sys def getfreqs(fasta): freqs = [] #[afreq, gfreq, cfreq, ufreq] a = 0 u = 0 c = 0 g = 0 tot = 0 for record in SeqIO.parse(fasta, 'fasta'): seq = str(record.seq....
1,397
663
version = "20.1"
17
10
import numpy as np from matplotlib import pyplot as plt from optsvm.svm import SVM x_neg = np.array([[3, 4], [1, 4], [2, 3]]) y_neg = np.array([-1, -1, -1]) x_pos = np.array([[6, -1], [7, -1], [5, -3]]) y_pos = np.array([1, 1, 1]) x1 = np.linspace(-10, 10) x = np.vstack((np.linspace(-10, 10), np.linspace(-10, 10))) #...
2,311
1,227
from typing import List, Dict from ts.c_syntax import CSyntax from ts import Tree from cfa import CFANode, CFA, CFAEdge from cfa import LocalisedCFA, LocalisedNode from .tweet_handler import TweetHandler from .decoration_strategy import StandardDecorationStrategy, DecorationStrategy from .conversion_strategy import Co...
3,574
1,081
# dicom_series.py """ By calling the function read_files with a directory name or list of files as an argument, a list of DicomSeries instances can be obtained. A DicomSeries object has some attributes that give information about the serie (such as shape, sampling, suid) and has an info attribute, which is a pydi...
22,550
6,757
# Copyright 2020 Graphcore Ltd. from pathlib import Path import pytest # NOTE: The import below is dependent on 'pytest.ini' in the root of # the repository from examples_tests.test_util import SubProcessChecker working_path = Path(__file__).parent class TestBuildAndRun(SubProcessChecker): def setUp(self): ...
1,216
343
import codecs import locale from mailbox import mbox from re import sub from re import compile from re import IGNORECASE from datetime import datetime from collections import Counter class MailboxStatistics(object): def __init__(self): """ Generic MailboxStatistics object that contains the statistics calc...
4,719
1,411
from PIL import Image import imagehash from dotenv import load_dotenv load_dotenv() import google_streetview.api import os from shapely.geometry import shape, Polygon, Point def get_point_photo(coords, download_folder): # Define parameters for street view api params_0 = [{ 'size': '640x640', # max 640x640 pixels ...
3,787
1,607
import re import copy import random changes = {} chain = "" lines = open('input.txt').readlines() moreChanges = True for l in lines: l = l.strip() if moreChanges and l != "": x = l.split("=>") if x[0].strip() not in changes.keys(): changes[x[0].strip()] = [] changes[x[0].str...
1,044
398
# Generated by Django 2.2.16 on 2020-09-29 23:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='Meetup', fields=[ ('id', mod...
1,102
324
from .resources.config import config from .utils import reverse_endianness from abc import ABC from abc import abstractmethod from logging import getLogger from logging import Logger from time import sleep from typing import Final import re import serial class ICardReader(ABC): """Class representation of card r...
4,124
1,107
import dateutil import yaml import feedparser as fp import newspaper as np from medios.medio import Medio from medios.diarios.noticia import Noticia from bd.entidades import Kiosco class Diario(Medio): def __init__(self, etiqueta): Medio.__init__(self, etiqueta) self.noticias = [] self.f...
2,754
867
# # BitBake Graphical GTK User Interface # # Copyright (C) 2012 Intel Corporation # # Authored by Shane Wang <shane.wang@intel.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundat...
1,230
452