text string | size int64 | token_count int64 |
|---|---|---|
import logging
import os
import time
from zipfile import ZipFile
from bisect import bisect, bisect_left
from html.parser import HTMLParser
from dataclasses import dataclass, field
from filelock import FileLock
from typing import List, Optional, Tuple, Dict, NewType, Any
import xml.etree.ElementTree as ET
import re
from... | 18,585 | 4,689 |
import discord
from discord.ext import commands
from random import shuffle
import time
class Blackjack:
def __init__(self, bot):
self.bot = bot;
self.state = 3
def setup(self):
self.deck = []
self.deck = self.newDeck()
self.pHand = []
self.dHand = []
sel... | 4,983 | 1,559 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# radio.py, version 3.4 (RGB LCD Pi Plate version)
# September 14.3, 2013
# Edited by Dylan Leite
# Written by Sheldon Hartling for Usual Panic
# BSD license, all text above must be included in any redistribution
#
#
# based on code from Kyle Prier (http://wwww.youtube.com/mei... | 4,409 | 1,678 |
import pygame
import random
from StarTradingCompany import MainScene
class MainApp:
def main_loop(self, width, height, fps):
random.seed()
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode(
(width, height), pygame.SCALED)
pygame.display.set_cap... | 1,703 | 473 |
#!/usr/bin/env python3
import numpy as np
import simtk.openmm as mm
def apply_opls_combo(system, switching_distance=None):
"""Apply the opls combination rules to a OpenMM system and return the new system."""
# Get the system information from the openmm system
forces = {system.getForce(index).__class__.... | 451,805 | 246,290 |
import sqlite3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import requests
from pandas import ExcelWriter
#from selenium.webdriver.common.by import By
#import time
import pandas as pd
import datetime
import numpy as np
import time
import re
from ... | 338 | 84 |
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from polarishub_flask.server.parser import printv
# printv(sys.path)
from flask import Flask, request, abort, send_file, render_template, redirect, url_for
from po... | 5,243 | 1,584 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# $Id$
#
# A very simple generator of rasters for testing WKT Raster.
# A test file is a matrix of numbered cells greyscaled randomly.
#
# Requirements: Python + Python Imaging Library (PIL)
# Also, path to FreeSans.ttf is a hardcoded Unix path, so fix it if you need.
#
... | 2,814 | 1,032 |
import os
import io
import json
import logging
import time
import json
import requests
from google.cloud import pubsub_v1
import cloudevents.exceptions as cloud_exceptions
from cloudevents.http import from_http
from flask import Flask, jsonify, redirect, render_template, request, Response
app = Flask(__name__)
PR... | 1,298 | 436 |
from django.shortcuts import redirect, render
from django.http import Http404, HttpResponse
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from videos.models import Video
from .forms import (
PlayListCreateForm,
)
from .models import Playlist
# Create your views here.
... | 3,934 | 1,314 |
import json
import logging
from abc import abstractmethod
from cloudsplaining.scan.policy_document import PolicyDocument
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.common.multi_signature import multi_signature
from checkov.terraform.checks.data.base_check import BaseDataCheck
fro... | 1,551 | 421 |
from numpy import array, matrix, diag, exp, inner, nan_to_num
from numpy.core.umath_tests import inner1d
from numpy import argmin, array
class GKS:
"""Gaussian kernel smoother to transform any clustering method into regression. setN is the list containing numpy arrays which are the weights of clustering centors.
... | 4,229 | 1,278 |
# -*- coding: utf-8 -*-
import re
import xml.etree.ElementTree as etree
from ..base.downloader import BaseDownloader
# Based on zdfm by Roland Beermann (http://github.com/enkore/zdfm/)
class ZDF(BaseDownloader):
__name__ = "ZDF Mediathek"
__type__ = "downloader"
__version__ = "0.89"
__status__ = "tes... | 1,887 | 651 |
import sys, os, numpy, unittest
import net
class DerivativesTestCase(unittest.TestCase):
conformists = None
def setUp(self):
self.conformists = [net.Step, net.Sigmoid, net.HardHyperbolicTangent, net.RectifiedLinearUnit, net.ParametricRectifiedLinearUnit, net.HardShrink, net.SoftShrink, net.SoftPlus, net.ShiftSca... | 2,335 | 945 |
import requests
import discord
class RelistenAPI:
base_url = "https://api.relisten.net"
api_prefix = "api/v2"
headers = {
"accept": "application/json"
}
def __init__(self, artist='grateful-dead'):
self.artist = artist
@property
def artists(self):
return requests.g... | 2,192 | 628 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GuiLayout.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_RobotController(object):
def setupUi(self, RobotController):
... | 3,663 | 1,233 |
#!/usr/bin/python
#
# Simple standalone HTTP server for testing MDAPI
#
# Mark Huang <mlhuang@cs.princeton.edu>
# Copyright (C) 2006 The Trustees of Princeton University
#
# Modifications by Jude Nelson
# $Id$
#
import os
import sys
import getopt
import traceback
import BaseHTTPServer
sys.path.append("/usr/share/SMDS... | 2,886 | 955 |
# -*- coding: utf-8 -*-
from numpy import array
def comp_height(self, Ndisc=200):
"""Compute the height of the Slot.
Caution, the bottom of the Slot is an Arc
Parameters
----------
self : Slot
A Slot object
Ndisc : int
Number of point to discretize the lines
Returns
... | 638 | 229 |
import pickle
import sympy as sym
import numpy as np
from functools import reduce
from itertools import groupby
def lie_bracket(element_1, element_2):
"""
Unfolds a Lie bracket. It is assumed that the second element is homogeneous (the bracket grows to the left).
Returns a string encoding the result of un... | 6,087 | 1,990 |
# Copyright (c) 2017 Thales Services SAS
# 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 r... | 1,185 | 390 |
import re
from .exceptions import InvalidRouteHandlerException
from . import handlers
class Route:
def __init__(self, path, handler):
if not path:
raise ValueError('Invalid path')
self.path = path
if not callable(handler):
raise InvalidRouteHandlerException('Handl... | 1,948 | 547 |
#!/usr/bin/env python
#
# 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 License, Version 2.0 (the
# "... | 6,503 | 1,928 |
"""
Remove metric records on state_dict.
"""
import argparse
from pathlib import Path
import torch
state_dict_keys_to_remove = ['test_acc.total', 'test_acc.correct',
'val_acc.total', 'val_acc.correct',
'train_acc.total', 'train_acc.correct', ]
def main():
... | 826 | 283 |
from car_pooling.IService import IService
class CarPooling(IService):
BAD_REQUEST = -1
NOT_ALLOCATED = 0
MAX_SEAT = 6
def __init__(self, _car_pooling=None):
"""
Class for car pooling service
:param _car_pooling: Car pooling list (format: [(1,1),(2,2),...])
"""
... | 5,527 | 1,723 |
###FeatureAlignment
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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 S... | 50,489 | 16,836 |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from typing import List, Optional
from databuilder.models.graph_node import GraphNode
from databuilder.models.graph_relationship import GraphRelationship
from databuilder.models.graph_serializable import GraphSerializable
from data... | 4,086 | 1,083 |
import numpy as np
import pandas as pd
dataset = pd.read_csv('datasets/Data.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 3].values
# from sklearn.preprocessing import Imputer
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy="mean")
imputer = imputer.fit(X[... | 1,035 | 390 |
import re
from xendbg.gdbserver.handler import handle
ack_re = re.compile(br'\+(?P<rest>.*)')
packet_re = re.compile(br'\$(?P<content>[^#]*)#(?P<checksum>[0-9a-f]{2})(?P<rest>.*)')
# breakin_re = re.compile(br'\x03(?P<rest>.*)')
def checksum(content):
return '{:02x}'.format(sum(content) % 256).encode('ascii')
d... | 1,822 | 547 |
import math
import pygame
from math import cos, sin, radians, exp
from src.const import *
from src.objects.LIDAR import LIDAR
from .CarCommands import CommandGas, CommandDir
# Todo : should be moved !
weight_on_road = 10
boost_checkpoint = 250
class Car:
def __init__(self, track):
# INIT VARIABLES
... | 11,708 | 3,869 |
# Copyright 2014 The Spitfire Authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import unittest
from spitfire.compiler import analyzer
from spitfire.compiler import ast
from spitfire.compiler import compiler
from spitfire.compiler imp... | 18,859 | 5,513 |
from main import *
import discord
from discord.ext import commands
from discord import File
from discord import Embed
from dotenv import load_dotenv
class addrole(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_any_role(admine_role)
async def addrole(... | 2,587 | 1,042 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains library item tree view implementation
"""
from __future__ import print_function, division, absolute_import
import logging
import traceback
from Qt.QtCore import Qt, Signal, QPoint, QRect, QSize, QMimeData
from Qt.QtWidgets import QListView, QAb... | 19,207 | 5,276 |
from tqdm import tqdm
import pymongo
import redis
import json
from bson import json_util
client = pymongo.MongoClient('localhost:27017')
db = client.tweet
r = redis.StrictRedis(host='localhost', port=6379, db=0)
events = [e for e in db.current_event.find({},{'_id':1})]
def send_message(eid):
message = {'event_... | 484 | 193 |
from .base import LasBase
class LasData(LasBase):
def __init__(self, *, header=None, vlrs=None, points=None):
super().__init__(header=header, vlrs=vlrs, points=points)
| 182 | 63 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Turku University (2019) Department of Future Technologies
# Course Virtualization / Website
# Class for Course Virtualization site downloadables
#
# File.py - Jani Tammi <jasata@utu.fi>
#
# 2019-12-07 Initial version.
# 2019-12-28 Add prepublish(), JSONFormSchem... | 26,043 | 7,052 |
# Generated by Django 2.0.5 on 2018-07-10 05:41
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20180625_1319'),
]
operations = [
migrations.RemoveField(
model_name='cuisine',
... | 687 | 222 |
config_map = {}
def execute(soup):
ret_map = {
"info": [],
"warn": [],
"error": [],
"config":config_map
}
if soup is None:
return ret_map
title = soup.title
if title is None:
ret_map["error"].append("Site has no title")
elif title.string is None... | 504 | 165 |
import numpy
from generate import *
def generate():
def manchester_encode(x):
out = numpy.array([], dtype=numpy.bool_)
for b in x:
if b:
out = numpy.append(out, [True, False])
else:
out = numpy.append(out, [False, True])
return out
... | 1,032 | 351 |
from edflow.iterators.tf_trainer import TFBaseTrainer
import tensorflow as tf
def loss(logits, labels):
"""Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor ... | 1,432 | 442 |
import logging
from gym.envs.registration import register
logger = logging.getLogger(__name__)
register(
id='MagicSquare3x3-v0',
entry_point='gym_magic.envs:MagicSquare3x3',
timestep_limit=100,
)
| 210 | 84 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .f2m import F2M
def pcen(x, eps=1E-6, s=0.025, alpha=0.98, delta=2, r=0.5, training=False, last_state=None, empty=True):
frames = x.split(1, -2)
m_frames = []
if empty:
last_state = None
for frame in fr... | 3,744 | 1,419 |
import time
from datetime import datetime
from gpiozero import OutputDevice
from pyplanter.constants import GPIOPins
from pyplanter.logger import logger
"""
resources:
- https://gpiozero.readthedocs.io/en/stable/api_output.html#outputdevice
- https://github.com/ankitr42/gardenpi/blob/master/pumpcontroller.py
- http... | 1,465 | 455 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# s10_vep_stat.py
# made by Daniel Minseok Kwon
# 2020-02-05 11:55:01
#########################
import sys
import os
SVRNAME = os.uname()[1]
if "MBI" in SVRNAME.upper():
sys_path = "/Users/pcaso/bin/python_lib"
elif SVRNAME == "T7":
sys_path = "/ms1/bin/python_lib"
... | 9,718 | 3,501 |
"""
..
/------------------------------------------------------------------------------\
| -- FACADE TECHNOLOGIES INC. CONFIDENTIAL -- |
|------------------------------------------------------------------------------|
| ... | 5,579 | 1,545 |
import json
import logging
from urllib import parse
import requests
from ghtrack.GhTrackException import UnknownApiQueryException
from ghtrack.Util import Util
class RequestInit:
"""This class initialize the requests object with default and required values"""
def __init__(self, token, apiUrl="https://api.gi... | 4,200 | 1,111 |
import click
from leaf_focus.download.command import download
from leaf_focus.ocr.command import ocr
from leaf_focus.pdf.command import pdf
from leaf_focus.pipeline.command import pipeline_visualise
from leaf_focus.report.command import report
from leaf_focus.support.log_config import configure_leaf_focus_logging
@c... | 697 | 213 |
#!/usr/bin/env python
# This script queries the Faculty Data Repository (FDR) and the Service Directory (SD) for faculty HR data to feed Symplectic Elements.
# For FDR records without email addresses it can query the LDAP Service Directory using the python util package
# from https://intranet.lib.duke.edu/download/pyt... | 14,866 | 4,556 |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import enum
import http
import logging
import uuid
# pylint: disable=wrong-import-order
import flask
from google.protobuf import symbol_database
# pylin... | 5,681 | 1,777 |
# Copyright (c) 2016-2020, LE GOFF Vincent
# 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 copyright notice, this
# list of conditions a... | 5,806 | 1,780 |
import os
import pytest
from iotedgedev.telemetryconfig import TelemetryConfig
pytestmark = pytest.mark.unit
def test_firsttime(request):
config = TelemetryConfig()
def clean():
config_path = config.get_config_path()
if os.path.exists(config_path):
os.remove(config_path)
re... | 740 | 250 |
import os
from os import path as osp
import shutil
from experiments.service.benchmark_base import Benchmark
from experiments.service.localizers_factory import LocalizersFactory
class VisualLocBenchmark(Benchmark):
def __init__(self, cfg):
super().__init__(cfg)
output_localization_dir = self.cfg.t... | 655 | 192 |
from flask import Flask
from flask import jsonify
from flask import request
# A very basic API created using Flask that has two possible routes for requests.
application = Flask(__name__)
# The service basepath has a short response just to ensure that healthchecks
# sent to the service root will receive a healthy re... | 1,132 | 383 |
#! python3
# Regex Example: Phone and Email Scraper
#PDF: http://cdm266101.cdmhost.com/cdm/ref/collection/p266101coll7/id/25785
#Directory of Arkansas higher education personnel, 2015
print("First, we'll start by scraping the PDF \"Directory of Arkansas higher education personnel, 2015\"")
import re, pypercl... | 2,774 | 918 |
# Copyright (C) tkornuta, 2019
#
# 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 writin... | 1,171 | 454 |
from flask_wtf import FlaskForm as Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length
class EditMovieForm(Form):
title = StringField('title', validators=[DataRequired()])
plot = TextAreaField('plot', validators=[Length(min=0, max=2047)])
| 314 | 94 |
class UnauthorizedException(Exception):
def __init__(self, code=401, response={}):
self.code = code
# We envelope error messages like this
self.message = response.get("message", "Unknown Error")
super(UnauthorizedException, self).__init__()
def __str__(self):
return "\n... | 1,135 | 335 |
#!/usr/bin/env python
# coding: utf-8
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Basic-Data-Types" data-toc-modified-id="Basic-Data-Types-1"><span class="toc-item-num">1 </span>Basic Data Types</a></span></li></ul></div>
# <!--BOOK_... | 10,408 | 3,425 |
# -*- coding: utf-8 -*-
import re
from dateutil import parser
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from artbot_scraper.items import EventItem
from pytz import timezone
class SarahCottierGallery(CrawlSpider):
name ... | 1,611 | 514 |
import csv
from collections import OrderedDict
csv_read = "/opt/repos/GIS_parser/Bedford_County_Parcels.csv"
csv_zipcodes = "/opt/repos/GIS_parser/Parcels_ZipCodes.csv"
objectkey = "OBJECTID"
postalkey = "PostalCode"
objectkey2 = '\xef\xbb\xbfOBJECTID'
zipDictionary = OrderedDict()
with open(csv_zipcodes, 'rb') as ... | 989 | 326 |
## Define the functions used in mapping the dataset of ACMAA
## To avoid having the same function name in different python script files, each function here adds a prefix with "ac_".
## By Chao on 05-08-2014@ISI
def ac_objectUri():
return "object/" + getValue("Accession Number")
def ac_objectIdentifierUri():
retu... | 7,843 | 2,861 |
"""
A set of utilitarian functions to facilitate cooperation with the file system.
"""
import os
def get_all_file_paths(directory):
""" Return a list of full file paths inside a given directory. """
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
... | 1,205 | 344 |
'''
4. Faça um Programa que peça as 4 notas bimestrais e mostre a média.
'''
notas = list()
for contador in range(4):
notas.append(float(input(f'Insira a nota do {contador + 1}º bimestre: ')))
print(f'A média das notas é {sum(notas)/len(notas)}')
| 253 | 107 |
#git clone https://github.com/ANTsX/ANTsPy
#cd ANTsPy
#python setup.py install
import os
import logging
class Config(object):
IMAGE_SIZE = 200
TRIALS = 1
BATCH_SIZE = 64
EPOCHS = 1
PATIENCE = 200
VALIDATION_SPLIT = 0.2
TEST_SPLIT = 0.1
OUTCOME_BIAS = "pos"
EXPERTS = "experts.csv... | 1,429 | 630 |
from behave import use_fixture
from behave.fixture import fixture
import behave_webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
def before_all(context):
use_fixture(browser_chrome, context, timeout=10)
def after_step(context, step):
context.browser.get_screenshot_as_... | 740 | 242 |
import dodge.components as components
from dodge.constants import ComponentType, EventParam, EventType, Factions
from dodge.fov import FOVMap
from dodge.entity import Entity
from dodge.event import Event
from dodge.paths import LinePath
import math
class Tile(object):
def __init__(self, blocked, block_sight=None)... | 10,129 | 2,911 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import CubicHermiteSpline as cbs
from matplotlib.gridspec import GridSpec
from numpy import trapz
import matplotlib as mpl
from scipy.ndimage.filters import uniform_filter1d
mpl.rcParams["axes.spines.top"] = True
mpl.rcParam... | 64,192 | 22,644 |
# Copyright (c) 2013-2014 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved.
from cgtsclient.common import utils
from cgtsclient import exc
from cgtsclient.v1 import ihost as ihost_utils
def _print_imemory_show(imemory):
fields ... | 9,138 | 2,983 |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
import collections
import functools
import warnings
from typing import (
TYPE_CHECKING,
An... | 6,672 | 1,990 |
import os
import grp
import itertools
import multiprocessing
import schedule
import time
from pwd import getpwuid
from datetime import datetime as dt
def getsize(filename):
return os.path.getsize(filename)
def getname(root, filename):
return os.path.join(root, filename)
def getctime(path):
return dt.f... | 2,350 | 762 |
from threading import Thread
from exe.proto import *
from queue import Queue
from time import sleep
import traceback
def sleeper(data,qoutput,wait=10):
sleep(wait)
qoutput.put(data)
def work(data):
while 1:
try:
host,msg=data['send'].get()
ip=data['x']['host'].get(host.spli... | 762 | 236 |
import os
import pickle
from nltk.util import pr
from src.seq_train import MachineBuilder as ms
from numpy.lib.ufunclike import _fix_and_maybe_deprecate_out_named_y
import streamlit as st
import pandas as pd
from src.twitterscraper import Twitter as ts
from src.preparedata import PrepareData as prep
import urllib
imp... | 4,305 | 1,299 |
import argparse
import pkg_resources
import sys
import IPython
from . import tasks
from . import util
from .attractiveness_finder import AttractivenessFinder
from .photo import PhotoUploader
from .session import Session
from .statistics import Statistics
from .user import User
from .util import save_file
__version_... | 1,552 | 474 |
# Copyright 2021 The ML Collections Authors.
#
# 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... | 3,063 | 1,119 |
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool_path",
)
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTIO... | 3,435 | 1,053 |
import os
import argparse
import datetime
from tqdm import tqdm
import numpy as np
import tensorflow as tf
from google.oauth2 import service_account
from protobuf.experience_replay_pb2 import Trajectory, Info
from breakout.dqn_model import DQN_Model, ExperienceBuffer
from util.gcp_io import gcp_load_pipeline, gcs_lo... | 5,541 | 1,975 |
# -*- codiEEG_dsddsdsng: utf-8 -*-
"""
Created on Mon Jun 29 20:08:11 2020
@author: mahjaf
"""
#%% Import libs
#####===================== Importiung libraries =========================#####
import mne
import numpy as np
from scipy.integrate import simps
from numpy import loadtxt
import h5py
import time
import os
#... | 16,572 | 6,351 |
#!/usr/bin/env python
# 1 stream 22.87s user 3.27s system 4% cpu 9:39.41 total
# 10 streams 25.15s user 4.63s system 47% cpu 1:02.48 total 7480 requests/second
from datetime import datetime
from elasticsearch import Elasticsearch
import threading
from threading import Thread
import subproce... | 3,301 | 1,149 |
from UserInterface.ProjectSQLiteHandler import ProjectSQLiteHandler
from Controller.UIToHandler import UIToHandler
from UserInterface.makeAttributeXML import integerToTimeIndex
def updateSetsSql(set, setupModel):
uihandler = UIToHandler()
xmlfile = setupModel.getSetAttributeXML(set)
soup = uihandler.getSet... | 4,064 | 1,151 |
#! /usr/bin/python
"""
Copyright (c) 2012 The Ohio State 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 require... | 147,841 | 52,226 |
def substring_copy(str, n):
flen = 2
if flen > len(str):
flen = len(str)
substr = str[:flen]
result = ""
for i in range(n):
result = result + substr
return result
print(substring_copy('abcdef', 2))
print(substring_copy('p', 3)); | 251 | 97 |
#!/usr/bin/env python3
# coqc wrapper
from __future__ import print_function
from datetime import datetime
from os import path
import re
import sqlite3
import subprocess
import sys
class NullDb:
def add_qed(self, fname, ident, time):
pass
def add_file(self, fname, time):
pass
def close... | 6,363 | 2,139 |
import RPi.GPIO as GPIO
from datetime import datetime, timedelta
import pickle
pin = 11
buttons = []
#Sets up GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.IN)
#Gets binary value
def getBinary():
#Internal vars
num1s = 0 #Number of consecutive 1s read
binary = 1 #The bianry value
command = [] #The list to s... | 2,737 | 1,107 |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
def try_int(arg,default):
try:
arg = int(arg)
except:
arg = default
return arg | 152 | 57 |
import glob
import sys
def main(argv):
if len(argv) != 2:
usage()
sys.exit(-1)
directory = argv[1]
for m_parameter in (3, 5, 7):
result = []
[result.append(parse_file(open(f, 'r'))) for f in glob.glob('{}/M{}*.txt'.format(directory, m_parameter))]
print(format(resu... | 2,243 | 716 |
from .journal import Main
Main().mainloop()
| 45 | 15 |
# pylint: disable=redefined-outer-name
import sys
import shlex
from collections import ChainMap
import sargeparse
def test_int_type_no_nargs():
definition = {
'arguments': [
{
'names': ['--arg'],
'type': int,
}
],
}
parser = sargep... | 3,659 | 1,185 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('application', '0010_auto_20150119_1555'),
]
operations = [
migrations.RenameField(
model_name='otherdetails',
... | 609 | 196 |
from ..dataset import DataSet
from ..networks import ShapeNet
from .preprocess import view_img
import numpy as np
import torch
from tqdm import trange
from tqdm.auto import tqdm
import math
import os
from random import randrange
import re
BATCH_SIZE = 1
N_COMPONENTS = 68
TRAIN_EPOCHS = 1000
DEBUG_SINGLE_IMG = None
PCA... | 9,962 | 3,398 |
from libs.credentials import RINGSETTING, RINGPOSITION
class revolutionTracker:
def __init__(self):
super().__init__()
self.max_state = RINGPOSITION
self.ringSetting = RINGSETTING
self.state = 1
def increase(self):
if self.state == len(self.ringSetting):
return 0
if self.ringSetting[self.... | 562 | 245 |
#!/usr/bin/env python
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 ... | 1,400 | 436 |
from django.shortcuts import render
from django.views.generic import CreateView, ListView, UpdateView, DeleteView
from .models import Resoluciones
from .formResoluciones import FormResoluciones
class ViewCreateResolucion(CreateView):
model = Resoluciones
template_name = 'resoluciones/crearResolucion.html'
... | 1,138 | 334 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Quantify the effect of variable stomatal conductance
Created on Mon Jun 29 13:29:01 2020
@author: EHU
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# import sys
# sys.path.insert(0, 'Users/lizz/Documents/GitHub/glacial-SPEI')
import gSPEI... | 4,695 | 1,999 |
from django.urls import path
from dashboard import views
urlpatterns = [
path('login', views.bloglogin, name="login"),
path('logout', views.bloglogout, name="logout"),
path('', views.dashboard, name="dashboard"),
path('posts', views.showAllpost, name='showallpost'),
path('category', views.category,... | 990 | 309 |
import flask
from voluptuous import All, Any, Length, Range, Schema
from core import APIException
from core.utils import require_permission, validate_data
from wiki.models import (
WikiArticle,
WikiLanguage,
WikiRevision,
WikiTranslation,
)
from wiki.permissions import WikiPermissions
from . import bp... | 2,779 | 977 |
import json
import os
import sys
import unicodedata
import quickfix
from unidef.languages.common.type_model import *
from unidef.models.input_model import ExampleInput, InputDefinition
from unidef.parsers import Parser
from unidef.utils.loader import load_module
class FixParserImpl(Parser):
BASE_DIR = "quickfix"... | 1,428 | 431 |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch.nn as nn
class BaseModel(nn.Module):
def __init__(self, num_atoms=None, bond_feat_dim=None, num_targets=None):
sup... | 630 | 209 |
#
# 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, software
# distributed under... | 1,261 | 420 |
# -*- coding: utf-8 -*-
# Copyright FMR LLC <opensource@fidelity.com>
# SPDX-License-Identifier: Apache-2.0
import unittest
import numpy as np
import pandas as pd
from jurity.recommenders import RankingRecoMetrics
from jurity.recommenders.ndcg import idcg
from jurity.utils import Constants
class TestRankingRecomme... | 6,774 | 2,373 |
from django.contrib import admin
from sh_app.models import *
admin.site.register(SH_User)
admin.site.register(League)
admin.site.register(Huddle)
admin.site.register(Suggestion)
| 180 | 63 |
from .invoxia_serializer import InvoxiaLocationTrackerUpdateSerializer
from django.conf import settings
from allauth.socialaccount.models import SocialApp
from django.contrib.auth import get_user_model
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from django.contrib.sites.shortcuts... | 2,145 | 663 |