content
stringlengths
0
894k
type
stringclasses
2 values
import os from rpython.rtyper.lltypesystem import lltype, llmemory, rffi from rpython.rlib.rposix import is_valid_fd from rpython.rlib.rarithmetic import widen, ovfcheck_float_to_longlong from rpython.rlib.objectmodel import keepalive_until_here from rpython.rtyper.annlowlevel import llhelper from pypy.interpreter.err...
python
from .CreateSource import CreateSource from .DropSource import DropSource from .InputKeys import InputKeys from .OutputKeys import OutputKeys from .ProducedKeys import ( ProducedKeys, ProducedLinkKeys, ProducedHubKeys ) from .SatelliteQuery import SatelliteQuery from .SerialiseSatellite import SerialiseSate...
python
"""Array with time epochs """ # Standard library imports from collections import namedtuple from datetime import datetime, timedelta from typing import Callable, Dict, List, Optional, Tuple, Any, TypeVar from functools import lru_cache try: import importlib.resources as importlib_resources # Python >= 3.7 except ...
python
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) p = list(map(int, input().split())) from collections import deque _min = 0 used = set() num = deque(range(1, 200000 + 2)) for v in p: used.add(v) if _min not in used: print(_min) else: while num: ...
python
class Solution: def plusOne(self, digits): length = len(digits) for i in range(length - 1, -1, -1): if digits[i] < 9: digits[i] += 1 return digits digits[i] = 0 return [1] + [0] * length
python
# coding: utf-8 # **Appendix D – Autodiff** # _This notebook contains toy implementations of various autodiff techniques, to explain how they works._ # # Setup # First, let's make sure this notebook works well in both python 2 and 3: # In[1]: # To support both python 2 and python 3 from __future__ import absolu...
python
from django.db import models # from django.contrib.auth.models import User from django.contrib.auth import get_user_model as user_model User = user_model() from apps.lobby.main.models import Lobby class Room(models.Model): title = models.CharField(max_length=30, primary_key=True) description = models.CharField...
python
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2016 Aarón Abraham Velasco Alvarez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rig...
python
""" Npy module This module implements all npy file management class and methods ... Classes ------- Npy Class that manages npy file's reading and writing functionalities """ import numpy as np import os class Npy(object): """ Class that manages npy file's reading and writing functionalities Methods ...
python
from machine import I2C import LIS2MDL i2c = I2C(1) mdl = LIS2MDL.LIS2MDL(i2c) mdl.x() mdl.get()
python
#!/usr/bin/env python3 #================== # gmail_pycamera #================== import os import json import datetime import shutil from devices import CameraMount from h264tomp4 import h264tomp4 from gmail import Gmail from command import parse_command class GmailPiCamera: """ gmail_picamera """ de...
python
# Generated by Django 3.2.8 on 2021-11-02 22:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('annotations', '0004_auto_20211102_1819'), ] operations = [ migrations.RemoveField( model_name='imagegroup', name='gr...
python
import unittest import solver from solver import sort_colors class TestSolver(unittest.TestCase): def test_sort_colors(self): self.assertEqual(sort_colors([0, 0, 0, 0, 0, 0]), [0, 0, 0, 0, 0, 0]) self.assertEqual(sort_colors([2, 2, 2, 2, 2, 2]), [2, 2, 2, 2, 2, 2]) self.assertEqual(sort_colors([0, 0, 2, ...
python
from django import template from raids.utils import get_instances register = template.Library() def get_loot_history(character): # Only filters items for main specialization -> where entitlement is set for the characters specialization # Dict for easy checking if instance is already a key instances = {in...
python
# Copyright (c) Open-MMLab. All rights reserved. from .checkpoint import (_load_checkpoint, load_checkpoint, load_state_dict, save_checkpoint, weights_to_cpu) from .dist_utils import get_dist_info, init_dist, master_only from .hooks import (CheckpointHook, ClosureHook, DistSamplerSeedHook, Hook...
python
# Standard imports from types import SimpleNamespace import numpy as np from scipy import optimize from scipy import stats from scipy import random from scipy.stats import beta import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') #Constructing grid of x and q in specific ranges q_values = np.linspace(0...
python
from core.config.setting import static_setting from core.resource.pool import ResourceSetting static_setting.setting_path = "/Users/lilen/mySetting" ResourceSetting.load() print(f"资源文件路径{ResourceSetting.resource_path}") print(f"配置文件路径{ResourceSetting.setting_path}") ResourceSetting.resource_path = "/User/user/new_res...
python
import pygame from settings import * class Entity: def __init__(self, x, y, w, h, speed, begin_act): self.x = x self.y = y self.w = w self.h = h self.rect = pygame.Rect(x, y, w, h) self.life = 100 self.life_rect = pygame.Rect(x, y, w, 4) self.action ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' mail.py: email server utils ''' import sys import argparse import getpass from os import getenv try: import mysql.connector as mariadb except ImportError: print('找不到 mysql 客户端,请安装: pip install mysql-connector-python') sys.exit(2) _version = '2.1' parse...
python
import os import json from .android_component_builder import AndroidComponentBuilder class LabelBuilder(AndroidComponentBuilder): def __init__(self, options, component): super().__init__(options, component) self.constraints = {} self.name = '' self.text = '' self.text_align...
python
import http import secrets import pytest from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from django.utils.http import urlencode from guildmaster import views from guildmaster.utils import reverse @pytest.fixture() def user(): user, __ = User.objects...
python
# coding: utf-8 """ Json-serializers for books-rest-api. """ from rest_framework.serializers import ( ModelSerializer, ReadOnlyField ) from books.models import * __author__ = "Vladimir Gerasimenko" __copyright__ = "Copyright (C) 2017, Vladimir Gerasimenko" __version__ = "0.0.1" __maintainer__ = "Vladimir...
python
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from faker import Faker from members.models.members import Member from members.models.services import Service from members.models.countries import City from django.template.defaultfilters import slugify import random from dj...
python
q1 = [] q2 = [] n = 5 def push(data): if not q1==[] and len(q1) == n: print("Overflow") return if not q2==[] and len(q2) == n: print("Overflow") return if(q2 == []): q1.append(data) else: q2.append(data) def pop(): if(q1 == [] and q2 == []): ...
python
import requests, time import sys,time,socket from Sensor import Sensor if __name__ == "__main__": sensor = Sensor("/dev/ttyUSB0",9600) while True: data = sensor.PM25_Hex(10).split(" ") pm = int(data[3]+data[2], 16)/10 print str(time.strftime("%H:%M:%S", time.localtime())) + ' PM2.5: ', ...
python
from test_helper import run_common_tests, failed, passed, check_tests_pass from maximum_salary import largest_number def reference(numbers): numbers = list(map(str, numbers)) for _ in numbers: for i in range(len(numbers) - 1): if numbers[i] + numbers[i + 1] < numbers[i + 1] + numbers[i]: ...
python
#!/usr/bin/python3 import requests s = requests.Session() #url = "http://127.0.0.1:8080" url = "http://52.76.131.184/_mijkweb/" #payload = {'request' : '{"type":"login", "login":"mijkenator@gmail.com", "password":"test", "as":"admin"}'} payload = {'request' : '{"type":"login", "login":"mijkenator", "password":"test"...
python
import pytest from anticrlf.types import SubstitutionMap from anticrlf.exception import UnsafeSubstitutionError def test_substitution_assign(): smap = SubstitutionMap(key="value") assert type(smap) == SubstitutionMap assert smap['key'] == 'value' assert smap["\n"] == "\\n" assert smap["\r"] == "\...
python
from gitlab.base import RESTManager, RESTObject from gitlab.mixins import ( AccessRequestMixin, CreateMixin, DeleteMixin, ListMixin, ObjectDeleteMixin, ) __all__ = [ "GroupAccessRequest", "GroupAccessRequestManager", "ProjectAccessRequest", "ProjectAccessRequestManager", ] class G...
python
#n = '' #while n != 'MnFf': #print('Qual o seu sexo? ') #x = input('[M/F]').upper().strip() #if x in 'MmFf': #print('OBRIGADO PELO ACESSO.') #else: #print('TENTE NOVAMENTE, INVALIDO.') sexo = str(input('Qual seu SEXO?: [M/F] ')).strip() while sexo not in 'FfMm': sexo = str(inpu...
python
""" Package for working with JSON-format configuration files. """ from ._JSONObject import JSONObject from ._StrictJSONObject import StrictJSONObject from ._typing import ( Absent, OptionallyPresent, PropertyValueType )
python
import itertools from datetime import datetime, timedelta from notifications_utils.polygons import Polygons from notifications_utils.template import BroadcastPreviewTemplate from orderedset import OrderedSet from werkzeug.utils import cached_property from app.broadcast_areas import CustomBroadcastAreas, broadcast_are...
python
#!/usr/bin/env python ''' Dane Warren Obtain the k nearest neighbors of the given player and use the second seasons these neighbors to predict the second season of the given player. ''' import cPickle as pickle ''' @param rbID: The ID of the running back to get the stats for @param rrbStats: A list containing dictio...
python
import FWCore.ParameterSet.Config as cms # list of crystal indecies ics = cms.untracked.vint32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 81, 82, 83, 84, 85, 86, 87, ...
python
import urllib.parse import urllib.request from doodledashboard.component import MissingRequiredOptionException, NotificationCreator, \ ComponentCreationException from doodledashboard.filters.contains_text import ContainsTextFilter from doodledashboard.filters.matches_regex import MatchesRegexFilter from doodledash...
python
from asyncio import Future, ensure_future from typing import Any, Callable from websockets import WebSocketCommonProtocol as WebSocket from .models import Notification __all__ = [ 'Notifier', ] _Sender = Callable[[Notification], Future] _Finalizer = Callable[[Future], Any] class Notifier: def __init__(sel...
python
"""Function for building a diatomic molecule.""" def create_diatomic_molecule_geometry(species1, species2, bond_length): """Create a molecular geometry for a diatomic molecule. Args: species1 (str): Chemical symbol of the first atom, e.g. 'H'. species2 (str): Chemical symbol of the second ...
python
from abc import abstractmethod from typing import Iterable from .common import PipelineContext, RecordEnvelope class Transformer: @abstractmethod def transform( self, record_envelopes: Iterable[RecordEnvelope] ) -> Iterable[RecordEnvelope]: """ Transforms a sequence of records. ...
python
from pygame.surface import Surface, SurfaceType from typing import Union, List, Tuple from pygame.color import Color GRAVITY_LEFT = 0 GRAVITY_RIGHT = 1 GRAVITY_TOP = 0 GRAVITY_BOTTOM = 2 GRAVITY_CENTER_HORIZONTAL = 4 GRAVITY_CENTER_VERTICAL = 8 STYLE_NORMAL = 0 STYLE_BOLD = 1 STYLE_ITALIC = 2 MOUSE_MODE_CONFINED = 1...
python
import collections from reclist.abstractions import RecList, rec_test from typing import List import random class CoveoCartRecList(RecList): @rec_test(test_type='stats') def basic_stats(self): """ Basic statistics on training, test and prediction data """ from reclist.metrics....
python
""" Method Resolution Order (MRO) MRO é a ordem de execução dos métodos, ou seja quem será executado primeiro. MRO tem 3 formas: - Via propriedade da clase - Via método MRO() - Via help Polimorfismo - Objetos que podem se comportar de diferentes formas """ class Animal: def __init__(self, nome): ...
python
""" [2014-11-19] Challenge #189 [Intermediate] Roman Numeral Conversion https://www.reddit.com/r/dailyprogrammer/comments/2ms946/20141119_challenge_189_intermediate_roman_numeral/ Your friend is an anthropology major who is studying roman history. They have never been able to quite get a handle for roman numerals and...
python
#!/usr/bin/env python3 # @generated AUTOGENERATED file. Do not Change! from dataclasses import dataclass from datetime import datetime from gql.gql.datetime_utils import DATETIME_FIELD from gql.gql.graphql_client import GraphqlClient from functools import partial from numbers import Number from typing import Any, Call...
python
# from .base import Base # # def initDB(engine): # metadata = Base.metadata # metadata.create_all(engine) # print ('Database structure created') # #
python
#!/usr/bin/env python from __future__ import print_function import os import sys import time import json import requests import argparse import lxml.html import io from lxml.cssselect import CSSSelector YOUTUBE_COMMENTS_URL = 'https://www.youtube.com/all_comments?v={youtube_id}' YOUTUBE_COMMENTS_AJAX_URL = 'https:/...
python
from django.db import models # Create your models here. from django.db import models from blog.models import Artikel from django.contrib.auth.models import User class Comment(models.Model): message = models.TextField() artikel_creator_username = models.CharField(max_length=200, null=True, blank=True) ...
python
import json from http import HTTPStatus from unittest.mock import patch from bridges.tests.api.basic_test import BasicTest DUMMY_USER_FULL_NAME = 'John Doe' DUMMY_USER_EMAIL = 'john.doe@company.com' class GetWhoAmITest(BasicTest): """ Class to test whoami endpoint. """ @patch('bridges.api.endpoints...
python
# (C) Copyright 1996-2016 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergov...
python
""" This class is responsible for storing all the information about the current state of a chess game. It will also be responsible for determining the valid moves at the current state. It will also keep keep a move log. """ class GameState(): def __init__(self): # board is an 8x8 2d list, each element of t...
python
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Power flow data for IEEE 118 bus test case. """ from numpy import array def case118(): """Power flow data for IEEE 118 bus test case. Please see L{cas...
python
#!/usr/bin/env python """Tests the tdb data store - in memory implementation.""" import shutil # pylint: disable=unused-import,g-bad-import-order from grr.lib import server_plugins # pylint: enable=unused-import,g-bad-import-order from grr.lib import access_control from grr.lib import config_lib from grr.lib import...
python
from radiacode.bytes_buffer import BytesBuffer from radiacode.radiacode import spectrum_channel_to_energy, RadiaCode from radiacode.types import *
python
class GameActuator: filename = None mode = None
python
import codecs import re import sys def warn(s): sys.stderr.write(s) sys.stderr.flush() class CfgParserError(Exception): pass _name_pat = re.compile("[a-z][a-z0-9]*", re.UNICODE) class CfgParser: """Important note: parser related methods and attributes are capitalized. You can access (get an...
python
from setuptools import setup, find_packages # read the contents of your README file from pathlib import Path this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() setup( name='jkx', version='1.0.4', license='MIT', author="Andrew Heaney", author_email=...
python
#Crie um algoritimo que leia um numero e mostre o seu dobro # o seu triplo e a raiz quadrada n = float(input('Digite um numero: ')) print('Seu dobro é {}'.format(n * 2)) print('Seu triplo é {}'.format(n * 3)) print('Sua raiz quadrada é: {}'.format(n**(1/2)))
python
# -*- coding: utf-8 -*- """ flask_babelplus.domain ~~~~~~~~~~~~~~~~~~~~~~ Localization domain. :copyright: (c) 2013 by Armin Ronacher, Daniel Neuhäuser and contributors. :license: BSD, see LICENSE for more details. """ import os from babel import support from .utils import get_state, get_locale f...
python
from __future__ import print_function from botocore.exceptions import ClientError import json import datetime import boto3 import os def handler(event, context): print("log -- Event: %s " % json.dumps(event)) response = "Error auto-remediating the finding." try: # Set Clients ec2 = boto3.clien...
python
import pytest from whatlies.language import BytePairLang @pytest.fixture() def lang(): return BytePairLang("en", vs=1000, dim=25, cache_dir="tests/cache") def test_single_token_words(lang): assert lang["red"].vector.shape == (25,) assert len(lang[["red", "blue"]]) == 2 def test_similar_retreival(lang...
python
class Solution: @staticmethod def addBinary(a: str, b: str) -> str: length = max(len(a), len(b)) answer = '' rem = 0 answer, rem = Solution.calculate(a.zfill(length), answer, b.zfill(length), length, rem) if rem != 0: answer = '1' + answer return answe...
python
import sys sys.path.append('/root/csdc3/src/sensors') import unittest import time from sensor_manager import SensorManager from sensor_constants import * class Tests(unittest.TestCase): def setUp(self): pass def test_ds1624(self): ds1624 = [TEMP_PAYLOAD_A, TEMP_BAT_1] for sensor in ds1...
python
import sys sys.dont_write_bytecode = True import json from PyQt5.QtWidgets import QApplication from models.Authenticate import Dialog from models.Base import MainWindow if __name__ == "__main__": try: cfg_file = open("config.json","r") config = json.loads(cfg_file.read()) ip = config['server_ip'] p...
python
from logging import getLogger from threading import Thread from time import sleep from signalrc.ws_transport import WebSocketsTransport logger = getLogger('signalr.client') class SignalRClient: def __init__(self, url, hub, session=None): self.url = url self._invokes_counter = -1 self.tok...
python
import shutil from fastapi import APIRouter, File, HTTPException, UploadFile from models.migration_models import ChowdownURL from services.migrations.chowdown import chowdown_migrate as chowdow_migrate from services.migrations.nextcloud import migrate as nextcloud_migrate from app_config import MIGRATION_DIR from util...
python
"""Top-level package for django-extra-field-validation.""" __author__ = """Tonye Jack""" __email__ = "jtonye@ymail.com" __version__ = "1.1.1" from .field_validation import FieldValidationMixin __all__ = ["FieldValidationMixin"]
python
#!/usr/bin/env python import random import rospy from std_msgs.msg import UInt32 if __name__ == '__main__': random.seed() rospy.init_node('random') pub = rospy.Publisher('rand_int', UInt32, queue_size = 1) rate = rospy.Rate(10) while not rospy.is_shutdown(): pub.publish(random.randint(0,...
python
# Generated by Django 3.0.5 on 2021-04-23 10:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('cse', '0011_delete_dev'), ] operations = [ migrations.CreateModel( name='semester', fields=[ ...
python
# Generated by Django 2.1 on 2018-08-18 02:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ('inventories', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='ItemInventory', ...
python
# -*- coding: utf-8 -*- """ The view ports widget @author: Chris Scott """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import logging from PySide2 import QtWidgets from . import rendererSubWindow class ViewPortsWidget(QtWidgets.QWidget): """ ...
python
from .views import SearchContact, markSpam, detailView from django.urls import path urlpatterns = [ path('Search/', SearchContact.as_view()), path('mark/<int:id>', markSpam, ), path('Detail/<int:id>', detailView), ]
python
from . import data from . import datasets from . import layers from . import losses from . import metrics from . import models from . import optimizers from . import utils
python
"""! @brief Unit-test runner for core wrapper. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest from pyclustering.tests.suite_holder import suite_holder # Generate images without having a window appear. import matplotlib matplotlib.use('Agg') from pyclu...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- #===============================================================================# #title :MangaPark.py # #description :contains the MangaPark class # #author :August B. San...
python
__all__ = ['HttpCacheControlMixin'] class HttpCacheControlMixin: http_cache_control_max_age = None def get_http_cache_control_max_age(self): return self.http_cache_control_max_age def dispatch(self, *args, **kwargs): response = super().dispatch(*args, **kwargs) if response.status...
python
from __future__ import annotations # python import logging import os import random import importlib import json import datetime from halo_app.classes import AbsBaseClass from halo_app.app.context import HaloContext, InitCtxFactory from halo_app.infra.providers.providers import get_provider,ONPREM from halo_app.app.re...
python
"""A helper rule for testing detect_root function.""" load("@rules_foreign_cc//tools/build_defs:detect_root.bzl", "detect_root") def _impl(ctx): detected_root = detect_root(ctx.attr.srcs) out = ctx.actions.declare_file(ctx.attr.out) ctx.actions.write( output = out, content = detected_root,...
python
import sys import json from .kafka import Consumer from .postgres import PGClient from .model import URLStatus if __name__ == '__main__': try: with PGClient() as pg_client, Consumer() as kafka_consumer: # TODO: change to subscript # TODO: try https://github.com/aio-libs/aiokafka ...
python
import os import neat import pygame from bird import Bird from pipe import Pipe from base import Base from background import Background class Game: WIN_WIDTH = 500 WIN_HEIGHT = 800 def __init__(self): self.isRunning = True self.score = 0 self.birds = [] self.nets = [] ...
python
import FWCore.ParameterSet.Config as cms process = cms.Process("ANALYSIS") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:clustering.root') ) process.pfClusterAnalyzer = cms.EDAnalyzer("PFClusterAnalyz...
python
#!/usr/bin/env python # David Prihoda # Calculate coverage of BGCs by a DataFrame of BGC Candidates import pandas as pd import matplotlib.pyplot as plt import numpy as np import argparse def get_single_contig_coverage(a_cands, b_cands): """ Get coverage of each BGC candidate in a_cands by BGC candidates in b_...
python
import tensorflow as tf class Generator(object): def __init__(self, n_node, node_emd_init, config): self.n_node = n_node self.node_emd_init = node_emd_init self.motif_size = config.motif_size self.max_value = config.max_value with tf.compat.v1.variable_scope('generator'): ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from django.conf import settings FRAME_FORMATTER = getattr(settings, 'FRAME_FORMATTER', None) FRAME_SEPARATOR = getattr(settings, 'FRAME_SEPARATOR', None) if FRAME_FORMATTER is None: raise ValueError('Improperly Configured FRAME_FORMA...
python
from __future__ import division from utils.utils import * from utils.datasets import * from utils.parse_config import * from models.darknet import * from models.yolo_nano_helper import YoloNano from torch.nn.parallel import DataParallel import os import sys import time import datetime import argparse import tqdm imp...
python
"""A module to generate OpenAPI and JSONSchemas.""" import json import os from pkg_resources import get_distribution from pydantic_openapi_helper.core import get_openapi from pydantic_openapi_helper.inheritance import class_mapper from queenbee.repository import RepositoryIndex from queenbee.job import Job, JobStat...
python
import unittest from time import sleep from random import randint import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys imp...
python
#!/usr/bin/env python import sys for line in sys.stdin: # extract data key, val = line.strip().split('\t', 1) s_val = val.split(',') # day day = key.split(',')[3][:10] # revenue try: revenue = float(s_val[11]) + float(s_val[12]) + float(s_val[14]) except ValueError: co...
python
from typing import TypeVar T = TypeVar("T") class Node: def __init__(self, item: T): self.item = item self.next = None
python
import re from File import * from Base import * from subprocess import call class Animation_Html(): ##! ##! Animation main HTML path ##! def Animation_HTML_Path(self): return "/".join( [ self.Path,self.FileName,self.Curve_Parms_Path ] ) ##! ##! Animation main HTML file...
python
from django.contrib.postgres.fields import ArrayField from django.db import models from osf.models import Node from osf.models import OSFUser from osf.models.base import BaseModel, ObjectIDMixin from osf.models.validators import validate_subscription_type from osf.utils.fields import NonNaiveDateTimeField from website....
python
import logging log = logging.getLogger(__name__) from dogpile.cache import make_region from dogpile.cache.api import NO_VALUE import os, errno CACHE_FAILS = (NO_VALUE,) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST: ...
python
#!/usr/bin/python # -*- coding: UTF-8 import sys import os import math import statistics import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib.backends.backend_pdf import PdfPages from datetime import datetime import col...
python
r""" ``cotk.metrics`` provides classes and functions evaluating results of models. It provides a fair metric for every model. """ import random import multiprocessing from multiprocessing import Pool import numpy as np from nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction from .._utils.un...
python
from re import search from requests import get, post from requests.exceptions import ConnectionError, MissingSchema, ReadTimeout from sqlalchemy import Boolean, case, ForeignKey, Integer from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy...
python
# Generated by Django 2.1 on 2020-08-04 10:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('encounterapp', '0032_auto_20200801_1914'), ('encounterapp', '0032_auto_20200801_1758'), ] operations = [ ]
python
import os #BASE_DIR = os.path.abspath('.') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #os.path.abspath('.') ROUGE_DIR = os.path.join(BASE_DIR,'summariser','rouge','ROUGE-RELEASE-1.5.5/') #do not delete the '/' at the end PROCESSED_PATH = os.path.join(BASE_DIR,'data','summaries_processed_data') SUMMARY_DB_DI...
python
""""Utilities for Diffie-Hellman key exchange.""" from __future__ import unicode_literals import base64 import warnings import six from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric.dh import DHParameterNumbers, DHP...
python
import imp import astropy.units as un import astropy.coordinates as coord import matplotlib.pyplot as plt import gala.coordinates as gal_coord from astropy.table import Table from vector_plane_calculations import * from velocity_transformations import * imp.load_source('helper', '../tSNE_test/helper_functions.py') f...
python
#import needed packages import os, json, sys #creates functions global commands = {} #import modules modules = os.listdir(path='modules') print('Importing modules') count_mod = 0 count_ok_mod = 0 for module in modules: try: with open('modules/' + module + '/index.json') as read_modules: mod_da...
python
from django.urls import path, include from management import views from rest_framework_simplejwt import views as jwt_views urlpatterns = [ # Used to signup as a teacher or a student path('signup/', views.SignUpView.as_view(), name = 'signup'), # Used to obtain refresh and access token path('login/acc...
python
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ...
python