text string | size int64 | token_count int64 |
|---|---|---|
#!api/api.py
import os
import datetime
from flask import Flask, jsonify, abort, make_response, render_template
from flask_restful import Api, Resource, reqparse, fields, marshal
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity, create_refresh_token,
jwt_refre... | 4,448 | 1,450 |
#A very simple poblation simulator made to study what happen when a society reaches the food-consumption limit.
#Made by ElBarto27. Feel free to reproduce this script giving the correspondent credits.
from scipy.stats import norm
import random
#Opening and clearing the file where the code will write how many peop... | 3,034 | 857 |
import balanced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
card_hold = balanced.CardHold.fetch('/card_holds/HL4iHX8OBNW7nVsu6MqyjnQ9') | 157 | 81 |
from memoize.configuration import DefaultInMemoryCacheConfiguration
from memoize.wrapper import memoize
@memoize(configuration=DefaultInMemoryCacheConfiguration())
async def cached():
return 'dummy'
| 205 | 53 |
# from skimage.io import imread
import datetime
import os
import pickle
import sys
from os import mkdir
# from torchsummary import summary
from os.path import join
from time import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
import src.models.utils.utils as utils
import torch
import torch.nn as ... | 13,147 | 4,551 |
# coding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 by Shuo Li (contact@shuo.li)
#
# 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 li... | 23,407 | 7,832 |
#! /usr/bin/env python3
import os
import sys
# Ayaneをインポート
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(script_dir + "/../../Ayane/source")
import shogi.Ayane as ayane
# その他必要なものをインポート
import time
import glob
from natsort import natsorted
from collections import defaultdict
import argparse
... | 7,060 | 2,878 |
import pytest
from ansible_host import AnsibleHost
def test_snmp_queues(ansible_adhoc, duthost, creds, collect_techsupport):
lhost = AnsibleHost(ansible_adhoc, 'localhost', True)
hostip = duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars['ansible_host']
snmp_facts = lhost.snmp_fac... | 624 | 220 |
# Project Title: Kenneth E. Batcher Historical Work OCR
# Project Description: Project to conduct OCR on the historical work of PP-father Kenneth E. Batcher
# Author: Matthew E. Miller
# Date: 02/01/2020 10:38:31
# Medium: https://medium.com/@matthew_earl_miller (where this is being published)
# Github: https://github... | 2,193 | 715 |
#try:
# import eventlet
# eventlet.monkey_patch()
#except:
# pass
import falcon
import json
try:
import ujson as json
except ImportError:
pass
from auth.CAS.authorization import Authorization
class AuthComponent(object):
def process_request(self, req, resp):
"""Process the request befo... | 6,272 | 1,882 |
from __future__ import division
if 1:
# deal with old files, forcing to numpy
import tables.flavor
tables.flavor.restrict_flavors(keep=['numpy'])
import os, sys, math
import warnings
import pkg_resources
from tvtk.api import tvtk
from tvtk.common import configure_input_data
import numpy
import numpy as n... | 53,035 | 16,555 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 16,921 | 4,788 |
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.model_selection import train_test_split
from sktime.classification.interval_based import SupervisedTimeSeriesForest
from sktime.datasets import load_gunpoint, load_italy_power_demand
def test_y_proba_on_gunpoint():
X, y = load_gunpoint(return_X_y=True)
... | 2,895 | 1,064 |
from epidag.fitting.alg.fitter import EvolutionaryFitter
from epidag.fitting.alg.genetic import *
from epidag.util import resample
class GA(EvolutionaryFitter):
DefaultParameters = {
'n_population': 100,
'n_generation': 20,
'p_mutation': 0.1,
'p_crossover': 0.1,
... | 5,883 | 2,011 |
#!/usr/bin/python
#
# BROKEN
# This script should run the traditional pylogo user inferface.
# It worked well while pylogo was in python2 and relying on python mega widgets
# (Pmw) version 1.3. Pmw1.3 is for python2 only and I don't have the time to
# try getting Pmw2 running (https://pypi.org/project/Pmw/)
#
# remembe... | 467 | 169 |
from .Pavel import Pavel
#from .Juergen1 import Juergen1
#print('%s imported'%__name__)
| 88 | 35 |
# TODO: Refactor merge-logging into TxInfoTransformer
| 54 | 16 |
from .src.models import * | 25 | 8 |
import os
import sys
import sqlite3
import yfinance as yf
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from scheduled_tasks.get_popular_tickers import full_ticker_list
from helpers import *
conn = sqlite3.connect(r"database/database.db", check_same_thread=False)
db = conn.cursor()
def short_volum... | 1,430 | 475 |
"""
WSGI config for invetronic project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
path = '/srv/www/vhosts/d... | 521 | 192 |
#!/user/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/2/13 0013 20:08
# @Author : CarryChang
# @Software: PyCharm
# @email: coolcahng@gmail.com
# @web :CarryChang.top
path_list = ['neg_all.txt', 'pos_all.txt']
train_all = open('train_all.txt', 'w', encoding='utf-8')
for path in path_list:
if 'pos' in p... | 665 | 259 |
from dataclasses import dataclass
from dbt.adapters.spark.column import SparkColumn
@dataclass
class DatabricksColumn(SparkColumn):
def __repr__(self) -> str:
return "<DatabricksColumn {} ({})>".format(self.name, self.data_type)
| 244 | 80 |
"""Handles incoming cloudtrail requests, invokes methods, returns responses."""
import json
from moto.core.responses import BaseResponse
from .models import cloudtrail_backends
from .exceptions import InvalidParameterCombinationException
class CloudTrailResponse(BaseResponse):
"""Handler for CloudTrail requests ... | 7,456 | 2,294 |
from multiprocessing.pool import ThreadPool
import datetime
import numpy as np
import math
def __is_divisible__(a,b):
if a%b == 0:
return 1
return 0
def isPrime_n(a):
#is prime noob
k=0
for i in range(2,a-1):
if __is_divisible__(a,i) == 1:
k=1
break
if k... | 1,661 | 657 |
from utils.admin import HiddenModelAdmin, iportalen_admin_site, iportalen_superadmin_site
from django.contrib import admin
from .models import Tag
# Register your models here.
iportalen_admin_site.register(Tag, HiddenModelAdmin)
iportalen_superadmin_site.register(Tag)
| 271 | 83 |
from pwn import remote
r = remote('2018shell2.picoctf.com', 45008)
r.recvuntil('Here is a sample cookie: ')
encrypted_cookie = r.recvline()[:-1]
for index in range(0, len(encrypted_cookie), 32):
print "%d : %s"%(index, encrypted_cookie[index:index+32])
| 261 | 113 |
import copy
import datetime
import json
import logging
import uuid
from blake3 import blake3
from google.cloud import bigquery
from exceptions import (
ConfigurationAlreadyExists,
InstallationWithSameNameAlreadyExists,
SensorTypeWithSameReferenceAlreadyExists,
)
logger = logging.getLogger(__name__)
SE... | 11,277 | 2,851 |
N = int(input())
current = []
x = []
y = []
nums = [int(a) for a in input().split()]
for n in nums:
if n % 2 != 1:
x.append(n)
else:
current.append(x)
x = []
current.append(x)
for l in current:
y.append(sum(l))
print(max(y)) | 234 | 113 |
import vlc
p = vlc.MediaPlayer("file: Chirping.mp3")
p.play() | 61 | 27 |
##Copyright (c) 2014 - 2020, The Trustees of Indiana University.
##
##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 a... | 2,091 | 726 |
"""
In this class we use hyperparameter search to find parameters needed in our model.
Depending on the input model we sample parameters from a random distribution.
The sampling rate can be increased.
The model with the best internally defined accuracy is picked.
To increase robustness we use cross ... | 3,067 | 924 |
# -*- coding: utf-8 -*-
"""
(c) 2017 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
from __future__ import unicode_literals, absolute_import
import os
import subprocess
import unittest
import six
REPO_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
cla... | 1,077 | 374 |
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n <= 1:
return n
dp = [0, 1]
for i in range(2, n + 1):
if i % 2 == 0:
dp.append(dp[i // 2])
else:
dp.append(dp[i // 2] + dp[i // 2 + 1])
return max(dp)... | 321 | 121 |
from setuptools import setup
setup(name='geoRpro',
version='0.1',
description='Library to process geo raster data',
url='https://github.com/ESS-uzh/geoRpro.git',
author='Diego Villamaina',
author_email='diego.villamaina@geo.uzh.ch',
license='MIT',
packages=['geoRpro'],
z... | 335 | 117 |
#!/home/twixtrom/miniconda3/envs/wrfpost/bin/python
import sys
from PWPP import wrfpost
import numpy as np
from metpy.units import units
# import xarray as xr
infile = sys.argv[1]
outfile = sys.argv[2]
variables = ['temp',
'dewpt',
'uwnd',
'vwnd',
'wwnd',
... | 792 | 301 |
'''
Created on 05 May 2010
@author: ejwillemse
'''
from copy import deepcopy
#===============================================================================
#
#===============================================================================
class SinlgeRouteModifications(object):
def __init__(self, in... | 32,575 | 10,666 |
# coding: utf-8
from __future__ import print_function
import os
import subprocess
def gsm_decode(hexstr):
return os.popen('echo %s | xxd -r -ps | iconv -f=UTF-16BE -t=UTF-8' % hexstr).read()
def init_gsm():
retcode = subprocess.call("wb-gsm restart_if_broken", shell=True)
if retcode != 0:
raise ... | 1,054 | 393 |
import requests
def download(url, file_name):
with open(file_name, 'wb') as handle:
response = requests.get(url, stream=True)
if not response.ok:
print(response)
for block in response.iter_content(1024):
if not block:
break
handle.write(... | 400 | 117 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MCMC-estimation of status transition rates from IUCN record
Created on Mon Oct 28 14:43:44 2019
@author: Tobias Andermann (tobias.andermann@bioenv.gu.se)
"""
import numpy as np
np.set_printoptions(suppress=True)
import pandas as pd
import os,sys
import datetime
from ... | 25,128 | 8,303 |
"""
Type inference
"""
| 23 | 9 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" User related actions """
from flask import Blueprint, render_template, redirect, abort
from ....data.users import User
from ....extensions.init_models import db
from ....extensions.is_admin_decorator import is_user_admin
# User actions Blueprint registration
user_action... | 1,904 | 587 |
import os
import shutil
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from future.utils import lmap
HIDDEN_LAYER_SIZE = 30
class Dqn():
def __init__(self, input_size, nb_action, gamma):
try:
shutil.rmtree("train/")
except OSError:
print... | 4,200 | 1,362 |
# coding:utf-8
# import os
import re
import sublime
from unittest import TestCase
VERSION = sublime.version()
class TestBase(TestCase):
'''Super class includes common settings and functions. This class doesn't include any tests.'''
def setUp(self):
self.view = sublime.active_window().new_file()
... | 3,022 | 1,029 |
from bareasgi import Application
import bareasgi_jinja2
from easydict import EasyDict as edict
import jinja2
import pkg_resources
import yaml
from .yaml import initialize_types
from .auth_controller import AuthController
from .auth_service import AuthService
from .jwt_authentication import JwtAuthentication
def make_... | 1,597 | 511 |
import numpy as np
import poppy
from poppy.optics import AnalyticImagePlaneElement
from poppy.poppy_core import Wavefront, PlaneType, BaseWavefront
from astropy import units as u
class ZernikeMaskWFS(object):
def __init__(self,
name='Zernike Mask WFS',
radius_in_arcsec=0.010,
... | 2,530 | 800 |
from .A1 import get_ticker_data, calc_moving_average, ma_backtest, plot
from .vectorized_backtest import The_Vectorized_Backtest
| 129 | 44 |
from django.contrib import admin
from .models import NormEntry, MissingEntry
admin.site.register(NormEntry)
admin.site.register(MissingEntry)
| 144 | 43 |
import matplotlib.pyplot as plt
import numpy as np
strat_list = []
topology = 'facebook'
folder = 'pre-cured-equal/'
strat_list.append({
'red_strat': 'bot',
'black_strat': 'uniform',
})
strat_list.append({
'red_strat': 'bot',
'black_strat': 'pure_centrality_threshold',
})
strat_list.append({
're... | 2,192 | 850 |
#
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applicab... | 3,049 | 1,026 |
# Copyright 2015 Google Inc.
#
# 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 agreed to in writing, ... | 977 | 283 |
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
import pytest
from ocean_lib.ocean.util import to_base_18
from ocean_lib.web3_internal.contract_base import ContractBase
from ocean_lib.web3_internal.contract_handler import ContractHandler
from ocean_lib.web3_internal.wallet import Wal... | 2,045 | 625 |
"""
Get the song lyrics via users' data from genius.com.
"""
import requests
from bs4 import BeautifulSoup
try:
from domains.genius.config import GENIUS_DOWNLOAD_URL
from domains.genius.utils import (
make_suitable_url_parameters,
remove_punctuation_symbols,
)
from domains.songlyrics.so... | 2,207 | 735 |
import vim
# Setup `vartabstop` so that columns line up.
vim.command('command! TabsLineUp py3 ' + __name__ + '.tabs_line_up()')
def tabs_line_up():
lengths = []
for line in vim.current.buffer:
if '\t' not in line:
continue
parts = line.split('\t')
lengths.app... | 451 | 170 |
# You are given a two-dimensional array of potentially unequal height and width.
# It contains only 0s and 1s. This array represents a map: 0s are land, and 1s are water.
# A "river" on this map consists of any number of contiguous, adjacent water squares,
# where "adjacent" means "above", "below", "to the left of",... | 2,397 | 893 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-14 15:42
from __future__ import unicode_literals
from django.db import migrations, models
import django_countries.fields
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('accounts', '0023_demographi... | 4,795 | 1,695 |
from flask_restplus import Namespace, Resource, fields, marshal_with
from infrastructure.DatasetUtils import get_datasets
api = Namespace('datasets')
resource_fields = {
'name': fields.String,
'type': fields.String,
'size': fields.Integer,
'createdAt': fields.DateTime('iso8601'),
'lastModifiedAt'... | 485 | 159 |
from datetime import date, datetime, timedelta
from airtech.apps.tickets.models import Ticket
def get_tickets_remaining_one_day():
# Get all tickets remaing less than 24 hours
yesterday = date.today() - timedelta(days=1)
all_awaiting_tickets = Ticket.objects.filter(
notification_sent=False, statu... | 946 | 290 |
from pylut import * | 19 | 7 |
import cv2
import numpy as np
class Warp:
@staticmethod
def warp_image(img, tx_src, tx_dest, **kwargs):
img_size = (img.shape[1], img.shape[0])
tx_src = tx_src.astype(np.float32)
tx_dest = tx_dest.astype(np.float32)
# Calculate the transformation matrix and it's inverse transf... | 1,029 | 413 |
from django.utils.decorators import available_attrs
from functools import wraps
def require_unbanned_user(view_func):
"""
Marks view function to be checked by Ban middleware
"""
def wrapped_view(*args, **kwargs): ... | 671 | 146 |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: agandong4
@license: (C) Copyright 2013-2019, Node Supply Chain Manager Corporation Limited.
@contact: agandong4@gmail.com
@software: garner
@file: spider.py
@time: 2019-03-12 21:39
@desc:
'''
import requests
from requests.exceptions import RequestException
import re... | 1,609 | 591 |
#!/usr/bin/env python3
################################################################################
# Copyright 2022 FZI Research Center for Information Technology
#
# 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... | 15,627 | 4,147 |
# 请你来实现一个 atoi 函数,使其能将字符串转换成整数。
# 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:
# 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
# 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
# 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。
# 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换,即无法进行有效转换。
# 在任何... | 1,244 | 827 |
import owl as owl
import rdflib
import json
from flask import Flask, render_template, jsonify, request
from rdflib.plugins.sparql import prepareQuery
from rdflib.graph import Graph
def stringFilter(s):
start = "("
end = ""
return s[s.find(start) + len(start):s.rfind(end)]
def search(key):
g... | 1,635 | 454 |
import time
import board, busio
import adafruit_mprls
i2c = busio.I2C(board.SCL, board.SDA)
mpr = adafruit_mprls.MPRLS(i2c)
THRESH_LOW = 10 # delta in hPa
THRESH_HIGH = 10 # delta in hPa
def pressure_sensor_init(count=10, delay=0.1):
reading = 0
for _ in range(count):
reading += mpr.pressure
... | 1,254 | 444 |
from collections import deque
from onapy.tracker2d import TrackDetectionFusedTracker
from onapy.tracker3d import create_tracker, get_tracker_names
import time
import click
import cv2
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
print(cv2.__version__)
import cupoch as cph
from mmcv.runner impor... | 6,432 | 2,158 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 测试文件或目录是否存在
Desc :
"""
import os
import time
def file_existence():
print(os.path.exists('/etc/passwd'))
print(os.path.exists('/tmp/spam'))
print(os.path.isfile('/etc/passwd'))
print(os.path.isdir('/etc/passwd'))
print(os.path.islink('/us... | 589 | 244 |
import time
import cv2
import logging
import signal
from threading import Thread, Lock, Condition
import cv2
import numpy
def exit_gracefully(sig, frame):
global running
running = False
logger.info('Ctrl+C detected: exit procedure commenced!')
class WebcamVideoStream:
def __init__(self, logger, src=... | 2,600 | 829 |
import pyaudio
import time
import numpy as np
from matplotlib import pyplot as plt
import scipy.signal as signal
print("Start run")
CHANNELS = 1
RATE = 44000
p = pyaudio.PyAudio()
fulldata = np.array([])
dry_data = np.array([])
def main():
stream = p.open(format=pyaudio.paFloat32,
channels=... | 2,207 | 767 |
"""
Film Mapper Module
Use this module to map the nearest movie filming spots for any location and year.
(c) Yuriy Nefedov
"""
import random
import pandas
import folium
import geopy
from haversine import haversine
geolocator = geopy.Nominatim(user_agent="UCU OP Lab 2 Nefedov")
CLOSEST_FILENAME = "closest10.csv"... | 7,102 | 2,297 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Myme and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
form_grid_templates = {
"packing_list_data_unchecked": ... | 13,291 | 6,049 |
"""
Built in functions
String related Functions,
upper, lower, title, capitalize, join, split
Integer related Functions,
abs, round, pow, div, divmod
Data Structure related Functions
min, max, count,len, zip, sorted
Common Functions,
sum, id, input, type, isinstance, prin... | 1,769 | 710 |
class Tries:
def __init__(self):
self.tree = {}
def insert(self,word):
a = self.tree
for c in word:
if c not in a:
a[c] = {}
a = a[c]
a['#'] = True
def start(self,pre):
a = self.tree
for i,c in enumerate(pre):
... | 745 | 233 |
import tensorflow as tf
from tensorflow.contrib.seq2seq import AttentionMechanism
from tensorflow.contrib.seq2seq.python.ops.attention_wrapper import\
_prepare_memory
class NestedMultiLevelAttn(AttentionMechanism):
'''
memory in the format of [b x k x n x h], where we have (k x n) tokens
divided into k... | 2,536 | 865 |
import numpy as np
import cv2
# camera matrix
mtx = [[647.048823, 0.000000, 326.544754], [0.000000, 645.959963, 234.463113], [0.000000, 0.000000, 1.000000]]
# distortion
dist = [0.026716, -0.114498, 0.001072, -0.004303,0.000000]... | 895 | 429 |
from typing import List
import heapq
class Node:
def __init__(self, val:int):
self.val = val
self.cnt = 1
def __lt__(self, other):
return self.cnt < other.cnt
def __eq__(self, other):
return self.cnt == other.cnt
class Solution:
def topKFrequent(self, nums: List[in... | 1,125 | 381 |
__all__ = ['parseArgs', 'match']
import re
from collections import OrderedDict
from tron import Misc
from .Exceptions import ParseException
from .keys import eatAString
# Match " key = STUFF"
arg_re = re.compile(
r"""
^\s* # Ignore leading space
(?P<key>[a-z_][a-z0-9_-]*) # Mat... | 4,864 | 1,540 |
# Futu Algo: Algorithmic High-Frequency Trading Framework
# Copyright (c) billpwchan - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Bill Chan <billpwchan@hotmail.com>, 2021
import unittest
import pandas as pd
from str... | 1,496 | 501 |
import jwt
from django.conf import settings
from rest_framework.status import (HTTP_200_OK, HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED)
from rest_framework import viewsets
from django.contrib.auth.hashers import check_password
from adminapp.models import (Admin)
from adminapp.seriali... | 5,916 | 1,693 |
import tensorflow as tf
from numba import njit
import numpy as np
@njit
def each_evidence(y_, f, fh, v, s, vh, N, D):
"""
compute the maximum evidence for each class
"""
alpha = 1.0
beta = 1.0
lam = alpha / beta
tmp = (vh @ (f @ y_))
for _ in range(11):
gamma = (s / (s + lam)).... | 1,972 | 805 |
#!/usr/bin/python
import cgi
import MySQLdb
import Cookie
import datetime
import random
cookie = Cookie.SimpleCookie()
cookie["session"] = random.randint(1,1000000)
expires = datetime.datetime.now() + datetime.timedelta(days=1)
cookie["session"]["expires"] = expires.strftime('%a, %d %b %Y %H:%M:%S') # Wdy, DD-Mon-YY... | 5,616 | 1,571 |
import rose.profile.profile as prof
import rose.profile.fields as fields
class TestProfile(object):
def test_profile_instantiation(self):
profile = prof.Profile("133750022779961344")
assert profile._id == "133750022779961344"
def test_profile_generate_empty_profile(self):
profile = pro... | 1,796 | 596 |
#!/usr/bin/python
import os
import sys
import csv
import argparse
import subprocess
from Queue import Queue
from threading import Thread
from time import sleep
import StringIO
from Bio import SeqIO
from Bio.AlignIO import convert
from Bio.Phylo import read
import pdb
def parse_cli():
parser = argparse.ArgumentP... | 5,578 | 1,891 |
import sys
from boto3.session import Session
from .models import Dataset
from .utils import get_headers
def get_instances_as_table(profile=None, region_name='us-east-1'):
session = Session(profile_name=profile)
ec2 = session.resource('ec2')
data = extract_data_from_objects(ec2.instances.all())
# enr... | 2,669 | 828 |
import json
import re
from urllib.parse import urlencode
from hashlib import md5
import pymongo
from bs4 import BeautifulSoup
from gevent import os
from requests.exceptions import RequestException
import requests
from config import *
from multiprocessing import Pool
from json.decoder import JSONDecodeError
client = pym... | 3,035 | 976 |
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo 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... | 1,652 | 492 |
# -*- coding: utf-8 -*-
# =============================================================================
# (c) Copyright 2020, Dynamic Graphics, Inc.
# ALL RIGHTS RESERVED
# Permission to use, copy, modify, or distribute this software for any
# purpose is prohibited without specific, written prior permission from
# ... | 1,114 | 319 |
from typing import NamedTuple, Any, List
from BasicORM.connection import DataBaseConnection
from BasicORM.validate import BaseModelValidations
class FilterConditional(NamedTuple):
field: str
conditional: str
value: Any
# class DefineBaseModel(object):
class PostOperations(DataBaseConnection):
def ... | 2,898 | 836 |
import typing
__author__ = "Jérémie Lumbroso <lumbroso@cs.princeton.edu>"
__all__ = [
"split_name",
]
def split_name(name: str) -> typing.Tuple[str, str]:
"""
Returns a likely `(first, last)` split given a full name. This uses
very simple heuristics, and assumes Western usage.
:param name: A ... | 775 | 273 |
#!/usr/bin/env python
# coding: utf-8
import time
import csv
import subprocess
import pandas as pd
import argparse
class QUESTION02:
index = 1
timeout_times = 1
def __init__(self, timeout_times):
self.timeout_times = timeout_times
print('timeout_times=' + self.timeout_times)
sel... | 2,189 | 821 |
"""empty message
Revision ID: 3c4f7702a459
Revises: 5a24a4aa5eb3
Create Date: 2015-07-10 23:59:20.856464
"""
# revision identifiers, used by Alembic.
revision = '3c4f7702a459'
down_revision = '5a24a4aa5eb3'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... | 1,002 | 374 |
"""
.. module:: FunctionUtils
:synopsis: Collection of mixed utility classes and functions
.. moduleauthor:: Marco Melis <marco.melis@unica.it>
"""
__all__ = ['AverageMeter', 'OrderedFlexibleClass', 'check_is_fitted']
class AverageMeter:
"""Computes and stores the average and current value.
Attributes
... | 4,965 | 1,404 |
#!/usr/bin/python
def find_primes(n):
"""
Finds all the primes below number n using the sieve of Eratosthenes
"""
candidates = [i + 2 for i in range(n-1)]
for p in candidates:
for i in candidates:
if i % p == 0 and p != i:
candidates.remove(i)
return candidat... | 621 | 210 |
# Copyright (c) 2010-2011, Found IT A/S and Piped Project Contributors.
# See LICENSE for details.
from piped_status_testing import statustest, util
from twisted.internet import reactor, defer
""" This module contains statustests used only for internal testing of piped_status_testing. """
class HelperStatusTest(stat... | 3,233 | 948 |
# MIT License
# Copyright (c) 2019 Veracode, 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 the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | 3,424 | 1,098 |
from . import HttpExtensions
from . import UsersExtensions
| 59 | 13 |
def from_openexplorer_Explorer(item, molecular_system=None, atom_indices='all', structure_indices='all'):
from molsysmt.native.io.topology.openmm_Topology import from_openmm_Topology
from molsysmt.api_forms.api_openexplorer_Explorer import to_openmm_Topology as openexplorer_Explorer_to_openmm_Topology
tmp... | 613 | 214 |
import feedparser
class Ansa():
def __init__(self, *args, **kwargs):
self.parsed_feed = []
def getNews(self, xmlrequest):
feed = feedparser.parse(xmlrequest)
for item in feed.entries:
self.parsed_feed.append(self.parseData(item))
return self.parsed_feed
... | 673 | 193 |
from .visit import *
from .location import *
from .browser import *
from .visitor import *
from .session import *
from .page import *
from .day import *
from .week import *
from .month import *
from .year import *
from .util import *
| 234 | 69 |
import os
from uroboros import Command, ExitStatus
class GetCommand(Command):
name = "get"
short_description = "Show value"
long_description = "Show value of given env var"
def build_option(self, parser):
parser.add_argument('name', type=str, help='Env var name')
parser.add_argument... | 862 | 243 |