text string | size int64 | token_count int64 |
|---|---|---|
import mongoengine
import datetime
class Task(mongoengine.Document):
title = mongoengine.StringField( max_length=100 )
body = mongoengine.StringField( required=True )
starts_on = mongoengine.DateTimeField( default=None )
ends_on = mongoengine.DateTimeField( default=None )
stage = mongoengine.Stri... | 853 | 258 |
import unittest
from ..packet import *
# Some packegs as captured on the network, each string is the payload
# of one UDP packet.
summary = [
b'SUMMARY: "MULT" "" 8220 "ID" "4.23.0" 129 "SJ0X" "JO99BM" "14" 200 1 3 1 0 7 7\x89\x00',
b'SUMMARY: "MULT" "" 8220 "HEADERS" 1 5 8 10 6 14 15\x9e\x00',
b'SUMMARY:... | 2,890 | 1,492 |
import apps.common.func.InitDjango
from all_models.models import *
from all_models.models.A0011_version_manage import TbVersionHttpInterface
from django.db import connection
from django.forms.models import model_to_dict
from apps.common.func.CommonFunc import *
from apps.common.func.ValidataFunc import *
from all_model... | 3,560 | 1,241 |
"""
Tests related to authenticating API requests
"""
import mock
from nose.tools import * # flake8: noqa
from framework.auth import cas
from tests.base import ApiTestCase
from tests.factories import ProjectFactory, UserFactory
from api.base.settings import API_BASE
class TestOAuthValidation(ApiTestCase):
"""... | 2,861 | 946 |
import numpy as np
__all__ = ['hz_to_normalized_rad',
'normalized_rad_to_hz']
def hz_to_normalized_rad(freqs, fs):
return freqs / fs * 2 * np.pi
def normalized_rad_to_hz(rad, fs):
return rad / np.pi * fs / 2 | 229 | 99 |
# import modules
from flask import Flask, jsonify
import requests
from pymongo import MongoClient
app = Flask(__name__)
mongo_uri = "mongodb://<mLab_username>:<mLab_password>@ds145299.mlab.com:45299/mydbinstance"
client = MongoClient(mongo_uri)
db = client.mydbinstance
yelp_collection = db.yelp
@app.route('/')
def i... | 1,215 | 429 |
"""
Example call:
export STORAGE_ROOT=<your desired storage root>
python -m padertorch.contrib.examples.wavenet.train
"""
import os
from pathlib import Path
from lazy_dataset.database import JsonDatabase
from padertorch.contrib.examples.audio_synthesis.wavenet.data import \
prepare_dataset
from padertorch.contrib... | 3,810 | 1,257 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Median filter of images + OpenCL
# https://github.com/silx-kit/silx
#
# 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... | 5,376 | 1,803 |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2015 by Tobias Houska
This file is part of Statistical Parameter Estimation Tool (SPOTPY).
:author: Tobias Houska
Implements a variant of DE-MC_Z. The sampler is a multi-chain sampler that
proposal states based on the differences between random past states.
The sampler doe... | 25,864 | 7,633 |
"""
Scatter AlignmentSet, ReferenceSet -> Chunk.JSON
This is effectively an
"""
import logging
import os
import sys
from pbcommand.cli import pbparser_runner
from pbcommand.utils import setup_log
from pbcoretools.tasks import scatter_alignments_reference
log = logging.getLogger(__name__)
TOOL_ID = "pbcoretools.t... | 900 | 281 |
"""Clean Code in Python - Chapter 6: Descriptors
> Methods of the descriptor interface: __set_name__
"""
from log import logger
class DescriptorWithName:
"""This descriptor requires the name to be explicitly set."""
def __init__(self, name):
self.name = name
def __get__(self, ins... | 2,126 | 682 |
import logging
import getpass
try:
from cmreslogging.handlers import CMRESHandler
except ImportError:
_es_logging_enabled = False
else:
_es_logging_enabled = True
class OptionalModuleMissing(Exception):
''' Error raised a required module is missing for a optional/extra provider
'''
def __ini... | 2,647 | 703 |
# Generated by Django 3.1.8 on 2021-04-26 07:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('end_user_advisories', '0001_initial'), ('end_user_advisories', '0002_enduseradvisoryquery_end_user'), ('end_user_advisories', '0003_remov... | 1,788 | 574 |
class Profile:
def __init__(self, username, password):
self.username = username
self.password = password
@property
def username(self):
return self.__username
@username.setter
def username(self, value):
if 5 > len(value) or len(value) > 15:
raise ValueErr... | 1,434 | 400 |
"""
list_node
~~~
:author: dilless(Huangbo)
:date: 2020/7/12
"""
class ListNode:
"""
Definition for singly-linked list
"""
def __init__(self, val: int) -> None:
self.val = val
self.next = None
| 251 | 101 |
#!/usr/bin/env python
"""
Southern California Earthquake Center Broadband Platform
Copyright 2010-2016 Southern California Earthquake Center
Utility classes for the SCEC Broadband Platform
$Id: bband_utils.py 1730 2016-09-06 20:26:43Z fsilva $
"""
from __future__ import division, print_function
# Import Python module... | 8,225 | 2,406 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from distutils.dir_util import copy_tree
from sys import exit
import os
import json
import datetime
import argparse
useMarkdown = False
try:
import markdown
useMarkdown = True
except ImportError as e:
useMarkdown = False
__version__ = "0.3.0"
class Site():
... | 5,415 | 1,508 |
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, HiddenField
from wtforms.validators import Required
class TasksForm(Form):
Task1 = StringField('Task 1:', validators=[])
Task2 = StringField('Task 2:', validators=[])
Task3 = StringField('Task 3:', validators=[])
Task4 = Stri... | 429 | 141 |
import logging
from abc import ABC, abstractmethod
from hardware import BME280, TSL2561, YL83
from resources.errors import AdapterException
from resources.utils import average
class AbstractAdapter(ABC):
def __init__(self):
self.data_buffer = dict()
@abstractmethod
def initialize(self, *args, **... | 4,421 | 1,428 |
import math
import pygame
import cairo
import numpy
import Image
import random
import copy
class Color(object):
def __init__(self, r = 1, g = 1, b = 1, a = 1):
self.r = r
self.g = g
self.b = b
self.a = a
def replace(self, r = None, g = None, b = None, a = None):
""" Ret... | 6,899 | 2,289 |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
#Veri setinin yüklenmesi
veri = pd.read_csv('c.csv')
#Verinin Sinif sayisinin ve etiklerinin belirlenmesi
label_encoder = LabelEncoder().fit(veri['HKIsonuc'])
labels = label_encoder.transform(veri['... | 1,917 | 781 |
import os
from ser import rename
pokes = './pokes'
lista = []
#os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
# print (f'{item}.png')
for file in os.listdir(pokes):
item = rename(file)
print(f"tranferindo {file} para {item}.jpg")
os.rename(f"{pokes}/{file}", f"./pokemons/{item}.jpg"... | 357 | 149 |
import pandas as pd
data = pd.read_csv("D:\iris.csv")
print("Number of rows in each column:")
print(data.count())
| 117 | 43 |
from unittest import TestCase
from nose.tools import raises
try:
from urlparse import parse_qs, parse_qsl
except ImportError:
from cgi import parse_qs, parse_qsl
import yql
class YahooTokenTest(TestCase):
def test_create_yahoo_token(self):
token = yql.YahooToken('test-key', 'test-secret')
... | 3,022 | 1,032 |
################################################################################
# Peach - Computational Intelligence for Python
# Jose Alexandre Nalon
#
# This file: nn/lrules.py
# Learning rules for neural networks
################################################################################
# Doc string, reStruc... | 17,782 | 4,587 |
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 ag... | 4,258 | 1,384 |
from __future__ import absolute_import
from elasticapm.contrib.pylons import ElasticAPM
def example_app(environ, start_response):
raise ValueError("hello world")
def test_init():
config = {
"elasticapm.server_url": "http://localhost/api/store",
"elasticapm.service_name": "p" * 32,
"... | 716 | 244 |
"""
Given two positive integers n and k.
A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order,
return the kth factor in this list or return -1 if n has less
than k factors.
Example:
Input: n = 12, k = 3
O... | 1,536 | 617 |
"""Contains utility methods for validating."""
import os
from typing import Any, Iterable, List, Optional
from typeguard import typechecked
@typechecked
def all_items(item_type: type, **kwargs: Iterable[Any]) -> None:
"""
Examples:
>>> all_items(str, a=['a', 'b', 'c'])
>>> all_items(int, a=[1... | 7,834 | 2,373 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# import(s)
# -
from OcsCameraEntity import *
from OcsSequencerEntity import *
import multiprocessing
import os
# +
# function: worker_code()
# -
def worker_code(entity='', entobj=None):
# debug output
print('name: {0:s}'.format(multiprocessing.current_proc... | 1,473 | 520 |
# Generated by Django 3.0.7 on 2020-06-12 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cv', '0015_closematchsetmembership_core'),
]
operations = [
migrations.RemoveField(
model_name='closematchsetmembership',
... | 631 | 196 |
import ctypes
import sys
import time
import yaml
import os
from ui_mainwindow import *
from ui_handler import UI_Handler
# Set HiDPI Scalling
os.environ['QT_AUTO_SCREEN_SCALE_FACTOR'] = '1'
# get the bundle location and file path
def get_file_path(filename):
bundle_dir = getattr(sys, '_MEIPASS', os.path.abspath(os.... | 2,068 | 695 |
from typing import List
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
res = []
combination = first + ' ' + second + ' '
text = text + ' '
word_len = len(combination)
start = 0
while True:
idx = text.find(combi... | 952 | 287 |
import pandas as pd
from QUANTAXIS.QAUtil import (
DATABASE
)
import pymongo
_table = DATABASE.stock_fundamentals
def init_index():
_table.create_index([('code',pymongo.ASCENDING),("date",pymongo.ASCENDING)], unique=True)
def query_fundamentals(codes,date):
query_condition = {
'date': date,
... | 615 | 214 |
# try:
import sys,logging,traceback
# sys.path.append(r"F:\Work\Maptor\venv\Model")
from PLSR_SSS_Model import PLSR_SSS_Model
# except Exception as e:
# logging.error("Exception occurred", exc_info=True)
# print('Can not import files:' + str(e))
# input("Press Enter to exit!")
# sys.exit(0)
class PLSR_SSS_Controller()... | 1,396 | 519 |
from .client_authentication import ClientAuthentication
| 56 | 10 |
import os
# check and create the path if not exists
def check_and_create_file_path(in_path, in_Path_desc_str=None):
if (in_Path_desc_str is None):
Path_desc_str = ""
else:
Path_desc_str = in_Path_desc_str
try:
os.stat(in_path)
print("{} Path [{}] exists.".format(Path_desc_str, in_path))
except:... | 417 | 161 |
import env
import re, sys, thread, time
def dbg(msg):
#print msg
pass
ENCODING = 'iso-8859-1'
def upage(s):
return unicode(s, ENCODING)
MAIN_PAGE = 'http://www.curitiba.pr.gov.br/Servicos/Transporte/HorarioOnibus/ctba.asp'
def url_horario(cod):
return 'http://www.curitiba.pr.gov.br/Servicos/Transporte/HorarioOn... | 2,899 | 1,376 |
schema = {
"$schema": "http://json-schema.org/draft-06/schema#",
"$comment": "Additional exchange customization to complement/rewrite exchange settings fetched directly from the exchange.",
"type": "object",
"properties": {
"marketRules": {
"$comment": "Definition of symbol rules that will overwrite rules fet... | 2,140 | 940 |
from enum import Enum, unique
@unique
class Difficulty(Enum):
EASY = "easy"
MEDIUM = "medium"
HARD = "hard"
difficulty_map = {i.value: i for i in Difficulty}
| 174 | 74 |
from .. import *
CWD = "./tests/ropemporium/"
BIN32 = "./callme32"
BIN64 = "./callme"
def test_callme32_local(exploit):
with cwd(CWD):
state = exploit(BIN32, lambda: process(BIN32))
state = turnkey.Classic()(state)
assert assertion.have_shell(state.target)
def test_callme_local(exploit)... | 487 | 187 |
#Class Task-10
#Hero Inventory
# Hero's Inventory
# Demonstrates tuple creation
# create an empty tuple
inventory = ()
# treat the tuple as a condition
if not inventory:
print("You are empty-handed.")
input("\nPress the enter key to continue.")
# create a tuple with some items
inventory = ("sword",
"armor",
"shi... | 559 | 184 |
'''tzinfo timezone information for Africa/Niamey.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Niamey(DstTzInfo):
'''Africa/Niamey timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Niamey'
_ut... | 553 | 271 |
# Deletes all notifications
from usermgmt.models import Notification
Notification.objects.all().delete()
| 108 | 30 |
from unittest import TestCase
from skypyblue.models import *
from skypyblue.core import Mvine, Marker, ConstraintSystem
class ChainTests(TestCase):
def setUp(self):
cs = ConstraintSystem()
self.first = None
self.last = None
prev = None
n = 50
# We need to go up to n inclusively, as this is d... | 806 | 286 |
from mock import Mock
from flows.simulacra.youtube_dl.factory import youtube_dl_flow_factory
from flows.simulacra.youtube_dl.post import download_videos
from tests.testcase import TestCase
class TestDownloadVideos(TestCase):
def setUp(self):
self.open = self.set_up_patch(
'flows.simulacra.you... | 1,926 | 635 |
import torch
from torch.optim.lr_scheduler import LambdaLR
import pytorch_lightning as pl
from pytorch_lightning.metrics import Accuracy
from loss import LabelSmoothingLoss
from models import resnet18, vgg16
from bisect import bisect
from torch import nn
from absl import flags
from pl_bolts.optimizers.lr_scheduler impo... | 3,594 | 1,206 |
from typing import List
import pytest
from openapi_parser.builders import ServerBuilder
from openapi_parser.specification import Server
data_provider = (
(
[],
[],
),
(
[
{
"url": "https://development.gigantic-server.com/v1",
},
... | 1,769 | 504 |
import sys, os, numpy as np
from PIL import Image, ImageDraw, ImageFont
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale
from crfrnn_model import get_crfrnn_model_def
GenImSize = 128
FitImSize = 500
def MakeCellImage(x, y, r, i):
im = Image.new(mode='F', size=(GenImSize, GenImSize))
... | 4,987 | 1,955 |
import abc
from datetime import datetime
from typing import Dict, Type
from ..adapters import Adapter
from ..posts import OrderPost
_executor_registry = {}
class ExecutorRegistry:
registry: Dict[str, Type["OrderExecutor"]] = dict()
@classmethod
def register(cls, mode: str, exec_class: Type["OrderExecut... | 1,397 | 417 |
#Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
#A) Quantos números foram digitados.
#B) A lista de valores, ordenada de forma decrescente.
#C) Se o valor 5 foi digitado e está ou não na lista.
valores = list()
cont = 0
while True:# assim eu consegui capturar quantos val... | 885 | 311 |
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu) and Wei Dong (weidong@andrew.cmu.edu)
#
# Please cite the following papers if you use any part of the code.
# - Christopher Choy, Wei Dong, Vladlen Koltun, Deep Global Registration, CVPR 2020
# - Christopher Choy, Jaesik Park, Vladlen Koltun, Fully Convolutional Ge... | 9,649 | 3,787 |
import os
import compas_vibro
from compas_vibro.structure import Structure
from compas_vibro.viewers import HarmonicViewer
from compas_vibro.viewers import ModalViewer
filepath = os.path.join(compas_vibro.TEMP, 'ansys_mesh_flat_20x20_harmonic_s.obj')
s = Structure.from_obj(filepath)
print(s.results.keys())
v = Har... | 372 | 156 |
n = int(raw_input())
print (n // 10) * 100 + min((n % 10) * 15, 100)
| 69 | 43 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import inspect
from typing import Dict, List, Optional, Tuple, Union
import torch
import copy
from torch import nn
import math
import numpy as np
import torch.nn.functional as F
from torch.autograd.function import Function
from detectron2.modeling.... | 42,165 | 12,981 |
# -*- coding: utf-8 -*-
"""lab11-2_deep.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1J_sFTBx4jqSfkefhBLFxUZjET-fHjI8g
## Deep CNN for MNIST
"""
!pip3 install -U -q PyDrive
# see https://stackoverflow.com/questions/48596521/how-to-read-data-... | 7,054 | 3,029 |
import unittest
from .. import *
class PlayerTestCase(unittest.TestCase):
def test_do_research(self):
#TODO
return
p = player.Player()
p.energy = 1000000
p.energy_minister.allocate_budget(p.energy)
p.energy_minister.research_budget = 100
p.research_field = 'e... | 5,694 | 2,082 |
class Solution:
"""
@问题: 给定一个数列 nums = [1,3,-1,-3,5,3,6,7] 和 一个常数 k 代表窗口大小, 输出每一个window最大值
@例子: Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3... | 1,423 | 588 |
from setuptools import setup
setup(
name='ManuscriptManager',
version='00.00.01',
packages=['sly',
'tests', 'manuscript', 'manuscript.tools', 'manuscript.actors', 'manuscript.language'],
url='',
license='MIT',
author='Antero Kangas',
author_email='antero.kangas@gmail.com',
descr... | 370 | 129 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test Sync Manifest """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ i... | 7,704 | 2,631 |
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score,f1_score
from scipy.special import expit
def softmax(r):
shift=r-np.max(r)
exps=np.exp(shift)
return exps/np.sum(exps,axis=0)
def sigmoid(r):
return expit(r)
def swish(r):
beta=1
return r * sigmoid(... | 5,992 | 1,993 |
from http.server import BaseHTTPRequestHandler, HTTPServer
class Server(BaseHTTPRequestHandler):
def do_GET(self):
"""Handles HTTP GET request"""
if self.path in ["/", "/index.html"]:
# Set a 200 response status code
self.send_response(200)
# Set content type ... | 1,298 | 386 |
# -*- coding: utf-8 -*-
"""
Celery pattern. Some interesting read here:
http://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern
Of course that discussion is not enough for
a flask templating framework like ours.
So we made some improvement along the code.
"""
from restapi.server import... | 1,252 | 379 |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from pathlib import Path
from torch.autograd import Variable
from tqdm import tqdm... | 4,019 | 1,377 |
with open('python\\2020\day3\data.txt') as f:
lines = f.readlines()
## start in the top left, 0,0
lay = 0
hang = 0
# found by counting data
width = 30
lay_d = 3
hang_d = 1
tree_hits = 0
stop = False
# loop for part 1
stop = True
while not stop:
if hang == len(lines):
stop = True
continue
... | 1,326 | 506 |
from unittest import TestCase
from context import Value
from rules import RuleParser, operators
from rules.conditional import ConditionalRule
from rules.rules import RuleContext
from rules.schedulerule import ScheduleRule
from mock import Mock, MagicMock
class TestRuleParser(TestCase):
def setUp(self):
se... | 9,253 | 2,967 |
import gym
from gym import monitoring
from gym import Wrapper
from gym.wrappers.time_limit import TimeLimit
from gym import error
import logging
logger = logging.getLogger(__name__)
class _Monitor(Wrapper):
def __init__(self, env, directory, video_callable=None, force=False, resume=False,
write_... | 2,044 | 623 |
# -*- coding: utf-8 -*-
"""
@author: Satoshi Hara
"""
import sys
sys.path.append('../')
import numpy as np
from AlternateLinearModel import AlternateLogisticLasso
# setting
seed = 0
num = 1000
dim = 2
dim_extra = 2
# data
np.random.seed(seed)
X = np.random.randn(num, dim + dim_extra)
for i in range(dim_extra):
... | 538 | 248 |
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
from src.svdd import SVDD
from src.visualize import Visualization as draw
from data import PrepareData as load
# load banana-shape data
trainData, testData, trainLabel, testLabel = load.banana()
# kernel list
kernelList = {"1": {"type": 'gauss', "width": 1/2... | 1,195 | 407 |
"""
For permutation cycles [[0, 1], [0, 2]]
"""
import matplotlib.pyplot as plt
level_1_lambdas = [-2. + 0.j, 4. + 0.j, 2. + 0.j]
level_2_lambdas = [-2. + 0.j, -0.73205081 + 0.j, 4. + 0.j, 2.73205081 + 0.j,
-1.64575131 + 0.j, 3.64575131 + 0.j, 2. + 0.j, 2. + 0.j, 2. + 0.j]
level_3_lambdas = [-2. ... | 5,183 | 2,786 |
from django.shortcuts import render
from django.db import models
from rest_framework import generics
from .serializers import *
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
class UserListAPIView(generics.ListAPIView):
serializer_class = UserSerializ... | 3,580 | 1,057 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
# pylint: disable=protected-access,too-many-public-methods,inherit-non-class
import unittest
from hamcrest import is_
from hamcrest import has_length
from hamcre... | 2,428 | 767 |
#Exercício Python 074:
# Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla.
# Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.
from random import randint
n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), ran... | 464 | 188 |
"""blogposts
Revision ID: 574aef3b4730
Revises: 916e12044eea
Create Date: 2019-02-18 02:50:45.508429
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '574aef3b4730'
down_revision = '916e12044eea'
branch_labels = None
depends_on = None
def upgrade():
# ### ... | 673 | 274 |
from setuptools import find_packages, setup
setup(
name="tf-bert",
version="1.0.0a0",
install_requires=["tensorflow>=2"],
packages=find_packages(exclude=["tests"]),
python_requires=">=3.6, <3.8",
#
description="bert implementation",
author="Jeong Ukjae",
author_email="jeongukjae@gma... | 685 | 225 |
"""cdbgui.py
Developers: Christina Hammer, Noelle Todd
Last Updated: August 19, 2014
This file contains a class version of the interface, in an effort to
make a program with no global variables.
"""
from datetime import datetime, timedelta, date
from tkinter import *
from tkinter import ttk
from tkinter import mess... | 60,992 | 19,165 |
import matplotlib.path as mplPath
from abc import ABCMeta
import abc
from protodata.utils import read_json
from protodata.columns import create_image_column
import numpy as np
import os
import tensorflow as tf
import logging
logger = logging.getLogger(__name__)
""" General functions for data manipulation """
cla... | 16,971 | 4,928 |
# Generated by Django 2.2.4 on 2020-01-14 06:28
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dashboard',
... | 1,875 | 555 |
import time
import re
from django.db.models.query import EmptyQuerySet
from django.http.response import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
fro... | 8,619 | 2,526 |
from functools import partial
from .. import args
from ..argparser import ParseStdin
class BitbucketOpts(args.ServiceOpts):
"""Bitbucket"""
_service = 'bitbucket'
class Search(args.Search, BitbucketOpts):
def add_args(self):
super().add_args()
# optional args
self.opts.add_arg... | 3,253 | 859 |
import parselmouth
from Voicelab.pipeline.Node import Node
from parselmouth.praat import call
from Voicelab.toolkits.Voicelab.VoicelabNode import VoicelabNode
class MeasureIntensityNode(VoicelabNode):
def __init__(self, *args, **kwargs):
"""
Args:
*args:
**kwargs:
... | 1,196 | 329 |
import enum
class Encrypting:
def __init__(self):
encrypting_type = "" #szyfr wybrany w gui
class Cipher(enum.Enum):
NO_CIPHER = 1
CAESAR = 2
FERNET = 3
POLYBIUS = 4
RAGBABY = 5
| 229 | 96 |
"""
Cosmic ray correction based on Astroscrappy
correct_cosmics(): remove cosmic rays from a FITS image
"""
from __future__ import division, print_function
__all__ = ['correct_cosmics']
def correct_cosmics(img, detect=False, sigclip=4.5, sigfrac=0.3, objlim=5.0,
gain=1.0, readnoise=10.0, satle... | 2,907 | 966 |
# -*- coding: utf-8 -*-
# Written by yq_yao
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn.init as init
from models.model_helper import FpnAdapter, WeaveAdapter, weights_init, WeaveAdapter2
# from model_helper import FpnAdapter, WeaveAdapter, weig... | 5,407 | 2,207 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import codecs
from pprint import pprint
from cStringIO import StringIO
def load(name):
f = codecs.open(name, "r", "utf-8")
json_object = json.load(f)
f.close()
return json_object
def load_municipals(file_name):
data = load(file_name)["f... | 3,630 | 1,324 |
from flask import Flask, render_template, redirect, url_for, request, flash
import csv, json
import NPRoneaccess
import DarkSkyaccess
import genlatlong
from station import Station
app = Flask(__name__)
stations = []
old_stations =[]
#The first part of this application is start-up focused
#Initializing arguments and ... | 14,159 | 3,460 |
def compress(s):
"""
Compress a string by replacing n contiguous characters c by cn
:param s: string to compress
:type s: str
:return: str
"""
n = len(s)
i = 0
j = 1
compressed_str = ""
while j < len(s):
if s[j] == s[i]:
j += 1
else:
c... | 978 | 356 |
import os
import re
import sys
import time
import urllib.request, urllib.error, urllib.parse
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from conflib.constants import *
def valid_version_and_release(version, release):
return (version != SIMP_INVALID_VERSION) and (release != SIMP... | 5,366 | 1,654 |
'''
Test environment creation with lib Environment()
'''
import unittest
import os
import argparse
from lib import Environment
class EnvironmentTests(unittest.TestCase):
'''
Test environment creation with Environment()
'''
def setUp(self):
with open('tests.apikey', 'w') as file_apikey:
... | 5,118 | 1,385 |
from django.utils.translation import get_language_from_request
from django_elasticsearch_dsl.registries import registry
from shop.models.product import ProductModel
class SearchViewMixin:
def get_document(self, language):
documents = registry.get_documents([ProductModel])
try:
return... | 2,231 | 613 |
# make sure to run this file in the same folder as sdegrad.py, electricdata.pkl
import pickle
import numpy as np
from sdegrad import sde, sde_mle, jump_ode, PiecewiseODE
import tensorflow as tf
import random
from tqdm import tqdm
#%% these are small models which run faster on cpu, disable gpu
try:
# Disable all GP... | 9,835 | 3,802 |
#!/usr/bin/env python
from pyscf.neo.mole import Mole
from pyscf.neo.hf import HF
from pyscf.neo.ks import KS
from pyscf.neo.cdft import CDFT
from pyscf.neo.grad import Gradients
from pyscf.neo.cphf import CPHF
from pyscf.neo.hessian import Hessian
from pyscf.neo.ase import Pyscf_NEO, Pyscf_DFT
from pyscf.neo.mp2 impo... | 349 | 151 |
import xmltodict
import json
from xml.etree import ElementTree
from display_xml import XML
def xml_element_to_json(element: ElementTree.Element):
return json.loads(json.dumps(
xmltodict.parse(
ElementTree.tostring(
element
)
)
))
def display_xml(elemen... | 370 | 107 |
def test_category(category):
assert str(category) == f"{category.title}"
def test_commit(commit):
assert str(commit) == f"Commit for '{commit.package.title}' on {commit.commit_date}"
def test_package(package):
assert str(package) == f"{package.title}"
assert package.is_deprecated is False
assert... | 1,089 | 341 |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.rst')) as f:
CHANGES = f.read()
requires = [
'SQLAlchemy',
'python-slugify',
'block-io'... | 1,828 | 603 |
import os
import numpy as np
from toolkit.tvnet_pytorch.train_options import arguments
from toolkit.tvnet_pytorch.model.network import model
import scipy.io as sio
import cv2
import PIL.Image as Image
from toolkit.tvnet_pytorch.utils import *
from toolkit.datasets import DatasetFactory
from torchvision import transfor... | 3,899 | 1,343 |
#!/usr/bin/env python3
import requests, hashlib, os, tempfile, io
from time import time, sleep
from tqdm import tqdm, trange
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
from datetime import datetime
from README_TEMPLATE import README_TEMPLATE
from subprocess im... | 14,930 | 5,571 |
__author__ = 'roeiherz'
"""
A majority element is an element that makes up more than half of the items in an array.
Given a positive integers array, find the majority element. If there is no majority element, return -1.
Do this in O(N) time and O(1) space.
"""
def partition(A, p, q):
pivot = A[q]
curr = in... | 1,600 | 603 |
"""
Author: Ramiz Raja
Created on: 24/01/2020
Problem: In an ocean, there are n islands some of which are connected via bridges. Travelling over a
bridge has some cost attaced with it. Find bridges in such a way that all islands are connected
with minimum cost of travelling.
You can assume that there is at least one p... | 3,621 | 1,234 |
import os,sys
#run:
# python send_all_jobs.py data_dir checkpoints
# where data dir contains the UD directory and checkpoints
# will save checkpoints with one directory per treebank,
# named after its iso
#ISO_TODO = ['sv_talbanken', 'en_ewt', 'lv_lvtb', 'cs_fictree',
#'cs_pdt', 'it_isdt', 'uk_iu', 'pl_pdb','ru_synt... | 1,395 | 621 |