text string | size int64 | token_count int64 |
|---|---|---|
# This process handles all the requests in the queue task_queue and updates database
import json, pika, sys, time
from database_management import manage_database, submission_management
class core():
data_changed_flags = ''
task_queue = ''
channel = ''
file_password = ''
unicast_exchange = 'connection_manager'
... | 3,498 | 1,536 |
__version__ = "0.0.0"
__hash__ = "<invalid-hash>"
| 50 | 23 |
''' buildings and built environment '''
from datetime import datetime
import random
import tracery
from utilities import format_text, get_latin
def eatery(name, dish, category, data):
''' a charming stone hut where they serve tea '''
earliest = data['founded'] if data['founded'] > 1700 else 1700
founding =... | 5,954 | 1,793 |
## CUDA blocks are initialized here!
## Created by: Aditya Atluri
## Date: Mar 03 2014
def bx(blocks_dec, kernel):
if blocks_dec == False:
string = "int bx = blockIdx.x;\n"
kernel = kernel + string
blocks_dec = True
return kernel, blocks_dec
def by(blocks_dec, kernel):
if blocks_dec == False:
string = "int... | 1,235 | 527 |
import pytest
from dcolor.attr import *
def attr_init():
attr = Attr(
kind="bold"
)
yield attr
def test_init():
Attr(
kind="bold"
)
def test_init2():
Attr(
kind=AttrList.bold
)
@pytest.mark.parametrize(
"kind", [
b"kind",
10,
10.0,
["bold"],
... | 953 | 343 |
import os
import tarfile
import textwrap
from pathlib import Path
import setuptools
from wheel.wheelfile import WheelFile
from setuptools_build_subpackage import Distribution
ROOT = Path(__file__).parent.parent
def build_dist(folder, command, output, *args):
args = [
'--subpackage-folder',
fold... | 7,358 | 2,880 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.conf import settings
from django.http import HttpResponse
from django.test import (
Client,
TestCase,
)
from satchless.cart.tests import TestCart
from ...cart.models import CART_SESSION_KEY
from ...order.app import order_app
from ...pri... | 2,711 | 813 |
import os
import subprocess
import pathlib
import time
import sys
from numpy.core.shape_base import block
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from random import randint
import random
from datetime import datetime
def run_make():
p_status, p_output = subprocess.getstatusoutput('m... | 4,309 | 1,538 |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import numpy as np
import pandas as pd
import csv
from matplotlib.lines import Line2D
epsilon = pd.read_pickle('epsilon.pkl')
def plots_with_sizes(result_folder, query, attribute):
if attribute == 'age':
d = 1
if attribute == '... | 7,167 | 2,997 |
#!/usr/bin/env python
#
# Copyright 2020 GoPro Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... | 5,443 | 1,957 |
from django.db import models
from ozpcenter.utils import get_now_utc
from .import_task import ImportTask
class ImportTaskResultManager(models.Manager):
def get_queryset(self):
return super().get_queryset()
def find_all(self):
return self.all()
def find_by_id(self, id):
return s... | 1,624 | 552 |
"""
Loading utilities for computational experiments.
"""
import os
import pandas as pd
DATA_DIR = os.path.dirname(os.path.abspath(__file__))
def load_zT(all_data=False):
"""
Thermoelectric figures of merit for 165 experimentally measured compounds.
Obtained from the Citrination database maintained by C... | 3,422 | 1,094 |
import json
def get_qtypes(dataset_name, part):
"""Return list of question-types for a particular TriviaQA-CP dataset"""
if dataset_name not in {"location", "person"}:
raise ValueError("Unknown dataset %s" % dataset_name)
if part not in {"train", "dev", "test"}:
raise ValueError("Unknown part %s" % par... | 1,913 | 599 |
__all__= ['controller']
| 25 | 11 |
# test unicode in identifiers
# comment
# αβγδϵφζ
# global identifiers
α = 1
αβγ = 2
bβ = 3
βb = 4
print(α, αβγ, bβ, βb)
# function, argument, local identifiers
def α(β, γ):
δ = β + γ
print(β, γ, δ)
α(1, 2)
# class, method identifiers
class φ:
def __init__(self):
pass
def δ(self, ϵ):
... | 385 | 197 |
from cssdbpy import Connection
from time import time
import md5
if __name__ == '__main__':
conn = Connection('127.0.0.1', 8888)
for i in xrange(0, 10000):
md5word = md5.new('word{}'.format(i)).hexdigest()
create = conn.execute('hset','words', md5word, int(time()))
value = conn.execute('hget','words', md5word)... | 552 | 214 |
import os
import argparse
from distutils.dir_util import copy_tree
import random
def main(args):
"""
Simple function that looks at the arguments passed, checks to make sure
everything expected exists, and then defines a validation data set for
later processing by TrainTiramisu.py and TestTiramisu.py
... | 4,538 | 1,410 |
import datetime
import pytz
from tws_async import *
stocks = [
Stock('TSLA'),
Stock('AAPL'),
Stock('GOOG'),
Stock('INTC', primaryExchange='NASDAQ')
]
forexs = [
Forex('EURUSD'),
Forex('GBPUSD'),
Forex('USDJPY')
]
endDate = datetime.date.today()
startDate = endDate - datetime.timedelta(day... | 880 | 346 |
import heapq
import unittest
from typing import List
import utils
# O(nlog(n)) time. O(n) space. Interval, sorting by end, greedy.
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
courses.sort(key=lambda course: course[1])
time = 0
q = []
for t, d in co... | 961 | 309 |
"""cff2Lib_test.py -- unit test for Adobe CFF fonts."""
from fontTools.ttLib import TTFont
from io import StringIO
import re
import os
import unittest
CURR_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
DATA_DIR = os.path.join(CURR_DIR, 'data')
CFF_TTX = os.path.join(DATA_DIR, "C_F_F__2.ttx")
CF... | 1,761 | 657 |
from common.webdriver_factory import get_driver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = get_driver('chrome')
wait = WebDriverWait(driver, 5)
driver.get('https://www.mlb.com/es/standin... | 340 | 97 |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... | 13,380 | 3,775 |
import logging
import threading
import time
from pajbot.managers.db import DBManager
from pajbot.managers.schedule import ScheduleManager
from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo
from pajbot.models.user import User
log = logging.getLogger("pajbot")
WIDGET_ID = ... | 15,033 | 4,157 |
import numpy as np
def mean_or_nan(xs):
"""Return its mean a non-empty sequence, numpy.nan for a empty one."""
return np.mean(xs) if xs else np.nan | 157 | 53 |
import time
import unittest
import unittest.mock
from smac.configspace import ConfigurationSpace
from smac.runhistory.runhistory import RunInfo, RunValue
from smac.scenario.scenario import Scenario
from smac.stats.stats import Stats
from smac.tae import StatusType
from smac.tae.execute_func import ExecuteTAFuncDict
fr... | 3,065 | 939 |
# Generated by Django 3.0 on 2020-09-09 05:08
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gyms', '0002_auto_20200903_1750'),
]
operations = [
migrations.AlterField(
model_name='gym',
... | 531 | 193 |
#! /usr/bin/env python
# coding: utf-8
#
# Copyright (c) 2020 JR Oakes
#
# 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 rights to use,... | 3,467 | 1,157 |
def sample(name, custom_package):
native.android_binary(
name = name,
deps = [":sdk"],
srcs = native.glob(["samples/" + name + "/src/**/*.java"]),
custom_package = custom_package,
manifest = "samples/" + name + "/AndroidManifest.xml",
resource_files = native.glob(["sa... | 358 | 109 |
from deeplodocus.utils.generic_utils import get_corresponding_flag
from deeplodocus.utils.notification import Notification
from deeplodocus.flags import *
from typing import Union
class OverWatch(object):
"""
AUTHORS:
--------
:author: Alix Leroy
DESCRIPTION:
------------
Metric to ove... | 2,909 | 879 |
#!/usr/bin/env python
# reference build https://travis-ci.org/louiscklaw/test_git_repo/builds/625335510
# https://docs.travis-ci.com/user/environment-variables/
import os, re, subprocess
import slack
from fabric.api import local, shell_env, lcd, run, settings
SLACK_TOKEN = os.environ['SLACK_TOKEN']
BRANCH_TO_MERGE... | 2,483 | 1,006 |
## Built-in packages
import getopt
import json
import os
import sys
## Third-party packages
from PIL import Image
import joblib
import numpy as np
import tqdm
## Tensorflow
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from... | 876 | 284 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__version__ 1.0.0
"""
import csv
import agentframework7 as af
import random
import matplotlib.pyplot as pyplot
from sys import argv
import matplotlib.animation as anim
import os
from multiprocessing import Process
import time
'''
Step 1: Initialise parameters
'''
prin... | 7,715 | 2,402 |
from ..receivers import *
| 26 | 8 |
"""Tests rest of functions in manubot.cite, not covered by test_citekey_api.py."""
import pytest
from manubot.cite.citekey import (
citekey_pattern,
shorten_citekey,
infer_citekey_prefix,
inspect_citekey,
)
@pytest.mark.parametrize("citation_string", [
('@doi:10.5061/dryad.q447c/1'),
('@arxi... | 3,156 | 1,393 |
import pytest
from playwright.sync_api import Page
from pages.main_page.main_page import MainPage
from test.test_base import *
import logging
import re
logger = logging.getLogger("test")
@pytest.mark.only_browser("chromium")
def test_find_element_list(page: Page):
main_page = MainPage(base_url, page)
main_pa... | 1,727 | 546 |
### based on https://github.com/kylemcdonald/Parametric-t-SNE/blob/master/Parametric%20t-SNE%20(Keras).ipynb
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras.losses import categorical_crossentropy
from tqdm.autonotebook import tqdm
import tensorflow as tf
def Hbeta(D, beta):
""... | 5,703 | 1,971 |
#!/usr/bin/python
# Classification (U)
"""Program: gitmerge_commits_diff.py
Description: Unit testing of gitmerge.commits_diff in git_class.py.
Usage:
test/unit/git_class/gitmerge_commits_diff.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version... | 3,466 | 1,106 |
import random
import string
def test_append(lst):
ret_val = []
for w in lst:
ret_val.append(w.lower( ))
return ret_val
def test_map(lst):
ret_val = map(str.lower, lst)
return ret_val
def run_tests(n):
for i in range(n):
tst = ''.join(random.choices(string.ascii_uppercase + str... | 500 | 202 |
import os
import sys
import json
import argparse
from huepy import *
parser = argparse.ArgumentParser()
parser.add_argument('file', help= 'File with mtrees data (CSV or JSON)')
parser.add_argument('--mtrees', help = 'File with the mesh dictionary to be created (names to ids).', default = 'mhmd-driver/m.json')
parser.a... | 4,826 | 1,626 |
import cairo
from uuid import uuid4
from gen_art.graphics.Helpers import does_path_exist, open_file
from os import path
from datetime import datetime
class DrawContext:
def __init__(self, width, height, output_path, open_bool):
self.open_bool = open_bool
self.width = width
self.height = he... | 1,157 | 361 |
# -*- coding: utf-8 -*-
"""
@author : Tangui ALADJIDI
After the Matlab code from Yicheng WU
"""
import numpy as np
import matplotlib.pyplot as plt
from LightPipes import *
from PIL import Image
from time import time
from mpl_toolkits.axes_grid1 import make_axes_locatable
import time
import sys
import configparser
fro... | 19,080 | 7,537 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 26 20:17:06 2014
@author: stuart
"""
import os
import tempfile
import datetime
import astropy.table
import astropy.time
import astropy.units as u
import pytest
from sunpy.time import parse_time
from sunpy.net.jsoc import JSOCClient, JSOCResponse
from sunpy.net.vso.vso im... | 8,635 | 3,469 |
import turtle
if __name__ == '__main__':
colors = ['red', 'green', 'yellow', 'purple', 'blue', 'orange']
turtle.bgcolor('black')
for i in range(360):
turtle.pencolor(colors[i % 6])
turtle.width(int(i / 100 + 1))
turtle.forward(i)
turtle.left(59)
| 293 | 123 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Compare to numpy data"""
import sys
import numpy as np
import multipletau
from test_correlate import get_sample_arrays_cplx
def test_corresponds_ac():
myframe = sys._getframe()
myname = myframe.f_code.co_name
print("running ", myname)
a = np.concatenate... | 5,830 | 1,855 |
# Copyright 2020 The FedLearner Authors. 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 required by applica... | 2,613 | 781 |
# Homework 7
# Write a python program that will download the latest 10 comic images from https://www.gocomics.com/pearlsbeforeswine/
# Navigate to the latest page by clicking 'Read More'.
import requests
import bs4
import os
url = 'https://www.gocomics.com/pearlsbeforeswine/2019/08/21'
for i in range(10):
res = r... | 1,753 | 546 |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class TenantProxy(object):
"""Implementation of the 'TenantProxy' model.
Specifies the data for tenant proxy which has been deployed in tenant's
enviroment.
Attributes:
constituent_id (long|int): Specifies the constituent id of the prox... | 2,106 | 559 |
from __future__ import print_function
from argparse import Namespace
# a video display model to check timing
import pytest
from myhdl import Signal, intbv, instance, delay, StopSimulation, now
from rhea.system import Clock, Reset, Global
from rhea.cores.video.lcd import LT24Interface
from rhea.models.video import ... | 2,101 | 812 |
"""Utilities and implementation for model aggregation on the central server."""
from .aggregator import *
from .fedavg import *
from .fedprox import *
from .scaffold import *
from .aggregator_with_dropouts import *
from .multi_model_aggregator import * | 253 | 74 |
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
from nilearn.datasets.utils import _fetch_files
from scipy import sparse
class StudyID(str):
pass
class TfIDf(float):
pass
NS_DATA_URL = "https://github.com/neurosynth/neurosynth-data/raw/master/"
def fetch_stud... | 9,912 | 3,050 |
from typing import Any
from typing import Generic
from typing import overload
from typing import Type
from typing import TypeVar
from . import compat
if compat.py38:
from typing import Literal
from typing import Protocol
from typing import TypedDict
else:
from typing_extensions import Literal # noqa
... | 957 | 290 |
# generated from catkin/cmake/template/order_packages.context.py.in
source_root_dir = '/home/sim2real/ep_ws/src'
whitelisted_packages = ''.split(';') if '' != '' else []
blacklisted_packages = ''.split(';') if '' != '' else []
underlay_workspaces = '/home/sim2real/carto_ws/devel_isolated/cartographer_rviz;/home/sim2rea... | 563 | 228 |
import six
if six.PY3:
from unittest import mock
from io import StringIO
else:
import mock
from cStringIO import StringIO
from http.client import responses
import json
from django import test
from request_signer.client.generic import Response
class ResponseTests(test.TestCase):
def setUp(self):
... | 2,682 | 812 |
# Created by Tristan Bester.
import sys
import numpy as np
sys.path.append('../')
from envs import GridWorld
from itertools import product
from utils import print_episode, eps_greedy_policy, test_policy
'''
n-step Tree Backup used to estimate the optimal policy for
the gridworld environment defined on page 48 of
"Rein... | 3,373 | 1,172 |
from setuptools import setup, find_packages
# What packages are required for this module to be executed?
REQUIRED = [
"dm-tree",
"numpy",
"scipy"
]
setup(name="metalgpy", packages=find_packages(), install_requires=REQUIRED)
| 240 | 82 |
#!/usr/bin/env python3
import functools
#https://stackoverflow.com/questions/3888158
def optional_arg_decorator(fn):
@functools.wraps(fn)
def wrapped_decorator(*args, **kwargs):
# is_bound_method = hasattr(args[0], fn.__name__) if args else False
# if is_bound_method:
# klass = args[... | 1,722 | 617 |
from setuptools import setup
from homeassistant_api import __version__
with open("README.md", "r") as f:
read = f.read()
setup(
name="HomeAssistant API",
url="https://github.com/GrandMoff100/HomeassistantAPI",
description="Python Wrapper for Homeassistant's REST API",
version=__version__,
keyw... | 1,552 | 470 |
#!/usr/bin/env python3
import ctypes
import os
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
C_MOLLERS = ctypes.CDLL(os.path.join(CURRENT_PATH, 'build/mollers_tri_tri.so'))
C_DEVILLERS = ctypes.CDLL(
os.path.join(CURRENT_PATH, 'build/devillers_tri_tri.so'))
def mollers_alg(tri_1, tri_2):
"""
... | 2,316 | 1,055 |
"""
Copyright (c) 2018 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
Query the koji build target, if any, to find the enabled architectures. Remove any excluded
architectures, and return the resulting list.
"""
fr... | 5,381 | 1,452 |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 13:33:17 2020
@Author: Zhi-Jiang Yang, Dong-Sheng Cao
@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China
@Homepage: http://www.scbdd.com
@Mail: yzjkid9@gmail.com; oriental-cds@163.com
@Blog: https://blog.iamkotori.com
♥I love Princess Zelda... | 4,876 | 1,834 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# It's written by https://github.com/yumatsuoka
from __future__ import print_function
import math
from torch.optim.lr_scheduler import _LRScheduler
class FlatplusAnneal(_LRScheduler):
def __init__(self, optimizer, max_iter, step_size=0.7, eta_min=0, last_epoch=-1):... | 1,954 | 714 |
#
# PySNMP MIB module CISCOSB-RMON (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-RMON
# Produced by pysmi-0.3.4 at Wed May 1 12:23:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | 15,270 | 4,985 |
"""Git helper functions.
Everything in here should be project agnostic, shouldn't rely on project's structure,
and make any assumptions about the passed arguments or calls outcomes.
"""
import subprocess
def apply(repo, patch_path, reverse=False):
args = ['git', 'apply',
'--directory', repo,
'... | 604 | 181 |
'''
Copyright (c) 2019 Boshen Zhang
Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
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 t... | 4,308 | 1,459 |
import cv2 as cv
import numpy as np
img = cv.imread('Photos/park.jpg')
cv.imshow('Original', img)
grayscale = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("Jesmin", grayscale)
#Condition for Laplacian: Cannot take negative values
#Laplacian Edge Detection
lap = cv.Laplacian(grayscale, cv.CV_64F)
absouluteLap = np.u... | 713 | 316 |
import sys
import os
import timeit
# use local python package rather than the system install
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../python"))
from bitboost import BitBoostRegressor
import numpy as np
import sklearn.metrics
nfeatures = 5
nexamples = 10000
data = np.random.choice(np.array([0.0,... | 1,204 | 483 |
'''
Created on 2015/11/07
@author: _
'''
from types import NoneType
from pyth2.contracts import TypeValidator as tv
from pyth2.io.Stream import Stream, StreamDirection
class BinaryStream(Stream):
@tv.forms(object, StreamDirection)
def __init__(self, direction):
super(BinaryStream, self).__init_... | 676 | 218 |
import unittest
import os
import logging
import time
import re
import splunklib.client as client
import splunklib.results as results
from splunklib.binding import HTTPError
from . import dltk_api
from . import splunk_api
from . import dltk_environment
level_prog = re.compile(r'level=\"([^\"]*)\"')
msg_prog = re.comp... | 4,633 | 1,365 |
from pydc import DC
def main():
dc = DC("example_dc.pl", 200) #default is 0 sample (will produce nan if later on no n_samples provided)
prob1 = dc.query("drawn(1)~=1")
print(prob1)
prob2 = dc.query("drawn(1)~=1", n_samples=2000)
print(prob2)
if __name__ == "__main__":
main()
| 302 | 127 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .MaskLoader import MaskLoader
from .utils import IOUMetric, fast_ista, prepare_distance_transform_from_mask, \
prepare_overlay_DTMs_from_mask, prepare_extended_DTMs_from_mask, prepare_augmented_distance_transform_from_mask, \
prepare_di... | 826 | 265 |
from pymongo import MongoClient
def path():
client = MongoClient('mongodb://localhost:27017/')
db = client['UserBook']
return db
| 143 | 46 |
import asyncio
import time
from rap.client import Client
from rap.common.exceptions import FuncNotFoundError
client: Client = Client("example", [{"ip": "localhost", "port": "9000"}])
# in register, must use async def...
@client.register()
async def raise_msg_exc(a: int, b: int) -> int:
pass
# in register, mus... | 1,064 | 372 |
import os
from ..utils.log import log
from ..utils.yaml import read_yaml, write_yaml
class BaseSpec:
COMPONENTS = 'components'
REF_FIELD = '$ref'
def __init__(self, path,
read_func=read_yaml, write_func=write_yaml):
self.path = path
self.path_dir = os.path.dirname(path... | 3,544 | 1,051 |
import os
import numpy as np
from six.moves import cPickle
from tensorflow import keras
from tensorflow import keras
import helper
from tfomics import utils, metrics, explain
#------------------------------------------------------------------------
model_names = ['residualbind']
activations = ['exponential', 'relu']... | 2,750 | 824 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 14:15:38 2019
@author: Satish
"""
# doing the ortho-correction on the processed data from matchedFilter
import os
import numpy as np
import spectral as spy
import spectral.io.envi as envi
import spectral.algorithms as algo
from spectral.algorith... | 6,564 | 2,431 |
import unittest
import os
import shutil
import subprocess
from math import ceil
TEST_DIR = "testdir"
MOVE_DIR = "movedir"
NUM_FILES = 100
class TestDefault(unittest.TestCase):
def setUp(self):
if os.path.exists(TEST_DIR):
shutil.rmtree(TEST_DIR)
os.makedirs(TEST_DIR)
os.chdir(... | 1,519 | 563 |
import math
import h5py
import numpy as np
def extract_pexit_data(filename):
infile = open(filename, "r")
data = [line.split() for line in infile]
b = [(math.pi * float(lne[0]) / 180.0) for lne in data]
le = [math.log10(float(lne[1])) for lne in data]
p = [math.log10(float(lne[-1])) for lne in da... | 2,155 | 915 |
# -*- coding: utf-8 -*-
import numpy as np
import csv
import tensorflow as tf
from config import Config
from DataFeeder import DataFeeder,TestData
from model import DKT
from sklearn.metrics import f1_score,precision_score,recall_score
indices = [precision_score,recall_score,f1_score]
def make_prediction(... | 4,443 | 1,507 |
# -*- coding: utf-8 -*-
from ..helpers import construct_similarity_matrix_via_profiles
class SimilarityMatrix:
def __init__(self, keywords, matrix):
self.keywords = keywords
self.matrix = matrix
def construct_similarity_matrix(relevance_matrix, relevance_threshold=0.2):
"""
Constructs ke... | 1,579 | 460 |
# TODO write utilities for running MCMC stuff
import networkx as nx
from graph_tool.inference import minimize_blockmodel_dl
from graph_tool import load_graph
import numpy as np
import pandas as pd
import os
from src.graph import MetaGraph
def run_minimize_blockmodel(mg, temp_loc=None, weight_model=None):
meta = ... | 1,452 | 534 |
# Generated by Django 2.2.10 on 2020-06-16 17:08
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reo', '0063_auto_20200521_1528'),
]
operations = [
migrations.AddField(
model_name='profi... | 2,832 | 833 |
# Copyright 2021 solo-learn development team.
# 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 rights to use,
# copy, modify, merge, publ... | 2,378 | 797 |
# Generated by Django 2.2 on 2019-06-08 10:32
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Adult_Products',
fields=[
('id', models.AutoF... | 1,966 | 527 |
#!/usr/bin/env python
# BEGIN_LEGAL
# BSD License
#
# Copyright (c)2014 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above... | 21,773 | 6,793 |
#!/usr/bin/env python
"""This module remains for backwards compatibility reasons and will be
removed in PyDy 0.4.0."""
import warnings
from .ode_function_generators import generate_ode_function as new_gen_ode_func
with warnings.catch_warnings():
warnings.simplefilter('once')
warnings.warn("This module, 'pyd... | 2,918 | 757 |
from datetime import datetime
import numpy as np
from rich.console import Console
from rich.table import Table
from rich import box
from rich.align import Align
from typing import List, Optional, Union
console_width = 80
def welcome_message(
space_data: List[dict],
search_type: str,
fixed_params: Optiona... | 12,795 | 4,389 |
from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os
import torch
import unicodedata
import string
import random
import numpy as np
def findFiles(path): return glob.glob(path)
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
# Turn a U... | 4,009 | 1,285 |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.identity.aio._credentials.managed_identity import ImdsCredential
import pytest
from helpers_async import AsyncMockTransport
@pytest.mark.asyncio
async def ... | 749 | 209 |
import cv2
import numpy as np
class Stitcher:
def stitch(self, images, ratio=.75, reprojThresh=4.0, showMatches=False):
imagesCount = len(images)
if imagesCount == 0:
return
if imagesCount == 1:
return images[0]
result = images[-1]
for i in range(ima... | 7,576 | 3,206 |
#coding:utf-8
#
# id: bugs.core_3365
# title: Extend syntax for ALTER USER CURRENT_USER
# decription:
# Replaced old code: removed EDS from here as it is not needed at all:
# we can use here trivial "connect '$(DSN)' ..." instead.
# Non-privileg... | 4,339 | 1,460 |
#!/usr/bin/env/ python3
"""SoloLearn > Code Coach > Hovercraft"""
sales = int(input('How many did you sell? ')) * 3
expense = 21
if sales > expense:
print('Profit')
elif sales < expense:
print('Loss')
else:
print('Broke Even')
| 241 | 96 |
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import AuthenticationForm
from web3 import Web3
from .forms import SignupForm
from Key.models import Key
#The views and templates in this app a... | 2,522 | 704 |
from flask import Flask, Blueprint
from flask_jwt_extended import JWTManager
def create_app(config):
app = Flask(__name__)
from instance.config import app_config
app.config.from_object(app_config[config])
app.config['JWT_SECRET_KEY'] = 'jwt-secret-string'
from .api.V1 import productsale_api as p... | 398 | 140 |
"""
preprocess MSP IMPROV csv
run after MSP_IMPROV.py
"""
import os, torch, soundfile
from pathlib import Path
import librosa
import pandas as pd
ID2LABEL = {
0: "neu", 1: "sad", 2: "ang", 3: "hap"
}
pwd = Path(__file__).parent
csv_dir = pwd / "../data/datasets/MSP-IMPROV"
out_dir = pwd / "../data/datasets/MSP-IMP... | 918 | 372 |
""" evoke base User object
IHM 2/2/2006 and thereafter
CJH 2012 and therafter
gives session-based user validation
The database users table must have an entry with uid==1 and id==guest.
This is used to indicate no valid login.
The database users table must have an entry with uid==2 . This is the
sys admin user.
R... | 19,038 | 6,042 |
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag
def richcomments_static():
return render_to_string('richcomments/templatetags/richcomments_static.html')
| 242 | 67 |
#!/usr/bin/env python3
from nicegui import ui
import pylab as pl
import numpy as np
import time
from rosys.world.pose import Pose
from rosys.world.spline import Spline
from grid import Grid
from robot_renderer import RobotRenderer
from obstacle_map import ObstacleMap
import plot_tools as pt
grid = Grid((30, 40, 36), (... | 1,203 | 561 |
from math import sqrt
from typing import Tuple
def quadratic(a: float, b: float, c: float) -> Tuple[float, float]:
'''Compute roots of the quadratic equation:
a*x**2 + b*x + c = 0
For example:
>>> x1, x2 = quadratic(a=4, b=11, c=7)
>>> x1
-1.0
... | 599 | 245 |
import heapq
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
results = []
heap = []
for x, y in points:
dist = x * x + y * y
heapq.heappush(heap, (dist, x, y))
for i in range(K):
point = heapq.heappop(heap)
... | 391 | 129 |
import pytest
import numpy as np
"""
def test_mono_39():
from pg_comp.base_mono import *
with open("tests/test_output/base_mono_1_200_n.out","r") as f:
n_500 = int(f.readline().strip())
srHNFs = []
for n in range(1,201):
temp = base_mono_37_39(n)
for t in temp:
if le... | 2,236 | 876 |