text string | size int64 | token_count int64 |
|---|---|---|
import torch
import torch.nn as nn
import torchvision.transforms as T
from common.vision.transforms import Denormalize
class Translation(nn.Module):
"""
Image Translation Transform Module
Args:
generator (torch.nn.Module): An image generator, e.g. :meth:`~dalib.translation.cyclegan.resnet_9_gene... | 1,347 | 435 |
import intcomp
def quinaryRepAsList(integer):
quinary = []
if(integer >= 3125):
print("error in quinary representation: only numbers up to 3124 are supported (you tried "+str(integer)+")")
# 5^4
digit = int(integer/625)
quinary.append(digit)
integer -= digit*625
# 5^3
digit = i... | 3,188 | 1,148 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from distributions import Categorical2D
from utils import init, init_normc_
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class Policy(nn.Module):
def __init__(self, obs_shape, action_space, base_kwarg... | 24,443 | 9,797 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, re, shutil, json, urllib, urllib2, cgi
# Fix issues with decoding HTTP responses
#reload(sys)
#sys.setdefaultencoding('utf8')
cgi.test()
| 201 | 77 |
from __future__ import print_function
from __future__ import absolute_import
from lorem_text import lorem
import string
import random
class SamplerUtils:
@staticmethod
def get_random_title():
return lorem.words(random.randrange(1, 4, 1)).upper()
@staticmethod
def get_random_link():
... | 1,213 | 371 |
# Copyright 2020 reinforced_scinet (https://github.com/hendrikpn/reinforced_scinet)
#
# 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.... | 3,553 | 1,071 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
artist_name = models.CharField(max_length=100)
song_name = models.CharField(max_length=100)
description = models.TextField(max_length=280, bla... | 979 | 310 |
# IBM_PROLOG_BEGIN_TAG
#
# Copyright 2019,2020 IBM International Business Machines Corp.
#
# 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/LICENS... | 4,309 | 1,219 |
import os
import requests
import gzip
class MNISTFileLoader():
__base_url = "http://yann.lecun.com/exdb/mnist"
__filenames = {
"train": {
"image": {
"file": "train-images.idx3-ubyte",
"gz": "train-images-idx3-ubyte.gz",
},
"label": {
... | 4,422 | 1,368 |
from .anchor_heads import *
from .necks import sepc | 51 | 17 |
import random
import math
import RNG
import logging
from pymclevel import alphaMaterials, BoundingBox
import toolbox as toolbox
import utility as utility
from Carpet import generateCarpet
from Object import *
def generateHouse(matrix, wood_material, h_min, h_max, x_min, x_max, z_min, z_max, ceiling = None):
logger = ... | 18,350 | 8,026 |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url('^$', views.index, name='index'),
url(r'^neighborhood/(\d+)', views.my_area, name='hood'),
url(r'^neighborhood/(\d+)/join/$', views.join, name='join'),
ur... | 549 | 196 |
# Data Parallel Control (dpctl)
#
# Copyright 2020-2021 Intel Corporation
#
# 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.... | 2,037 | 710 |
#
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
"""
This module transforms data-parallel operations such as Numpy calls into
'Parfor' nodes, which are nested loops that can be parallelized.
It also implements optimizations such as loop fusion, and extends the rest of
compiler analysi... | 102,386 | 31,836 |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from eight import *
import copy
def delete_integer_codes(data):
"""Delete integer codes completely from extracted ecospold1 datasets"""
for ds in data:
if 'code' in ds and isinstance(ds['code'], int):
... | 3,031 | 868 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('feedjack', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='feed',
name='verify_tl... | 905 | 248 |
# AMZ-Driverless
# Copyright (c) 2019 Authors:
# - Huub Hendrikx <hhendrik@ethz.ch>
#
# 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 ... | 7,220 | 2,130 |
"""The crimereports component."""
| 34 | 10 |
import torch
from torch import nn
from mmdet.models.builder import HEADS, build_loss
from mmdet3d.core.bbox.structures import limit_period
@HEADS.register_module()
class LayoutHead(nn.Module):
def __init__(self,
n_channels,
linear_size,
dropout,
... | 4,609 | 1,546 |
import json
from collections import OrderedDict
from io import BytesIO
from typing import Tuple
from django import forms
from django.conf import settings
from django.contrib.staticfiles import finders
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.files.storage impor... | 5,381 | 1,577 |
from __future__ import division
from mmtbx.monomer_library.server import mon_lib_list_cif, geostd_list_cif
from mmtbx.monomer_library.server import merge_and_overwrite_cifs
# ['SS BOND', # short desc.
# # complete desc.
# 'Disulphide bond for CYS-like sulphur atoms within 3A (default) using '
# 'values... | 1,566 | 586 |
#!/usr/bin/env python
#TODO
# add text colors and decorations
# ##############################################################################
#
# Prerequisites
#
# ##############################################################################
#
# ####################################################################... | 20,093 | 6,944 |
from .algorithm import Algorithm, AlgorithmAlgorithmSchema
| 59 | 12 |
#!/usr/bin/env python3
# ########################################################################
# Copyright (c) 2019-2021 Advanced Micro Devices, Inc.
#
# 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 ... | 9,593 | 2,851 |
import argparse, numpy as np, os, pandas as pd
from oasis import *
from saps2 import *
def score_patients(score_name, root, partition, out_dir='scores'):
"""Score a directory of patient timeseries."""
score_dict = eval(score_name+'_score')
ts_files = sorted([f for f in root if f != 'listfile.csv'])
... | 1,761 | 597 |
"""
@author: hugonnet
create shapefiles of union-cascaded tiles to download ASTER L1A data on EarthData Search
"""
import numpy as np
import os
import pandas as pd
from vectlib import write_poly_to_shp, polygon_list_to_multipoly, union_cascaded_multipoly
from tiledivlib import stack_tile_polygon
def main(in_tile_list,... | 1,976 | 758 |
import getopt
import gettext
import locale
import os
import sys
import mailpile.util
import mailpile.defaults
from mailpile.commands import COMMANDS, Command, Action
from mailpile.commands import Help, HelpSplash, Load, Rescan
from mailpile.config import ConfigManager
from mailpile.conn_brokers import DisableUnbrokere... | 6,905 | 2,005 |
#!/usr/bin/env python
#################################################################################$$
# Copyright (c) 2011-2014, Pacific Biosciences of California, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limi... | 4,768 | 1,632 |
import os
import configparser
from unittest import TestCase
import unittest.mock as mock
from esrally import config
from esrally.utils import io
class MockInput:
def __init__(self, inputs):
self.inputs = iter(inputs)
def __call__(self, *args, **kwargs):
null_output(*args, **kwargs)
... | 41,119 | 12,431 |
import pickle
from sklearn.metrics import mean_squared_error, r2_score
import json
import lightgbm as lgbm
import numpy as np
def main():
with open("config.json") as f:
config_dict = json.load(f)
model_path = config_dict["no_inter_model_path"]
explainer_path = config_dict["no_inter_explai... | 1,513 | 559 |
import time
from image_app_core import start_server_process, get_control_instruction, put_output_image
import cv2
import os
import camera_stream
from pid_controller import PIController
from robot import Robot
class FaceTrackBehavior:
"""Behavior to find and point at a face."""
def __init__(self, robot):
... | 3,294 | 1,065 |
import pytest
from opera.error import ParseError
from opera.parser.tosca.v_1_3.operation_implementation_definition import OperationImplementationDefinition
from opera.parser.yaml.node import Node
class TestNormalize:
@pytest.mark.parametrize("data", [1, 2.3, True, (), []])
def test_invalid_data(self, data):
... | 1,201 | 327 |
import mock
from ctera_gateway_openapi.api import logout
from tests.ut import base
class TestApiLogout(base.BaseTest):
def setUp(self):
super().setUp()
login_manager_class_mock = self.patch_call('ctera_gateway_openapi.api.logout.LoginManager')
self.login_manager_instance_mock = login_man... | 546 | 176 |
#!/usr/bin/env python
import platform
import threading
import time
class ScreenState:
ON = 1
OFF = 2
if platform.system() == 'Darwin':
import Quartz
def init():
pass
def screen_state(context):
# thanks to http://stackoverflow.com/a/11511419/683436
d = Quartz.CGSessionCop... | 2,836 | 830 |
"""
make a function that returns the number that appear odd times in an array
"""
import unittest
def merge_ranges( meetings ):
## Meeting(start, end)
#sort the array
meetings.sort()
# make a pointer in the first position
i = 0
# if we receive just one or an empty metting return the array
... | 2,782 | 968 |
from .default import DefaultAttackEval
from .invoke_limit_eval import InvokeLimitedAttackEval
from .chinese_eval import ChineseAttackEval
from .detailed_eval import DetailedAttackEval
| 184 | 56 |
import os, fnmatch, sys
import dill as pickle
import scipy.interpolate as interp
import scipy.optimize as opti
import scipy.constants as constants
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import bead_util as bu
import configuration as config
import transfer_func_util as tf
... | 5,194 | 2,099 |
# The MIT license:
#
# Copyright 2017 Andre Netzeband
#
# 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, modi... | 3,086 | 1,075 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ===------------------------------* Python *------------------------------===
# THIS FILE IS GENERATED BY INVAR. DO NOT EDIT !!!
# ===------------------------------------------------------------------------===
from TestAbcConflict import TestAbcConflict
from... | 11,545 | 4,114 |
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from __future__ import print_function
import unittest
from unittest import TestCase
from pyqrllib.kyber import Kyber
class TestKyber(TestCase):
def __init__(self, *args, **kwa... | 1,038 | 341 |
"""HDR capture sample."""
from zivid import Application, Settings
def _main():
app = Application()
camera = app.connect_camera()
settings = Settings(
acquisitions=[
Settings.Acquisition(aperture=aperture) for aperture in (10.90, 5.80, 2.83)
]
)
with camera.capture(sett... | 418 | 146 |
from gevent import monkey
monkey.patch_all()
import gevent
import gevent.pool
import os
import sys
import glob
import time
import uuid
import ujson
import falcon
import base64
import shutil
import logging
import datetime
import mimetypes
from functools import partial
from . import _utils
while "time_per_example" not... | 13,871 | 3,967 |
"""
json.dumps 与 json.loads 实例
以下实例演示了 Python 数据结构转换为JSON:
"""
import json
data = {
"no": 1,
"name": "SPENCE",
"url": "https://www.google.com"
}
json_str = json.dumps(data)
print("Python 原始数据:", repr(data))
print("JSON对象:", json_str)
# 通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。
#
# 接着以上实例,我们可以将一个JSON编码的字... | 676 | 384 |
#! usr/bin/python
"""
File containing functions for database creation and management
"""
# IMPORTS
import pandas as pd
import sqlite3
def create_db():
print('Inside init_db file')
#df = pd.read_csv('../../Data/cannabis_new.csv')
df = pd.read_csv('Data/cannabis_new.csv')
print(df.head())
df = df.... | 743 | 277 |
# TESTING SCRIPT
import sys
from PySide2.QtWidgets import QApplication
from Views.MainViewController import View
import cv2
def checkQuality(self, contour, filteredFrame):
x, y, w, h = cv2.boundingRect(contour)
roi=filteredFrame[y:h, x:w]
# convert to HSV
for y in range(0, roi.shape[1]):
for x... | 1,223 | 443 |
#import unittest
#from tests.test_add import MyTestCase
| 58 | 20 |
import numpy as np
from numpy import random
from tqdm import tqdm
from src.pollution.tools import max_data
from src.trace_set.database import Database
from src.trace_set.set_hw import TraceSetHW
A = 5
B = 3
DELAY_AMP = 10
def random_delay(traces: np.ndarray, a: int = A, b: int = B, delay_amplitude: int = DELAY_AMP,... | 1,980 | 684 |
""" An extension of django ninja framework, providing a configurable password reset strategy"""
__version__ = "1.0.0"
default_app_config = "django_rest_passwordreset.apps.DjangoRestPasswordResetConfig"
| 203 | 57 |
import random
import allure
from data.contacts import testdata as contact_testdata
from data.groups import testdata as group_testdata
from model.contact import Contact
def test_add_contact_into_group(app, db, check_ui):
with allure.step("Given a non-empty group list and a non-empty contact list"):
if not... | 1,375 | 414 |
from django.conf import settings
from exact.users.models import Team
from exact.tagger_messages.models import TeamMessage
from django.db.models import Q
def base_data(request):
show_datasets = settings.SHOW_DEMO_DATASETS
if request.user.is_authenticated:
my_teams = Team.objects.filter(members=request... | 898 | 309 |
#!/usr/bin/env python3
import io
from setuptools import setup
with io.open('README.md', encoding='utf-8') as f:
README = f.read()
with io.open('HISTORY.md', encoding='utf-8') as f:
HISTORY = f.read()
setup(
name='Flask-Redis',
version='0.1',
url='https://github.com/imcery/flask-redis',
auth... | 1,538 | 502 |
import math
import numpy
# ROS main library
import rospy
# Parameters
from ControlParameters import ControlParameters
# PID controller (SISO)
from PIDController import PIDController
# Low-pass filter
from ..common.LowPassFilter import LowPassFilter
class Controller(object):
"""MIMO controller to compute drone att... | 4,859 | 1,938 |
char1 = input()
char2 = input()
char3 = input()
print(f"{char1}{char2}{char3}") | 80 | 34 |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import uuid
import os
import cv2
import rospy
TRAFFIC_LIGHTS = ['Green', 'Red', 'Yellow', 'Unknown']
home = os.path.expanduser("~")
class TLClassifier(object):
def __init__(self, is_site):
#TODO load classifier
if is... | 6,786 | 2,189 |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="aoctools",
version="0.0.1",
author="Stefan Kruger",
author_email="stefan.kruger@gmail.com",
description="Utility classes and algorithms for AoC",
long_description=long_description,
... | 639 | 210 |
def add(x,y):return x+y
params = (1,2)
print add(*params)
def hello(**params):
print params
print '='*30
params = {'name':'Sir Robin','greeting':'Well met'}
hello(**params)
def with_stars(**kwds):
print kwds['name'],'is',kwds['age'],'year old'
def without_stars(kwds):
print kwds['name'],'is',kwds['age'],'years o... | 414 | 176 |
import collections
class Solution(object):
def movesToChessboard(self, b):
N = len(b)
if any(b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j] for i in range(N) for j in range(N)):
return -1
if not N / 2 <= sum(b[0]) <= (N + 1) / 2:
return -1
if not N / 2 <= sum(b[i][0... | 2,717 | 1,011 |
"""The MathLinkFlags class is a single object that handles data type translation from flag ints
"""
from decimal import Decimal as decimal
import os
##############################################################################################
# ... | 32,085 | 9,985 |
import dcase_util
import pandas
from dabstract.dataprocessor.processing_chain import ProcessingChain
from dabstract.dataset.dataset import Dataset
from dabstract.dataprocessor.processors import *
from dabstract.utils import stringlist2ind
class DCASE2018Task5(Dataset):
"""DCASE2020Task1A dataset
This class ... | 3,379 | 973 |
# Author: vvlachoudis@gmail.com
# Vasilis Vlachoudis
# Date: 20-Oct-2015
# ##########################################################
# FlatCAM: 2D Post-processing for Manufacturing #
# File modified: Marius Adrian Stanciu #
# Date: 3/10/2019 #
# ... | 28,568 | 8,821 |
ASK_CFPB_H1 = {
# Initial clusters that went live on 12/4/18,
# testing the full set of pages in each cluster:
18: [
103, 160, 187, 337, 731, 767, 951, 1157, 1161, 1403, 1405, 1439, 1447,
1567, 1695,
],
34: [
104, 105, 130, 205, 747, 841, 1423, 1791,
],
38: [
... | 907 | 644 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio App ILS Circulation views."""
from __future__ import absolute_import, print_function
from functools i... | 4,001 | 1,240 |
import re
from datetime import datetime
import pytest
from pydantic import ValidationError
from node.blockchain.facade import BlockchainFacade
from node.blockchain.inner_models import (
BlockMessage, BlockMessageUpdate, PVScheduleUpdateBlockMessage, PVScheduleUpdateSignedChangeRequest
)
from node.blockchain.types... | 3,287 | 975 |
"""
Contains commands for lightweight text editing of an ASDF file.
"""
import io
import os
import re
import shutil
# Marked safe because the editor command is specified by an
# environment variable that the user controls.
import subprocess # nosec
import sys
import tempfile
import yaml
from .. import constants, g... | 11,606 | 3,283 |
import json
import os
import cv2
import numpy as np
import pandas as pd
from pycocotools.coco import COCO
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
from anomaly_detector import crea... | 12,765 | 4,084 |
import pandas as pd
import datetime
import urllib
import json
import apikey
def apply_request(req_str: str):
""" Request to API. Returns json
"""
assert isinstance(req_str, str)
http = urllib.request.urlopen(req_str)
return json.loads(http.read().decode('utf-8'))
def daily_prices_pattern(symb... | 1,174 | 386 |
HEADERS_MRCONSO = [
'cui', 'lat', 'ts', 'lui', 'stt', 'sui', 'ispref', 'aui', 'saui',
'scui', 'sdui', 'sab', 'tty', 'code', 'str', 'srl', 'suppress', 'cvf'
]
HEADERS_MRSTY = [
'cui', 'sty', 'hier' 'desc', 'sid', 'num'
]
NEGATIONS = {'none', 'non', 'neither', 'nor', 'no', 'not'}
ACCEPTED_SEMTYPES = {
'... | 2,290 | 1,066 |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.Results.test_XraySpectraSpecimen
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Tests for the module `XraySpectraSpecimen`.
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""... | 2,147 | 739 |
import os
import base64
import csv
import datetime
import time
import json
import re
from pprint import pformat
from PyPDF4 import PdfFileReader, PdfFileWriter
from typing import cast
from looker_sdk import models
from main import app
from core import action_hub, get_input_file_name, get_output_file_name, get_temp_fil... | 16,015 | 7,064 |
from .SketchConstructsView import SketchConstructsView
| 55 | 17 |
# Think about another ways
def mincoin(coins, target):
# coins: positive nums
coins.sort()
cand = set(coins)
minnums = [0] * target
cnt = 0
while len(cand) != 0:
cnt += 1
newcand = set()
for c in cand:
minnums[c] = cnt
for coin in coins:
... | 620 | 200 |
import re
import json
import collections
import ocdsmacaw.common.tools as tools
from ocdsmacaw.common.common import common_checks_context, get_additional_codelist_values
from django.utils.html import mark_safe, escape, conditional_escape, format_html
import commonmark
import bleach
validation_error_lookup = {
... | 22,209 | 6,674 |
import asyncio
async def coro():
await asyncio.sleep(1)
print("Hello world")
return 42
res = asyncio.run(coro())
print(res)
#print(type(coro))
#print(type(coro()))
| 179 | 74 |
from rest_framework import permissions, status, serializers
from rest_framework.response import Response
from rest_framework.views import APIView
from reservationsystem.models import BusStation, BusSeat, Trip
from reservationsystem.services.trips import get_all_trips, get_available_seats
class TripListApi(APIView):
... | 4,893 | 1,313 |
from flask import render_template
from db.queries import get_last_measurement_pack
def wind_page():
wind_data = get_last_measurement_pack('wind_data', '0')
return render_template("weather_station/wind_dashboard.html",
avg_rps=wind_data['avg_rps'],
max_rp... | 1,072 | 320 |
from .source import Source
| 27 | 7 |
"""Session router dependency-injection wire-up."""
from fastapi import Depends
from starlette.datastructures import State
from typing import cast
from opentrons.hardware_control import ThreadManager, API as HardwareAPI
from robot_server.service.dependencies import get_app_state, get_hardware
from .engine_store impor... | 1,284 | 393 |
#!/usr/bin/env python3
# This script regrids raw MALDI-TOF MS files to a fixed grid based on average weights
from os import listdir, path
from os.path import isfile, join
import argparse
import numpy as np
import pandas as pd
import multiprocessing
from functools import partial
np_grid_mz = np.array([
... | 202,377 | 192,860 |
import math
angulo = float(input('Digite o ângulo que você deseja: '))
radiano = math.radians(angulo)
print('O ângulo de {:.1f} tem o SENO de {:.2f}'.format(angulo, math.sin(radiano)))
print('O ângulo de {:.1f} tem o COSSENO de {:.2f}'.format(angulo, math.cos(radiano)))
print('O ângulo de {:.1f} tem a TANGENTE de {:... | 360 | 155 |
# Lecture 5, Problem 3
def recurPowerNew (base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float; base^exp
'''
if (exp == 0):
return 1
elif (exp % 2 == 0):
return recurPowerNew (base * base, exp / 2)
elif (exp % 2 == 1):
return base * recurPower... | 339 | 129 |
#!/usr/bin/env python3
"""Blackjack.
Create a function that takes a list of card numbers and checks
if the sum of their value exceeds 21. If the sum exceeds 21,
return True and if the sum is under or equal to 21,
return False. Values of the cards are as follows:
* 2-10 are their value.
* J-K (face cards) count as 10... | 1,210 | 466 |
# -*- coding: utf-8 -*-
__author__ = "eduard.snezhko@gmail.com"
import os
import pydicom
import shutil
import requests
import json
from test_auth_app.core.resource_manager import ResourceManager
def make_dir_if_not_exists(dirname_, clean_if_exists_=True):
"""
create directory if directory is absent
:para... | 5,483 | 1,691 |
"""
Created on Tue Jun 16 16:41:07 2020
Usage: python detect_faces_video.py [file_name]
Parameters
----------
file_name: str
image file name
@author: KamranBinaee
"""
import cv2
import numpy as np
import argparse
import os
# Set the input arguments to the function and their typ... | 2,244 | 882 |
import tensorflow as tf
from hamiltonian import Hamiltonian
import itertools
import numpy as np
import scipy
import scipy.sparse.linalg
class HeisenbergJ1J2(Hamiltonian):
"""
This class is used to define Heisenberg J1-J2 model.
Nearest neighbor interaction along x-, y- and z-axis with magnitude J_1,
n... | 13,705 | 4,438 |
import numpy as np
%%time
x = np.random.random((20000, 20000))
y = x.mean(axis=0)
| 83 | 43 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.15.6
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class IstioNetwo... | 5,885 | 1,627 |
# coding: utf-8
from django.conf import settings
from django_th.tests.test_main import MainTest
from th_trello.models import Trello
from th_trello.forms import TrelloProviderForm, TrelloConsumerForm
from th_trello.my_trello import ServiceTrello
from trello import TrelloClient
from unittest.mock import patch
class... | 4,995 | 1,580 |
#!/usr/bin/env python
"""
This script helps to flip videos horizontally for data augmentation.
Generally, it can be used to quickly double the size of your dataset, or,
in the case where you've collected data for an action performed on a specific side,
you can flip these videos and use them to classify the opposite si... | 1,685 | 547 |
import itertools
from typing import List
import pytest
from httpcore._utils import exponential_backoff
@pytest.mark.parametrize(
"factor, expected",
[
(0.1, [0, 0.1, 0.2, 0.4, 0.8]),
(0.2, [0, 0.2, 0.4, 0.8, 1.6]),
(0.5, [0, 0.5, 1.0, 2.0, 4.0]),
],
)
def test_exponential_backoff... | 464 | 202 |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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... | 2,897 | 837 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def computeLoss(ys, xs, W):
data_sz = len(ys)
sq_err = (np.dot(W.T,xs) - ys)**2
avg_loss = np.sqrt(np.sum(sq_err))/data_sz
return avg_loss
def computeGradNorm(ys,xs, W):
data_... | 1,726 | 743 |
# This file is currently unused
import bpy
def import_sequence(is_dsq, shape, seq):
if is_dsq:
name = shape.names[seq.nameIndex]
else:
name = seq.name
act = bpy.data.actions.new(name)
flags = ["priority {}".format(seq.priority)]
if seq.flags & Sequence.Cyclic:
fla... | 3,840 | 1,210 |
import random
from r2c_isg.structures import Dataset
def sample(ds: Dataset, n: int,
on_versions: bool = True, seed: str = None) -> None:
"""Samples n projects in place."""
# seed random, if a seed was provided
if seed:
random.seed(seed)
# select a sample of versions in each proj... | 1,170 | 336 |
import pytest
pytest.importorskip("flask")
views = pytest.importorskip("flask.views")
contrib = pytest.importorskip("dependencies.contrib.flask")
http_methods = views.http_method_funcs
http_methods_no_head = http_methods - {"head"}
@pytest.fixture()
def app():
from flask_project.app import create_app
app... | 908 | 294 |
def _(string):
return string
| 34 | 13 |
from .build import build_dataset
from .cse import CocoCSE
from .deep_fashion import DeepFashion | 95 | 29 |
#!/usr/bin/env python
#-*- coding:utf8 -*-
#Author: Leo
#Email: leoliuabc@gmail.com
#Date: 2018-05-05
from django.conf.urls import url
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^stores/$', views.s... | 643 | 257 |
from organism import Organism
import networkx as nx
def load(string_id,ppi_infile_path,threshold,ess_infile_path=None,name=None):
'''
Parameters
------------
string_id - The STRING database ID of the orgaism.
ppi_infile_path - Path of the file containing the protein protein interaction (PPI) data.
For this pack... | 1,731 | 667 |
# Copyright 2020 Adap GmbH. 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 applicable law or ag... | 7,001 | 1,665 |
from lab3_values import values
from struct import pack
from binascii import hexlify
def mix(x):
return (x + ((x >> 5)^(x<<4))) & 0xffffffff
fn = 0x57415343
fprev = 0x41484148
#fprev = 0x57415343
#fn = 0x41484148
for x in values[::-1]:
tmp = (fn + (mix(fprev) ^ x)) & 0xffffffff
fn = fprev
f... | 428 | 215 |