text string | size int64 | token_count int64 |
|---|---|---|
from django.urls import path
from applications.reviews import views
urlpatterns = [
path('', views.AllPostView.as_view(), name='reviews'),
path('add_post', views.AddPostView.as_view(), name='add_post'),
path('post/<int:pk>', views.ShowPostView.as_view(), name='post'),
path('update_post/<int:pk>', view... | 371 | 126 |
import pytest
from pydent.planner import Planner
from pydent.planner import PlannerException
from pydent.planner.utils import get_subgraphs
def test_canvas_create(session):
canvas = Planner(session)
canvas.create()
assert canvas.plan.id
def test_raises_exception_wiring_with_no_afts(session):
canvas... | 13,207 | 4,495 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_plugins_image', '0014_image_external_ref'),
]
operations = [
migrations.RenameField(
model_name='image',
... | 1,021 | 295 |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2015 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... | 3,531 | 994 |
from datetime import datetime
from .extractor import DateExtractor, ExtractedData, ExtractorException
class CapitalOne360ExtractorException(ExtractorException):
def __init__(self, *args, **kwargs):
ExtractorException.__init__(self, *args, **kwargs)
class CapitalOne360DateExtractor(DateExtractor):
... | 1,670 | 502 |
from setuptools import find_packages, setup
version = {}
with open("src/ya2ro/ya2ro.py") as fp:
exec(fp.read(), version)
setup(
name='ya2ro',
author='Antonia Pavel',
author_email='floriana.antonia.pavel@gmail.com',
description='Tool to which you pass basic information of a project or a research ar... | 1,335 | 431 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/resources/ad_group_simulation.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf... | 13,816 | 5,330 |
l = [-2, -1, 0, 1, 2]
print(filter(lambda x: x % 2 == 0, l))
# <filter object at 0x10bb38580>
print(type(filter(lambda x: x % 2 == 0, l)))
# <class 'filter'>
for i in filter(lambda x: x % 2 == 0, l):
print(i)
# -2
# 0
# 2
print(list(filter(lambda x: x % 2 == 0, l)))
# [-2, 0, 2]
print(list(filter(lambda x: x % ... | 1,958 | 1,022 |
import pandas as pd
import json
# plots
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
# Load and read json data
df = pd.read_json('full_info.json', lines=True)
user_name, commits, followers, repo, stars, forks, organizations, issues, contributions = \
[], [], [], [], [], [], [], [... | 3,487 | 1,258 |
import time
import Adafruit_BBIO.GPIO as GPIO
Debug = True
class DHT():
global Debug
def __init__(self, pin, type = "DHT22", count = 6):
self._pin = pin
self._type = type
self._count = count
self.firstreading = True
self.MAXTIMINGS = 85
self._lastreadtime = int(... | 3,400 | 1,134 |
from .victoria import Victoria
| 31 | 9 |
from unittest import TestCase
from django.apps.registry import apps
class ActstreamConfigTestCase(TestCase):
def test_data_field_is_added_to_action_class_only_once_even_if_app_is_loaded_again(self):
actstream_config = apps.get_app_config('actstream')
actstream_config.ready()
actstream_co... | 545 | 162 |
import numpy as np
import scipy
import scipy.special
import scipy.interpolate
import pickle
import sklearn
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import MySQLdb
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
import sqla... | 26,445 | 8,902 |
[2021-06-17T19:47:05.267189+03:00] DiscordPHP.INFO: gateway retrieved and set {"gateway":"wss://gateway.discord.gg/?v=6&encoding=json","session":{"total":1000,"remaining":983,"reset_after":62092171,"max_concurrency":1}} []
[2021-06-17T19:47:05.270016+03:00] DiscordPHP.INFO: starting connection to websocket {"gateway":"... | 20,247 | 10,371 |
import random
from typing import Dict, Callable, List, Any, Optional
import pandas as pd
class Table:
def __init__(self,
name: str,
outfile: str,
index_cache_size: int,
random_cache_size: int,
debug: bool):
"""
D... | 7,592 | 2,120 |
import numpy
import powerbox
import matplotlib
from matplotlib import pyplot
import matplotlib.colors as colors
from plottools import colorbar
from generaltools import symlog_bounds
from radiotelescope import beam_width
"""
This file is going to contain all relevant power spectrum functions, i.e data gridding, (freq... | 13,428 | 4,627 |
class PermissionConst:
'''
目前有几种权限:
add / edit / check / copy / run / delete / distinct
'''
urlAllPermission = "urlAllPermission"
urlDefaultPermission = "urlDefaultPermission"
user_permission = "user_permission"
team_url_permission = "team_url_permission"
| 298 | 95 |
from typing import List, Dict
import numpy as np
from absl import logging
from banditpylib.bandits import Bandit
from banditpylib.learners import Learner
from .utils import Protocol
class SinglePlayerProtocol(Protocol):
"""Single player protocol
This protocol is used to simulate the ordinary single-player gam... | 3,089 | 863 |
#!/usr/bin/env python
################################################################################
# MIT License
#
# Copyright (c) 2019 UCLA NanoCAD Laboratory
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "So... | 2,873 | 945 |
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
required = ['requests>=1.0.0',
'requests-oauth2>=0.2.0']
setup(
name='basecampx',
version='0.1.8',
... | 978 | 319 |
import sys
rootPath = '/Users/siwei/Desktop/noisyFER'
sys.path.append(rootPath)
import os
from tqdm import tqdm
import cv2
import csv
import numpy as np
import argparse
from crop_align.align import MyFaceAligner
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=str, default='datasets/affectnet')... | 2,602 | 932 |
#!/usr/bin/env python
import argparse
from Toggl.togglApi import getTogglReport
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Obtain report from Toggl.')
parser.add_argument("--toggl-token", "-tt", help="Set Toggl token.")
parser.add_argument("--toggl-workspace", "-w", help="S... | 640 | 219 |
from ._codec_data import _CodecData
#===============================================
class CodecAGroup(_CodecData):
def __init__(self, master, parent, schema_instr, default_name):
self.mGroupName = "?"
_CodecData.__init__(self, master, parent, schema_instr, default_name)
self.mGroup = self._... | 3,746 | 1,156 |
# coding=utf-8
import random
from mongoengine import *
from base.settings import CHATPAMONGO
import datetime
connect(CHATPAMONGO.db, host=CHATPAMONGO.host, port=CHATPAMONGO.port, username=CHATPAMONGO.username,
password=CHATPAMONGO.password)
class BottleMessageText(Document):
USER_TYPE = [
(0, "主... | 3,528 | 1,307 |
# Stdlib
import logging
# Django imports
from django.conf import settings
# Pip imports
import twitter
logger = logging.getLogger(__name__)
class TwitterClient:
api = None
def __init__(self):
self.api = twitter.Api(consumer_key=settings.TWITTER_CONSUMER_KEY,
... | 1,440 | 409 |
# Copyright 2016 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, ... | 5,834 | 1,988 |
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
class RegisterTestCase(APITestCase):
def test_register(self):
data = {
'username': 'test... | 1,399 | 421 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from reports.models import Report
from reports.serializers import ReportSerializer, UserSerializer
class R... | 663 | 187 |
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making QTA available.
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may not use this
# file except in compliance with the License. You may... | 67,578 | 21,070 |
# This program is free software: you can redistribute it and/or modify it under the
# terms of the Apache License (v2.0) as published by the Apache Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or... | 3,646 | 1,194 |
import io
import typing
import uuid
import ratelimit
import telegram
import telegram.ext
from cotd.plugins.helpers import make_image
from PIL import Image
ONE_SECOND = 1
def motivation_inline(
update: telegram.Update, context: telegram.ext.CallbackContext
) -> telegram.InlineQueryResultCachedPhoto:
db = con... | 849 | 283 |
import os
from ...envs.fs import Env
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def make_fs_env():
return Env(CURRENT_PATH)
def read(name):
with open(os.path.join(CURRENT_PATH, name), 'rb') as f:
return f.read().decode('utf-8')
| 265 | 105 |
from __future__ import annotations
from blox_old.core.engine.device import BlockDevice
from blox_old.btorch.module import TorchModule, TorchModuleError
import torch
from blox_old.utils import raise_if
from blox_old.core.block.base import Block
import typing as T
class TorchCudaError(TorchModuleError):
pass
def ... | 1,844 | 601 |
import ij
import os
import math
global foldername
foldername=None
tilesize=1024
##############################
''' Start of actual script '''
##############################
#fd = OpenDialog("Save Tiles In",None)
prefixval = 'Chan3_'
fd= DirectoryChooser("Save Tiles In")
foldername= fd.getDirectory()
if foldername:
... | 2,987 | 1,292 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Main
"""
from .compat import *
import os
import sys
import logging
import codecs
import time
from .RayvisionUtil import get_os, hump2underline, cg_id_name_dict, decorator_use_in_class, format_time
from .RayvisionAPI import RayvisionAPI
from .RayvisionJob import Rayvi... | 21,090 | 6,575 |
# 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
# "License"); you may not u... | 2,943 | 873 |
"""
Parrots
~~~~~~~
"""
from party_parrot._utils import get_parrots
slack_parrots = """
:aussie_parrot: :blonde_sassy_parrot: :bored_parrot: :chill_parrot: :christmas_parrot: :coffee_parrot:
:confused_parrot: :conga_parrot: :dark_beer_parrot: :deal_with_it_parrot: :angel_parrot: :fieri_parrot:
:goth_parrot: ... | 576 | 268 |
# fileio_backends.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019 and later, Jens Koch and Peter Groszkowski
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
###############################... | 13,764 | 4,194 |
import pytest
from rest_framework.status import (
HTTP_200_OK,
HTTP_204_NO_CONTENT,
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
)
from django.shortcuts import reverse
from baserow.core.handler import CoreHandler
from baserow.core.models import GroupUser
from baserow.core.trash.handler import TrashHandl... | 7,855 | 2,791 |
# Ce fichier contient une fonction permettant de vérifier si le mot de passe est assez complexe et s'il peut être brute force grâce à un dictonnaire de mots communs
# Permet la recherche
import re
# Permet de faire une pause dans le programme
import time
# Importe nos fonctions utiles
import sys
sys.path.insert(0, '... | 4,636 | 1,300 |
"""
"""
import logging
import os
import sys
# insert *this* galaxy before all others on sys.path
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)))
from galaxy.tool_util.cwl import handle_outputs
# ensure supported version
assert sys.version_info[:2] >= (2, 6) and sys... | 524 | 196 |
import os
import re
import asyncio
from pyrogram.types import Message
from util.message import send_media
class Trigger:
def __init__(self, regex:str,
response:str = "",
from_self:bool = False,
from_others:bool = True,
mention:bool = True,
media_path:str = "",
auto_vanish:int = -1,
):
self.re... | 2,107 | 873 |
import cv2
from typing import Tuple, Generator
from research.form_vision.image import Image, NormalizedCoords
import numpy as np
class TemplateMatcher:
width = 800
def __init__(
self, template_image: Image, reference_region: Tuple[NormalizedCoords, NormalizedCoords]
):
self._template = te... | 3,185 | 1,025 |
import os
import emoji
import telebot
from loguru import logger
from src.utils.constant import keyboards
from src.utils.io import write_json
class But:
"""
telegram bot to randomly connect two strangers
"""
def __init__(self):
self.bot = telebot.TeleBot(os.environ['BOT_TOKEN'])
self.... | 763 | 255 |
from MCQGame2 import Question
MCQ=[
"What color of apples? \na)red\nb)blue\nc)green\nd)yellow",
"Half adder has how many inputs?\na)1\nb)2\nc)3\nd)4",
"which operator can be overloaded?\na).\nb).*\nc)::\nd)+"
]
questions = [
Question(MCQ[0],"a"), #Objects of class Question
Question... | 713 | 260 |
from __future__ import annotations
__all__ = ["run", "main"]
import os
import sys
import io
import argparse
from typing import Optional
from gada import component, runners, datadir
def split_unknown_args(argv: list[str]) -> tuple[list[str], list[str]]:
"""Separate known command-line arguments from unknown one.
... | 5,286 | 1,553 |
#!/usr/bin/env python
"""Module for gyp1d functions"""
import numpy as np
import platform
import subprocess
import os
import data_expt as de
# Detect operating system
op_sys = platform.system()
def gen_input( k1, k2, k3, k4, rho_0, c_p1, c_p2, c_p3, eps, Y1_0,
A1, A2, E1, E2, dh1, dh2 ):
"""Genera... | 2,912 | 1,215 |
# © 2021 Nokia
#
# Licensed under the Apache license, version 2.0
# SPDX-License-Identifier: Apache-2.0
"""Class for handling collector threads."""
import logging
import time
from datetime import datetime
from threading import Event, Thread
from datacollector.collector.connection_config_parser import ConnectionConfig... | 6,356 | 1,649 |
import numpy as np
import torch
class ReplayBuffer(object):
def __init__(
self, state_dim, action_dim, hidden_size,
max_size=int(5e3), recurrent=False
):
self.max_size = int(max_size)
self.ptr = 0
self.size = 0
self.recurrent = recurrent
s... | 5,959 | 1,999 |
##############################################################################
#
# Copyright (c) 2006-2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THI... | 1,226 | 368 |
from GraphDraw import *
from Graph import *
from Implicit import *
from impExamples import *
import os
import errno
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
# For trying stuff
# Currently just displays the alternating domain on 9 outcomes
n = 9
impG = impAlternatingDomain(n)
G = impG.explicit()
d = G.d
G.comp... | 1,043 | 387 |
import random
import numpy as np
from PIL import Image
from DeepLineWars.Game import Game
import uuid
# https://github.com/cair/DeepRTS
# https://github.com/reinforceio/tensorforce
class GameInstance:
@staticmethod
def start(data_queue):
g = GameInstance(data_queue)
g.loop()
return T... | 3,647 | 1,156 |
import json
import pytest
from django.urls import reverse
from scraper_api.models import ScrapedPage
class TestPageListView:
@pytest.mark.django_db
def test_get(self, client, fill_db, url, html):
url = reverse("pages/")
response = client.get(url)
pages = json.loads(response.body)
... | 790 | 261 |
from typing import Callable, Dict, List, Optional
import os
import sys
from budgeted_bo.budgeted_bo_trial import budgeted_bo_trial
def experiment_manager(
problem: str,
algo: str,
algo_params: Dict,
restart: bool,
first_trial: int,
last_trial: int,
get_objective_cost_function: Callable,... | 1,566 | 490 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 17:34:43 2018
@author: arndt
"""
# http://scikit-learn.org/stable/developers/contributing.html#rolling-your-own-estimator
# https://github.com/vishnumani2009/sklearn-fasttext
from os import chdir
chdir("/home/arndt/git-reps/hatespeech/")
from ... | 594 | 235 |
# -*- coding: utf-8 -*-
__author__ = 'ffuentes'
from apps.noclook.tests.schema.base import Neo4jGraphQLGenericTest
from apps.noclook.models import NodeHandleContext
from django.contrib.auth.models import User
from niweb.schema import schema
from pprint import pformat
from . import BasicAdminTest
import apps.noclook.... | 15,366 | 3,835 |
def format_message(message, to_replace=["_", "*", "[", "`"]):
for symbol in to_replace:
message.replace(symbol, '\\' + symbol)
message.rp
return message
| 179 | 58 |
# -*- coding: utf-8 -*-
"""
Created on 2017-5-12
@author: cheng.li
"""
import unittest
import numpy as np
import pandas as pd
from alphamind.analysis.perfanalysis import perf_attribution_by_pos
class TestPerformanceAnalysis(unittest.TestCase):
@classmethod
def test_perf_attribution_by_pos(cls):
n... | 1,542 | 507 |
"""
Tests for :mod:`greenday_api.misc.distinct_channels_api <greenday_api.misc.distinct_channels_api>`
"""
from protorpc import message_types
from .base import ApiTestCase
from ..misc.distinct_channels_api import DistinctChannelsAPI
class DistinctChannelsAPITests(ApiTestCase):
"""
Test case for
... | 1,457 | 487 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# @Author: ZhuangYuZhou
# @E-mail: 605540375@qq.com
# @Desc:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import numpy as np
def random_intensity_shift(img_numpy, limit=0.1):
shift... | 1,043 | 404 |
AuthModelInvalid = Exception(
"The auth model you passed to the app config"
"should be a subclass of djask.auth.abstract.AbstractUser."
)
ModelTypeError = TypeError(
"The arg passed to register_model() must be a subclass of"
"Model instead of PureModel or something else."
)
| 291 | 81 |
"""
The MIT License (MIT)
Copyright (c) 2012, Florian Finkernagel <finkernagel@imt.uni-marburg.de>
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 limitatio... | 3,142 | 971 |
import ldap3
import re
from jupyterhub.auth import Authenticator
from tornado import gen
from traitlets import Unicode, Int, Bool, List, Union
class LDAPAuthenticator(Authenticator):
server_address = Unicode(
config=True,
help="""
Address of the LDAP server to contact.
Could be a... | 9,130 | 2,379 |
import json
from ..models import UserMailer
from .literals import (
TEST_EMAIL_ADDRESS, TEST_EMAIL_FROM_ADDRESS,
TEST_USER_MAILER_BACKEND_PATH, TEST_USER_MAILER_LABEL
)
class DocumentMailerViewTestMixin:
def _request_test_document_send_link_single_view(self):
return self.post(
viewna... | 6,567 | 1,925 |
import json
import io
from PIL import Image
import cv2
import numpy as np
def load(data):
image = Image.open(io.BytesIO(data))
opencvImage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
return opencvImage
| 223 | 81 |
#!/usr/bin/env python3
"""
The main file for a basic code editor written
entirely with the python standard library
main.py
PyText3 Text Editor
Created by Kaleb Rosborough on 10/23/2018
Copyright © Shock9616 2018 All rights reserved
"""
#region Imports
from tkinter import *
import tkinter as tk
from ... | 23,329 | 7,571 |
class Solution(object):
def sortColors(self, nums):
def triPartition(nums, target):
i,j,n = 0, 0,len(nums) -1
while j <= n:
if nums[j] < target:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
... | 569 | 207 |
# general functions for transforming h5 files
from ibex.utilities.constants import *
from numba import jit
import numpy as np
import math
# downsample the data by (z, y, x) ratio
@jit(nopython=True)
def DownsampleData(data, ratio=(1, 2, 2)):
# get the size of the current dataset
(zres, yres, xres) = data.shap... | 2,545 | 881 |
# inisiasi set awal kartu
class bank_card:
# finish
def __init__(self, pin, balance):
self.set_pin = pin
self.set_balance = balance
def check_set_pin(self):
return self.set_pin
def check_set_bal(self):
return self.set_balance
| 278 | 96 |
# -*- coding: utf-8 -*-
"""Test exotic program topologies.
For pictures, see ``macro_extras/callcc_topology.pdf`` in the source distribution.
"""
from inspect import stack
from ...syntax import macros, continuations, call_cc
def me():
"""Return the caller's function name."""
callstack = stack()
framerec... | 5,629 | 1,817 |
import logging
import os
import torch
from farm.modeling.prediction_head import FeedForwardBlock, PredictionHead
from torch.nn import MSELoss
from torch.nn.functional import pad
from lingcomp.farm.utils import roll
logger = logging.getLogger(__name__)
# TokenRegressionHead
class TokenRegressionHead(PredictionHead... | 7,933 | 2,400 |
import matplotlib.pyplot as pylab
principal = 10000
interestRate = 0.05
years = 20
values = []
for i in range(years + 1):
values.append(principal)
principal += principal * interestRate
pylab.plot(range(years + 1), values, linewidth=3)
pylab.title('5% Growth, Compaunded Annually')
pylab.xlabel('Years or Compo... | 381 | 147 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-13 08:55
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
... | 1,455 | 440 |
import dataclasses
import datetime
import typing
@dataclasses.dataclass
class Context:
build: str
name: str
version: str
@dataclasses.dataclass
class Frame:
abs_path: str
context_line: str
filename: str
function: str
lineno: int
module: str
pre_context: typing.List[str]
p... | 780 | 247 |
import os
from getpass import getpass
from .request_handler import request, set_dry
from .yaml_validator import yaml_user, yaml_update, yaml_reset
from .tokens import new_token
from datetime import datetime, timedelta
import json
def list_methods():
return ["user_info", "register", "edit_profile", "delete_profil... | 3,986 | 1,204 |
import requests
import json
from urllib.parse import urlparse
from httpsig import HeaderSigner
from datetime import datetime
def sign_headers(account, method, path):
sign = HeaderSigner(account.ap_id(), account.private_key, algorithm='rsa-sha256', headers=['(request-target)', 'date']).sign({'Date': datetime.now().... | 972 | 299 |
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from .forms import (
LoginForm,
UserRegistrationForm,
UserEditForm,
ProfileEditForm
... | 4,230 | 1,008 |
import os
from datetime import datetime
from flask import Flask
IS_PROD_ENV = True # CHANGE BETWEEN STAGING AND PRODUCTION ENVS
SUBDOMAIN_NAME = 'ponthe' if IS_PROD_ENV else 'ponthe-testing'
DOMAIN_NAME = f'https://{SUBDOMAIN_NAME}.enpc.org/'
def get_latest_promotion():
now = datetime.now()
prom_increment =... | 2,478 | 938 |
"""Collection of mapreduce jobs."""
import logging
from mapreduce import operation as op
from codereview.models import Account, Issue
def delete_unused_accounts(account):
"""Delete accounts for uses that don't participate in any reviews."""
email = account.user.email()
if Issue.query(Issue.owner_email == email... | 932 | 280 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from core.corr import AlternateCorrBlock, CorrBlock
from core.extractor import BasicEncoder, SmallEncoder
from core.mobilenetv3 import MobileNetV3
from core.pwc_decoder import Decoder
from core.pwc_refiner import Refiner
from core.up... | 3,426 | 1,205 |
'''
Created by:
@author: Andrea F Daniele - TTIC - Toyota Technological Institute at Chicago
Feb 6, 2019 - Mountain View, CA
'''
import sys
import numpy as np
from os.path import isfile
class ProgressBar(object):
def __init__(self, maxVal=100, precision=5, doneMessage=True ):
self.maxVal = float( max(1.0, ma... | 1,631 | 578 |
from attendees.persons.models import Folk, FolkAttendee, Relation, Utility, Attendee
from attendees.whereabouts.serializers import PlaceSerializer
from rest_framework import serializers
class FolkSerializer(serializers.ModelSerializer):
places = PlaceSerializer(many=True, read_only=True)
class Meta:
... | 1,673 | 472 |
# flake8: noqa
from .classification.predict import make_prediction
from .classification.predict_api import predict | 114 | 31 |
import string
import random
from nltk.tokenize import TweetTokenizer
import re
import time
import sys
import numpy as np
# source: https://gist.github.com/nealrs/96342d8231b75cf4bb82
cList = {
"ain't": "am not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",... | 6,826 | 2,797 |
class Solution:
def reverse(self, x):
sign = -1 if x<0 else 1
x = abs(x) # floor division ALWAYS rounds down (-1//10 = -1)
n = 0 # thus save sign and take absolute value
while x != 0:
n *= 10 # left shift digits one place
n += x%10 # push least significant digit
x //= 10 # pop processed digit
... | 896 | 374 |
from tkinter import Tk, Label
root = Tk()
root.title('Hello World')
root.geometry('500x300')
lb1 = Label(root, text = 'Hello, this is a tag -> 1')
lb2 = Label(root, text = 'Hello, this is a tag -> 2')
lb3 = Label(root, text = 'Hello, this is a tag -> 3')
# Label(root, text = 'Hello, this is a tag').pack()
lb1.grid(r... | 405 | 170 |
from __future__ import absolute_import
from populus.utils.contracts import (
is_test_contract,
)
from .base import (
BaseContractBackend,
)
class TestContractsBackend(BaseContractBackend):
"""
Provides access to compiled contract assets sources from the project
`tests_dir`
"""
is_provide... | 836 | 248 |
import argparse
import logging
import re
import struct
import uuid
import sys
from struct import *
import sys
import os
import array
import fcntl
import socket
import fcntl
import struct
import array
from multiprocessing.pool import ThreadPool
from powscan_common.banner_grabber import *
from powscan_common.network_ma... | 2,125 | 708 |
#!/usr/bin/env python
import time
import json
import sys
import tweepy
import slackweb
import configparser
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
def read_config(filename = 'twitter.ini'):
config = configparser.ConfigParser()
config.read(filename)... | 1,563 | 499 |
# -*- coding: utf-8 -*-
"""The sales features related to parking spots"""
from . import views # noqa
| 102 | 37 |
"""An extension of Rainbow to perform quantile regression.
This loss is computed as in "Distributional Reinforcement Learning with Quantile
Regression" - Dabney et. al, 2017"
Specifically, we implement the following components:
* n-step updates
* prioritized replay
* double_dqn
* noisy
* dueling
"""
impor... | 17,537 | 5,282 |
import pandas as pd
from glob import glob
import os
path = 'data/'
all_files = glob(os.path.join(path, '*.json'))
dfs = (pd.read_json(f) for f in all_files)
df = pd.concat(dfs, ignore_index=True)
print (df)
| 208 | 79 |
import torch
import os.path
from utils.train_utils import load_globals, init_folders, init_nets
from loaders.motif_dataset import MotifDS
from PIL import Image
import numpy as np
# network names
root_path = '..'
train_tag = 'vm_demo_text_remover'
load_tag = ''
device = torch.device('cuda:0')
net_path =... | 4,395 | 1,570 |
from django.conf.urls import include, url
from djcyradm.views import locked_out
from djcyradm import views
urlpatterns = [
url(r"session_security/", include("session_security.urls")),
url(
r"^mail-users/$",
views.MailUsersTableView.as_view(),
name="mail-users"),
url(r"^login/?$", v... | 3,651 | 1,292 |
from arraystack import ArrayStack
def is_matched(expr):
"""Return True if all delimiters properly match (or closed); False otherwise"""
left_delimiters = "({["
right_delimiter = ")}]"
S = ArrayStack()
for c in expr:
if c in left_delimiters:
S.push(c)
elif c in right_del... | 651 | 220 |
import discord
from discord.ext import commands
import random
import asyncio
cards = ["villager", "werewolf", "minion", "mason", "seer", "robber", "troublemaker", "drunk", "insomniac", "tanner", "hunter"]
aesthetics = {
"werewolf" : {
"color" : 0x25d0ff,
"thumbnail" : "https://cdn.discordapp.com/a... | 24,522 | 7,246 |
###################################################
# Uses the tweepy client to query a user's tweets #
###################################################
import csv
import tweepy
# Load secrets from separate file
from user_secrets import *
# Set up API client
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRE... | 650 | 224 |
from anime_downloader.sites.anime import Anime, AnimeEpisode, SearchResult
from anime_downloader.sites import helpers
class Nyaa(Anime, sitename='nyaa'):
"""
Site: https://nyaa.si
Config
~~~~~~
filter: Choose filter method in search. One of ['No filter', 'No remakes', 'Trusted Only']
category... | 1,664 | 555 |
from .factories import (coordinates_to_ported_edges,
coordinates_to_ported_edges_with_nodes_pairs,
coordinates_to_ported_leaves,
coordinates_to_ported_points,
coordinates_to_ported_points_pairs_edges_pairs,
... | 1,212 | 331 |
import gzip
import lzma
import warnings
from typing import Optional
import xgboost
def _get_gzip(fname: str) -> bytearray:
return bytearray(gzip.open(fname, "rb").read())
def _get_lzma(fname: str) -> bytearray:
return bytearray(lzma.open(fname, "rb").read())
_magics = {
b"\x1f\x8b": _get_gzip,
b"... | 810 | 318 |