content stringlengths 5 1.05M |
|---|
from turtle import Turtle, Screen
screen = Screen()
my_turtle = Turtle()
def clear():
my_turtle.clear()
my_turtle.penup()
my_turtle.home()
my_turtle.pendown()
def move_forward():
my_turtle.forward(10)
def move_backward():
my_turtle.backward(10)
def turn_right():
new_direction = my_t... |
import torch
import torch.nn as nn
class ImageNetHEAD(nn.Sequential):
def __init__(self, C, stride=2):
super(ImageNetHEAD, self).__init__()
self.add_module(
"conv1",
nn.Conv2d(3, C // 2, kernel_size=3, stride=2, padding=1, bias=False),
)
self.add_module("bn1... |
import discord
from json import loads
from requests import get
from discord.ext import commands
class Covid(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases = ["covid"])
async def ковид(self, ctx):
res = loads(get("https://covid19api.com/summary").t... |
import math
M = 2.0 # Mach Number
mach_angle = math.degrees(math.asin(1 / M))
print(f'The Mach angle at M = { M } is { mach_angle } degrees.') |
#!/usr/bin/env python
import sys
import warnings
from obspy import read, UTCDateTime, read_inventory
#from obspy.clients.fdsn.header import FDSNNoDataException
#from numpy import median
#import collections
import numpy as np
warnings.filterwarnings('ignore')
import argparse
parser = argparse.ArgumentParser(descriptio... |
# operator.py
# ALS 2017/06/01
import abc
from .obsobj import obsObj
class Operator(object, metaclass=abc.ABCMeta):
def __init__(self, **kwargs):
"""
objOperator
Parent class for operators that operates on obsobj, e.g., imgLoader.
Params
----------
/either
obj (object of class obsobj): with attr... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
parser.py
@author ejnp
"""
from nameless.lambda_calculus_ast import Variable, Application, Abstraction
class Parser(object):
"""An LL(1) parser that performs syntactic analysis on lambda calculus
source code. An abstract syntax tree is provided if the given ex... |
class List:
def __init__(self, name, tasks, done_tasks):
"""
Includes information about task list
:param name: name of this task list
:param tasks: list of tasks in this task list
:param done_tasks: list of complete tasks in this task list
"""
self.name = na... |
# variables=>
# pk = probablity of event happening
# pki = probability of event not happening(inverse)
# n = number of events we wish to account for ( How many times is event going to happen?)
# t = total number of events outcomes ( coin toss has 2 possible event outcomes)
# We'll make this in a separate function ... |
class Solution(object):
def maxKilledEnemies(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not any(grid):
return 0
m, n = len(grid), len(grid[0])
rowhits = 0
ans = 0
colhits = [0] * n
for i, row in enumerat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from webapp.config import load as load_config
from webapp.server import init as init_app
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
config = load_config()
app = init_app(config)
app.run(
host=config.server_... |
import numpy as np
def print_matrix(state):
counter = 0
for row in range(0, len(state), 3):
if counter == 0 :
print("-------------")
for element in range(counter, len(state), 3):
if element <= counter:
print("|", end=" ")
print(int(s... |
# -*- coding: cp1252 -*-
# Main Module by: Blazetamer and TheHighway
import urllib,urllib2,re,xbmcplugin,xbmcgui,sys,xbmc,os,xbmcaddon
try: from addon.common.addon import Addon
except:
try: from t0mm0.common.addon import Addon
except: from t0mm0_common_addon import Addon
try: from addon.... |
import os
import glob
import uuid
import random
from nose.plugins.attrib import attr
from indra_world.service.app import sc
from indra_world.service.db.manager import DbManager
from indra_world.service.corpus_manager import CorpusManager
from .test_rest_api import _call_api
HERE = os.path.dirname(os.path.abspath(__fil... |
#!/usr/bin/env python3
import codecs
import hashlib
import os
MAIN_GAME_FILE_NAME = 'game.js'
CONFIGS_FILE_NAME = 'configs.js'
ASSETS_FILE_NAME = 'assets.js'
ACTORS_FILE_NAME = 'actors.js'
TEMPLATES_FOLDER = '../../templates/'
MAIN_GAME_TEMPLATE = TEMPLATES_FOLDER + MAIN_GAME_FILE_NAME
ASSETS_TEMPLATE = TEMPLATES_FO... |
import asyncio
from pprint import pprint
from asyncdb.providers import sqlserver
from asyncdb import AsyncDB
from asyncdb.exceptions import default_exception_handler
params = {
"host": "localhost",
"port": "1433",
"database": 'AdventureWorks2019',
"user": 'SA',
"password": 'P4ssW0rd1.'
}
DRIVER ... |
from capreolus import Dependency, ModuleBase, get_logger
logger = get_logger(__name__) # pylint: disable=invalid-name
class Index(ModuleBase):
"""Base class for Index modules. The purpose of an Index module is to represent an inverted index that can be queried with a :class:`~capreolus.searcher.Searcher` modul... |
import jingo
import jinja2
from waffle import flag_is_active, sample_is_active, switch_is_active
@jinja2.contextfunction
def flag_helper(context, flag_name):
return flag_is_active(context['request'], flag_name)
jingo.env.globals['waffle'] = {
'flag': flag_helper,
'switch': switch_is_active,
'sample... |
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain r... |
"""
by Denexapp
"""
import threading
import usb.core
import usb.util
import denexapp_config as dconfig
import time
import sys
class ups():
def __init__(self, gsm_object):
self.warning_sent = False
self.ready_to_work = True
self.stop = False
self.gsm_object = gsm_object
sel... |
import uuid
from django import template
from django.conf import settings
from paypal.standard.forms import PayPalPaymentsForm
register = template.Library()
# Paypal subscriptions
def paypal_form_for(product, user):
paypal_dict = {
"business": settings.PAYPAL_RECEIVER_EMAIL,
"currency_code": "GBP... |
# Copyright (c) 2017, Matt Layman
from .base import Command # NOQA
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
import copy
from rest_framework.exceptions import ValidationError
from api.data_structures.operation_output_spec import output_spec_mapping
from api.serializers.input_output_spec import InputOutputSpecSerializer
class OutputSpecSerializer(InputOutputSpecSerializer):
'''
Serializes/deserializes OutputSpec inst... |
import os
import sys
import unittest
from pathlib import Path
from examples.example_parametric_shapes import (
make_blanket_from_parameters, make_blanket_from_points,
make_CAD_from_points, make_can_reactor_from_parameters,
make_can_reactor_from_points, make_html_diagram_from_stp_file,
)
import paramak
s... |
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import List, Optional, Any, Dict, Tuple
import numpy as np
from .cards_board_state import CardsBoardState
from .military_state_track import MilitaryTrackState
from .player_state import PlayerState
class GameStatus(Enum):
PICK_WONDE... |
#-*- coding:utf-8 -*-
#'''
# Created on 19-5-11 下午3:39
#
# @Author: Greg Gao(laygin)
#'''
'''adapted from csp, many thanks to the original authors'''
from keras import backend as K
import tensorflow as tf
epsilon = 1e-4
def cls_center(y_true, y_pred):
classification_loss = K.binary_crossentropy(y_pred[:, :, :, 0... |
import uuid
import requests
from kong import handler
from test_cfn_kong_service_provider import Request as ServiceRequest
def clean_plugins():
request = Request('Create', {})
url = '%s/plugins' % request.admin_url
response = requests.get(url)
if response.status_code == 200:
plugins = respons... |
#print("hello")
from helper import greeting
#greeting("hi there")
greeting("hello")
greeting("this is another message")
|
from import_export import resources
from .models import School
class SchoolResource(resources.ModelResource):
class Meta:
model = School
exclude = ()
|
Mein neuer Code...
Mein weiterer Code
|
import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(40), nullable=... |
"""
opencadd.databases.klifs module
"""
from .api import setup_local, setup_remote
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import logging
import multiprocessing
import socket
from qw.client import Client
from qw.exception import AlreadyStartedException, NotStartedException
from qw.worker import Worker
class Manager(object):
__slots__ = ["workers", "client", "num_workers", "log", "name", "target"]
def __init__(self, target, host... |
import numpy as np
from scipy.stats import t
class Uncertainty(object):
"""Computes the uncertainty of a measurement.
Attributes
----------
cov: float
Coefficient of variation for all transects used in dicharge computation
cov_95: float
Coefficient of variation inflated to the 95%... |
import imblearn
import numpy as np
import pandas as pd
import math
#import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import warnings
warnings.simplefilter('ignore')
warnings.filterwarnings("ignore", category=DeprecationWarning)
print("###########################################")
d... |
#!/usr/bin/env python
from configuration.config import BASEURL
from api.txtly.txtly_response import TxtlyResponse
from api.txtly.txtly_report import TxtlyReport
from api.txtly.txtly_log import TxtlyLog
from utility.klient import Klient
__author__ = "Likhit Jain and Yashita P Jain"
__copyright__ = "Copyright 2019, Kal... |
"""
Test module for pcap_to_node_pcap.py
Created on 20 December 2018
@author: Charlie Lewis
"""
import argparse
from .pcap_to_node_pcap import get_path, ipaddress_fields, run_tool, parse_pcap_json_to_layers, pcap_name_with_layers, parse_args
def test_parse_pcap_json():
test_pcap_json = [{
"_source": {
... |
valor = input('Digite Algo: ')
print('É Alfanumérico: ', valor.isalnum())
print('É Alfabético: ', valor.isalpha())
print('É ASCII: ', valor.isascii())
print('É Decimal: ', valor.isdecimal())
print('É um Dígito: ', valor.isdigit())
print('É um Indentificador: ', valor.isidentifier())
print('Está em Minúsculas: ', valor.... |
needed_experience = float(input()) # 500 при достигане на стойността, принтираме броя завъртания
count = int(input()) # 5 брой завъртания
counter = 0
total = 0
for i in range(1, count + 1):
input_number = float(input()) # входните данни
total += input_number
counter += 1
if i % 3 == 0:
... |
"""
Pyfranca processor tests.
"""
import unittest
import os
import errno
import shutil
from pyfranca import ProcessorException, Processor, ast
class BaseTestCase(unittest.TestCase):
def setUp(self):
# Create temporary file directory.
tmp_dir = self.get_spec()
try:
os.makedir... |
# Path
default_matrix = "data/default_matrix.sav"
log_dir = "log"
graph_dir = "graphs"
data_dir = "data"
# Person
hunger_check = 5
# logging
on_screen_print = True
person_messages = False
# life expectancy, max age
longest_life = 120
# speed
speed = 1
birth_rate = 0.248 # best for balance population equalibrium |
#!/usr/bin/env python3
#
# Copytright 2021 Graviti. Licensed under MIT License.
#
# pylint: disable=invalid-name
"""Dataloader of RarePlanesSynthetic dataset."""
import os
from itertools import takewhile
from typing import Any, Callable, Dict, List, Tuple, Union
import numpy as np
from tensorbay.dataset import Data... |
import json
from json import JSONDecodeError
from .ping import ping
from .subscribe import subscribe
from .unsubscribe import unsubscribe
from .status import status
# Registered actions callbacks
ACTIONS = {
'subscribe': subscribe,
'unsubscribe': unsubscribe,
'status': status
}
async def handle_message(... |
"""Commands for scene events tracking in maya.
Scene tracking observes if files are opened, closed or Maya exits.
That may be important for deleting and recreating callbacks automatically.
When Maya exits, we will try to disconnect from the Editor and save
settings.
"""
import logging
import pymel.api as mapi
imp... |
import torch
import torch.nn as nn
torch.manual_seed(123)
fake_img = torch.ones((3, 8, 8))
fake_img = torch.rand_like(fake_img)
fake_img.requires_grad_(True)
lin = nn.Linear(in_features=192, out_features=50)
lin2 = nn.Linear(in_features=50, out_features=2)
print(lin.weight.requires_grad)
print(fake_img.requires_grad... |
import numpy as np
optimized_M_16_96_1 = np.array([[0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 1.,
0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 1., 0., 0., 1., ... |
import os
from hunter import trace
from xunter import CallPrinterProfile, StackPrinterProfile
printers = ['stack', 'call']
printer = os.environ.get('XUNTER_PRINTER', 'stack')
if printer == 'call':
printer = CallPrinterProfile
elif printer == 'stack':
printer = StackPrinterProfile
else:
raise Exception('Unk... |
from random import randint
from time import sleep
print('ÍMPAR OU PAR!!')
print('=' * 35)
print('''Escolha:
Ímpar
Par''')
print('=' * 35)
computador = randint(0,10)
jogador = input('Ímpar ou par? ')
print('=' * 35)
if jogador != 'impar' and jogador != 'par':
print('Jogada inválida!')
... |
class Templator:
def nginxWrap(self,domain,body):
template = '''
proxy_cache_path /data/nginx/cache/'''+domain+''' levels=1:2 keys_zone='''+domain+''':10m inactive=24h max_size=1g;
'''+body+'''
'''
return template
def nginxHTTP(self,domain,target):
template = '''
server {
listen 80;... |
import re
from datetime import datetime
from email import policy
from email.parser import BytesParser
from city_scrapers_core.constants import BOARD
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
class AkrAirportAuthoritySpider(CityScrapersSpider):
name = "... |
import sys
import json
import base64
import requests
from ..exceptions import Auth0Error
UNKNOWN_ERROR = 'a0.sdk.internal.unknown'
class RestClient(object):
"""Provides simple methods for handling all RESTful api endpoints. """
def __init__(self, jwt, telemetry=True):
self.jwt = jwt
if te... |
from cryptoxlib.exceptions import CryptoXLibException
class LiquidException(CryptoXLibException):
pass |
from qmc.wavefunction import HarmonicTrialFunction, ParticleBoxFunction, HydrogenTrialWavefunction, \
HeliumTrialWavefunction, NelectronVander, NelectronVanderWithMult
import torch
import numpy as np
from hypothesis import given
from hypothesis.extra.numpy import arrays
from hypothesis.strategies import floats
# t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOverseasTransferConsultResponse(AlipayResponse):
def __init__(self):
super(AlipayOverseasTransferConsultResponse, self).__init__()
self._channel_list = None
... |
_base_ = ["ss_FreezeBN_20e_Blender08_bboxCrop_refinePM100_blenderCrop_DZI10_ape.py"]
# refiner_cfg_path = "configs/_base_/self6dpp_refiner_base.py"
OUTPUT_DIR = "output/self6dpp/ssLMCrop/FreezeBN_20e_Blender08_bboxCrop_refinePM100_blenderCrop_DZI10/duck"
DATASETS = dict(
TRAIN=("lm_crop_duck_train",), # real da... |
from setuptools import setup
setup(
name='package',
version='0.1',
description="magic. it's full of magic.",
author='buck',
author_email='buck@buck.buck',
packages=['package'],
)
|
from bs4 import BeautifulSoup
import requests
import jsobj
class Bandcamp:
def parse(self, url):
try:
r = requests.get(url)
except requests.exceptions.MissingSchema:
return None
if r.status_code is not 200:
return None
self.soup = BeautifulSo... |
"""
MIT License
Copyright (c) 2020 Dominik Kopczynski - dominik.kopczynski {at} isas.de
Nils Hoffmann - nils.hoffmann {at} isas.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 ... |
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result, numberOfCandidates = [], len(candidates)
def backtrack(remainingSum, currentCombination, startIndex):
if remainingSum == 0:
result.append(list(currentCombination))
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FileSenderWindow.ui'
#
# Created: Mon Oct 09 13:21:21 2006
# by: PyQt4 UI code generator 4.0.1
#
# WARNING! All changes made in this file will be lost!
import sys
from PyQt4 import QtCore, QtGui
class Ui_FileSenderWindow(o... |
import unittest
import os
import shutil
from blobobj.blob_obj import BlobObject
from tools_objects import get_file_dirs
class BlobObjectTest(unittest.TestCase):
""" проверяем работоспособность объектов типа Blob """
@classmethod
def setUpClass(cls) -> None:
cls.current_dir_test = os.path.dirname... |
# Copyright (c) 2017 Fujitsu Limited
# 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 requi... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import os
import glob
import math
import random
import time
import datetime
from collections import defaultdict
from tqdm import tqdm, tqdm_notebook
import xml.etree.ElementTree as ... |
import numpy as np
import matplotlib.pyplot as plt
import pickle
from wotan import flatten
from astropy.io import ascii
import pickle
from astropy.io import fits
from matplotlib.patches import ConnectionPatch
from matplotlib import colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from tqdm impor... |
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
cur_len = cur_max = 1
cur_num = nums[0]
for num in nums[1:]:
if num > cur_num:
cur_len += 1
... |
#!/usr/bin/env python3
"""
Keras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.
The current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.
Adopting to other backends should be easy, but I have not tested this.
Usage:
p... |
"""A low-memoryt variant of sequence finder
"""
from copy import deepcopy
from typing import List
import numpy as np
from .neighbours import Neighbours
class SequenceFinder:
"""Testing a low-memory approach to finding sequences.
Returns:
A sequence finder object
"""
neighbours: Neighbour... |
import unittest
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from CNN import train_cnn
class Test_CNN(unittest.TestCase):
def test_input_shape(self):
"""
Test that the input shape is as expected
"""
shape = ()
image = tf.ones(shape)
s... |
from __future__ import absolute_import
from djay.commands.dj import dj
if __name__ == '__main__':
try:
dj()
except SystemExit as e:
if e.code:
raise
|
from audio_separation.rl.ppo.ppo_trainer import PPOTrainer, RolloutStoragePol, RolloutStorageSep
from audio_separation.pretrain.passive.passive_trainer import PassiveTrainer
__all__ = ["BaseTrainer", "BaseRLTrainer", "PPOTrainer", "RolloutStoragePol", "RolloutStorageSep", "PassiveTrainer"]
|
from pathlib import Path
import numpy as np
import h5py
from datetime import datetime
from input import parameters as para
from lib import cfl as cfl
from lib import write_field as wf
from lib import avg_profile as avgp
from lib import grid as gd
from lib import timehistory as tmsr
from lib import initial as initC
from... |
"""Fields."""
from abc import ABC
from abc import abstractmethod
from enum import auto
from enum import Enum
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Tuple
from typing import Type
from typing import Union
from pydent.marshaller.descriptors im... |
# Generated by Django 3.2.5 on 2021-07-06 02:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0008_auto_20210703_1732'),
]
operations = [
migrations.RenameField(
model_name='chapter',
old_name='votes',
... |
#!/usr/bin/env python3
"""Multi Processing based routines"""
import logging
logger = logging.getLogger("MP")
def multiprocessing(args=None):
logger.info("multiprocessing")
if args:
print(vars(args))
logger.info(vars(args))
|
# Copyright 2020 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from abc import ABC
from enum import Enum
from typing import Any, Callable, Dict
from aiomusiccast.musiccast_data import RangeStep
class EntityType(Enum):
"""Type of the Capability."""
REGULAR = 1 # For major features
CONFIG = 2 # For features to configure the device or a zone
DIAGNOSTIC = 3 # For... |
class Pessoa:
olhos=2
def __init__(self,*filhos,nome=None,idade=35):
self.idade = idade
self.nome=nome
self.filhos=list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
def nome_e_... |
# coding: utf-8
"""
Connect API
Pelion Device Management Connect API allows web applications to communicate with devices. You can subscribe to device resources and read/write values to them. Device Management Connect allows connectivity to devices by queueing requests and caching resource values.
OpenAPI... |
from itertools import groupby
from random import shuffle
from typing import Iterable, List, Tuple
from django.conf import settings
from django.contrib import messages
from django.db import models, transaction
from django.http import HttpResponse, HttpResponseNotAllowed
from django.shortcuts import get_object_or_404, r... |
from typing import List
from rlutilities.simulation import Game, Car, Ball, Pad
from rlutilities.linear_algebra import vec3
class Goal:
WIDTH = 1784.0
HEIGHT = 640.0
DISTANCE = 5120.0
def __init__(self, team):
sign = -1 if team == 0 else 1
self.center = vec3(0, sign * Goal.DISTANCE,... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
token = 'your gitee account token' |
from flask import *
import os
from decorators import validate_account_and_region
from aws import connect, route53
elastatus = Blueprint('elastatus', __name__)
@elastatus.route('/')
def index():
return redirect('/%s/%s/%s' % (current_app.config['CONFIG']['default_account'],
cu... |
from abc import ABC
from typing import List
from card import Card
class Participant:
def __init__(self):
self.name = None
def get_cards(self) -> List[Card]:
raise NotImplementedError
def clear_cards(self):
raise NotImplementedError
def add_a_card(self, card: Card):
... |
import pandas as pd
import numpy as np
import os
import shutil
import re
from shutil import unpack_archive, move
from datetime import date
from pathlib import Path
from typing import Optional, List
class GooglePlayProcessor:
source_directory_path: Path
processed_data_path: Path
country_impressions_df: Optional[... |
from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer
# normal function to run on cpu
def func(a):
for i in range(10000000):
a[i] += 1
# function optimized to run on gpu
@jit(target="cuda")
def func2(a):
for i in range(10000000):
... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006 (ita)
"""
Custom objects:
- execute a function everytime
- copy a file somewhere else
"""
import shutil, re, os
import TaskGen, Node, Task, Utils, Build, Constants
from TaskGen import feature, taskgen, after, before
from Logs import debug
def copy_func(ts... |
#!/usr/bin/python3
import requests
def run():
url = "https://api.github.com/users/andrew/repos"
result = get_repositories(url)
print(result)
print(len(result))
def get_repositories(url):
result = []
r = requests.get(url=url)
if 'next' in r.links :
result += get_repositories(r.links... |
import os, os.path
import shutil
from play.utils import *
COMMANDS = ['idealize', 'idea']
HELP = {
'idealize': 'Create all IntelliJ Idea configuration files'
}
def execute(**kargs):
command = kargs.get("command")
app = kargs.get("app")
args = kargs.get("args")
play_env = kargs.get("env")
ap... |
import subprocess # skipcq: BAN-B404
class Brew:
@staticmethod
def install(package: str) -> None:
subprocess.run( # skipcq: BAN-B603
["/usr/local/bin/brew", "install", package], check=True
)
@staticmethod
def update() -> None:
subprocess.run( # skipcq: BAN-B603
... |
from unittest import TestCase
import subprocess
class SourceFileTestCase(TestCase):
def assertWorks(self, filename):
proc = subprocess.run([
'darglint', filename
])
self.assertTrue(
proc.returncode in {0, 1},
'Expected error code 0 or 1, but got {} for ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
import os
ROOT_DIR = os.getenv('PLASTICC_DIR')
WORK_DIR = os.path.join(ROOT_DIR, 'plasticc')
sys.path.append(WORK_DIR)
import numpy as np
import argparse
import ANTARES_object
import p... |
#!/usr/bin/env python3
# FreeRTOS STM32 Reference Integration
#
# Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 So... |
# coding=utf-8
from __future__ import unicode_literals
from utils.models import JSONField
from account.models import User
from contest.models import Contest
from utils.models import RichTextField
from utils.constants import Choices
from django.db import models
class CodeInfo(models.Model):
#code_id=models.Integer... |
from django.urls import path
from . import views
urlpatterns = [
path("login/", views.LoginView.as_view(), name="login"),
path("signup/", views.SignupView.as_view(), name="signup"),
path("logout/", views.LogoutView.as_view(), name="logout"),
path(
"password/reset/",
views.PasswordReset... |
# Copyright 2019 The Tranquility Base 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 agree... |
# pylint: disable=redefined-outer-name, missing-function-docstring, unused-import, too-many-arguments
from datetime import datetime
from copy import deepcopy
from unittest.mock import Mock
import pytest
from pyspark.sql import functions as sf
from pyspark.sql.types import StringType, StructType
from replay.constants ... |
# WARNING: Do not edit by hand, this file was generated by Crank:
#
# https://github.com/gocardless/crank
#
import json
import requests
import responses
from nose.tools import (
assert_equal,
assert_is_instance,
assert_is_none,
assert_is_not_none,
assert_not_equal,
assert_raises
)
from gocardless_pro.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.