id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3274274
<filename>tests/general_tests.py<gh_stars>1-10 import os os.environ['WINNOW_CONFIG'] = os.path.abspath('config.yaml') from glob import glob import numpy as np from winnow.feature_extraction import IntermediateCnnExtractor,frameToVideoRepresentation,SimilarityModel from winnow.utils import create_directory,scan_videos,g...
StarcoderdataPython
175431
<filename>txircd/modules/rfc/response_error.py from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class ErrorResponse(ModuleData): implements(IPlugin, IModuleData) name = "ErrorResponse" core = True def actions(self): return [ ...
StarcoderdataPython
4838485
<filename>hotmail_eml_to_txt_converter/parser/HotmailEMLChainParser.py import quopri as qp from bs4 import BeautifulSoup from hotmail_eml_to_txt_converter.parser.Email import Email from datetime import datetime class HotmailEMLChainParser(): # Parses .eml files downloaded from Hotmail into individual email objects...
StarcoderdataPython
183587
<reponame>ShaswatPrabhat/LinkedList from LinkedList import LinkedListNodes class SinglyLinkedList: def __init__(self, sourceList: list): lastInitializedNode: LinkedListNodes.SinglyLinkedNode or None = None self.headOfList: LinkedListNodes.SinglyLinkedNode or None = None self.length = len(...
StarcoderdataPython
1718741
import logging from time import sleep, time from bs4 import BeautifulSoup from xml.etree import ElementTree import requests USER_AGENT = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) ' 'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 ' 'Safari/605.1.15') class Site(object): ...
StarcoderdataPython
3225520
<filename>exploit/webapp/apache/Apache_Struts_2_CVE-2013-2251.py #!/usr/bin/python from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import input from builtins import str import urllib.request, urllib.error, urllib.parse import time import sys im...
StarcoderdataPython
1754270
### Exercicio 4 e 5 def primo(v): for i in range(2,(v//2)+1): if v % i == 0: return False return True ### Exercicio 4 valor = int(input("Digite um valor: ")) if primo(valor): print(f"{valor} e primo!") else: print(f"{valor} nao e primo!") print("\n\n") ### Exercicio 5 f = int(input("Digite o valor d...
StarcoderdataPython
3336673
from pygbif import species from .format_helpers import _make_id def gbif_query_for_single_name(name, rank): response = species.name_usage(name=name, rank=rank.upper())["results"] return response def process_gbif_response(list_of_response_dicts, rank): key = rank + "Key" extracted_ids = list( ...
StarcoderdataPython
1723968
from django.contrib import admin from imagekit.admin import AdminThumbnail from common.admin import AutoUserMixin from shapes.models import SubmittedShape, \ MaterialShape, ShapeSubstance, ShapeSubstanceLabel, \ ShapeName, MaterialShapeNameLabel, MaterialShapeQuality from normals.models import ShapeRectifiedN...
StarcoderdataPython
1639780
<gh_stars>0 # coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2....
StarcoderdataPython
90108
<reponame>Y-Kuro-u/chariot import os import mmap from chariot.util import xtqdm class DataFile(): def __init__(self, path, encoding="utf-8"): self.path = path self.encoding = encoding file_name = os.path.basename(path) base_name, ext = os.path.splitext(file_name) self.base...
StarcoderdataPython
1686876
<filename>env/Lib/site-packages/anyio/_core/_signals.py from typing import AsyncIterator from ._compat import DeprecatedAsyncContextManager from ._eventloop import get_asynclib def open_signal_receiver(*signals: int) -> DeprecatedAsyncContextManager[AsyncIterator[int]]: """ Start receiving operating system s...
StarcoderdataPython
1774235
from django.contrib import admin from .models import User admin.site.register(User) # admin.site.Register(User) # Register your models here.
StarcoderdataPython
1663595
<filename>scripts/flowpusher_demo.py import httplib import json class StaticFlowPusher(object): def __init__(self, server): self.server = server def get(self, data): ret = self.rest_call({}, 'GET') return json.loads(ret[2]) def set(self, data): ret = self.rest_call(data, ...
StarcoderdataPython
3329030
<gh_stars>0 from main import Link, Event from . import BaseTest class TestViewHandlers(BaseTest): def test_index(self): response = self.app.get('/') assert 'Zongo' in response def test_admin(self): response = self.app.get('/admin') assert response def test_published_link(...
StarcoderdataPython
1735515
<filename>Python3/Coursera/others/use_fork_2.py # Память родительского и дочернего процесса import os import time foo = "bar" if os.fork() == 0: # дочерний процесс foo = "baz" print("child:", foo) else: # родительский процесс time.sleep(2) print("parent:", foo) os.wait()
StarcoderdataPython
4837779
<reponame>jttaylor/TPLink-SmartPlug import json import urllib2 import uuid class SmartPlug: def __init__(self, username, password): self.username = username self.password = password self.token = None self.tp_uuid = str(uuid.uuid4()) self.login_req = { ...
StarcoderdataPython
74758
<reponame>arryaaas/Met-Num<gh_stars>0 from app import app import os if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(debug=True, port=port)
StarcoderdataPython
1756899
<gh_stars>1000+ # -*- coding: utf-8 -*- """Top-level package for Lambda Python Powertools.""" from .logging import Logger # noqa: F401 from .metrics import Metrics, single_metric # noqa: F401 from .package_logger import set_package_logger_handler from .tracing import Tracer # noqa: F401 __author__ = """Amazon We...
StarcoderdataPython
1773245
<reponame>pavoljuhas/diffpy.Structure #!/usr/bin/env python ############################################################################## # # diffpy.structure by DANSE Diffraction group # <NAME> # (c) 2006 trustees of the Michigan State University. # All rights re...
StarcoderdataPython
3363210
mail_address = "<EMAIL>" passplain = "<PASSWORD>" passtwt = "<PASSWORD>" passgoog = "<PASSWORD>"
StarcoderdataPython
3309203
<gh_stars>1-10 """Convolutional Neural Network. """ from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPool2D import dualing.utils.logging as l from dualing.core import Base logger = l.get_logger(__name__) class CNN(Base): """A CNN class stands for a standard Convolutional Neural Network implementa...
StarcoderdataPython
73087
<reponame>penguinwang96825/Intelligent-Asset-Allocation<filename>model/markowitz.py<gh_stars>1-10 from database.database import db from database.tables.price import StockPrice from tqdm import tqdm import datetime as dt import numpy as np import pandas as pd import scipy from pandas_datareader import data class Marko...
StarcoderdataPython
94746
<gh_stars>1-10 import datetime # Django imports from django.contrib.auth.models import Group from rest_framework import permissions # Local imports from config.settings import JWT_AUTH # Create your views here. def jwt_payload_handler(user): """Defines payload to be stored in JWT passed to the client. """ ...
StarcoderdataPython
3209228
import sqlalchemy from flask_taxonomies.constants import INCLUDE_DELETED, INCLUDE_DESCENDANTS, \ INCLUDE_DESCENDANTS_COUNT, INCLUDE_STATUS, INCLUDE_SELF from flask_taxonomies.models import TaxonomyTerm, TermStatusEnum, Representation from flask_taxonomies.proxies import current_flask_taxonomies from flask_taxonomie...
StarcoderdataPython
109992
""" Copyright (c) 2010-2013, Contrail consortium. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
StarcoderdataPython
3380304
import re PRIVILEGED_STATEMENT_RULES = { "\*:\*": "Full AWS Account Admin", "^[A-Za-z0-9]+:\*$": "Full {service} Admin" } FIND_SERVICE_REGEX = "^([A-Za-z0-9]+)(?=:)" RESOURCE_ARN_WITH_SERVICE_REGEX = "^arn:aws(-cn|):{service}:.+" class PoliciesPermissionsParser(object): def __init__(self, policies): ...
StarcoderdataPython
156004
<reponame>adi2011/plugins #! /usr/bin/python3 import py_compile from pyln.client import Plugin import pyqrcode from requests import get plugin = Plugin() def getChannel(peerid, chanid): peer = plugin.rpc.listpeers(peerid) assert peer, "cannot find peer" chan = peer["channels"] assert chan["channel_id...
StarcoderdataPython
3361704
<gh_stars>0 import unittest import sys import os from os import system from time import time from pathlib import Path from unittest.mock import patch from self import test_self_compilation from lib.runner import execute, TimeoutException, set_home_path from tests.utils import CaptureOutput, for_all_test_results class...
StarcoderdataPython
1775162
<reponame>Ostap2003/backtracking-team-project<gh_stars>0 import turtle from stack import Stack from pprint import pprint class PathFinder: """Find path in a maze""" PATH = "o" WALL = "*" USED = "-" def __init__(self, start: tuple, finish: tuple, maze=None, path=None, draw_maze=False): self...
StarcoderdataPython
1796423
<reponame>stevedya/wagtail<gh_stars>1-10 from wagtail.test.dummy_external_storage import * # noqa
StarcoderdataPython
3237223
''' Author: jianzhnie Date: 2022-01-05 16:21:54 LastEditTime: 2022-03-07 16:16:06 LastEditors: jianzhnie Description: ''' import sys import torch import torch.optim as optim from tqdm.auto import tqdm from nlptoolkit.data.utils.utils import (get_loader, load_reuters, save_pr...
StarcoderdataPython
1692386
import re from datetime import date as datetime_date from .add_time import add_months, add_days from calendar import day_name, day_abbr from .YearMonth import YearMonth from .YearQuarter import YearQuarter from .to_quarter import get_quarter from .remove_non_alphanumeric import remove_non_alphanumeric def to_monthnam...
StarcoderdataPython
1692448
#!/usr/bin/python #import import RPi.GPIO as GPIO import rasiberryPiGPIOBaseController.Pin as Pin import time # Define GPIO to LCD mapping LCD_RS = 23 LCD_E = 24 LCD_D4 = 25 LCD_D5 = 1 LCD_D6 = 12 LCD_D7 = 16 # Define some device constants LCD_WIDTH = 16 # Maximum characters per line LCD_CHR = Pin.PIN_HIGH LCD_...
StarcoderdataPython
139104
<filename>ooi_harvester/metadata/cli.py<gh_stars>1-10 import datetime import typer from . import create_metadata app = typer.Typer() @app.command() def create( s3_bucket: str = "ooi-metadata", axiom: bool = False, global_ranges: bool = False, cava_assets: bool = False, ooinet_inventory: bool = F...
StarcoderdataPython
160068
from guizero import App, Text a = App() a.font = "courier new" t1 = Text(a) t1.value = "{}, {}, {}".format(t1.font, t1.text_size, t1.text_color) t2 = Text(a, font="arial") t2.value = "{}, {}, {}".format(t2.font, t2.text_size, t2.text_color) t3 = Text(a, color="red", size=8, font="verdana") t3.value = "{}, {}, {}".f...
StarcoderdataPython
3205999
from enum import Enum as BaseEnum from .packing import pack_int64 from .deserialization import deserialize_int64 from .exceptions import DeserializationError class Enum(BaseEnum): """Enumeration. """ def __ge__(self, other): if self.__class__ is other.__class__: return self._value_ >=...
StarcoderdataPython
1640269
import json def get_report_type(report_type, date_range, rsid): if report_type == 'core_metrics': report = get_core_metrics_report_type(date_range) elif report_type == 'emea_metrics': report = get_country_metrics_report_type(date_range, rsid) else: print("You need to provide an A...
StarcoderdataPython
26830
<filename>evaluation/dwf_power.py from ctypes import * from dwfconstants import * dwf = cdll.LoadLibrary("libdwf.so") hdwf = c_int() dwf.FDwfParamSet(DwfParamOnClose, c_int(0)) # 0 = run, 1 = stop, 2 = shutdown print("Opening first device") dwf.FDwfDeviceOpen(c_int(-1), byref(hdwf)) if hdwf.value == hdwfNone.value: ...
StarcoderdataPython
1749071
<filename>spirit/user/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import set...
StarcoderdataPython
3319236
##for Raleigh & Grant ##who contributed more than they know ################################################################################ ############################## WHEEL OF FORTUNE ################################ ################################################################################ import random im...
StarcoderdataPython
3282187
<filename>optskills/pydart/pydart_api.py # This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.11 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_i...
StarcoderdataPython
3267623
#!/usr/bin/env python import yaml, sys def calib_from_file(filename): y = yaml.load(file(filename, 'r')) lower = [[1e6]*3, [1e6]*3, [1e6]*3] upper = [[-1e6]*3, [-1e6]*3, [-1e6]*3] boards = { 'mm': 0, 'pp': 1, 'dp': 2 } for sample in y: for board_name, board_idx in boards.iteritems(): for axis in xr...
StarcoderdataPython
108696
import subprocess import sys import ipaddress import threading import re import time import platform from datetime import datetime from multiprocessing import Queue # Verifie que oui.txt est present sinon on le recupere try: file = open('oui.txt', encoding='utf-8', mode='r') file.close() except FileNotFoundEr...
StarcoderdataPython
30404
# 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 json from pathlib import Path import pytest import cc_net import cc_net.minify as minify from cc_net import jsonql, process_wet_fil...
StarcoderdataPython
1694378
''' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ SALT RSS Calibration This program performs the flux calibration and heliocentric velocity correction for a FITS file reduced by the SALT RSS pipeline. The target FITS file is typically a 2D flux spectrum of a galaxy, but may but may be other...
StarcoderdataPython
172348
<filename>cloudrail/knowledge/rules/aws/non_context_aware/iam_no_human_users_rule.py from typing import Dict, List from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext from cloudrail.knowledge.rules.aws.aws_base_rule import AwsBaseRule from cloudrail.knowledge.rules.base_rule import...
StarcoderdataPython
3260434
<reponame>rgreinho/pyconsql<gh_stars>0 """Define the connexion settings for a local setup.""" import os # pylint: disable=wildcard-import,unused-wildcard-import from pyconsql.api.settings.common import * # noqa DEBUG = True if os.environ.get("KUBERNETES_PORT"): minikube_ip = os.environ.get("MINIKUBE_IP", "192.16...
StarcoderdataPython
1627165
#!/usr/bin/env python """ Copy the configuration file from the repository to the current directory, for editing. """ import argparse import os import sys import yaml import textwrap from XtDac.ChandraUtils import logging_system from XtDac.data_files import get_data_file_path from XtDac.ChandraUtils.sanitize_filename...
StarcoderdataPython
141887
# JANKENPOOP import nextcord import config from nextcord.ext import commands client = commands.Bot(command_prefix = 'janken ') game = nextcord.Game("Legacy Code Course") @client.event async def on_ready(): await client.change_presence(status=nextcord.Status.idle, activity=game) print("JANKENPOPP IS HERE HAHAH...
StarcoderdataPython
155963
<filename>tbonlineproject/RegistrationRecaptcha/forms.py<gh_stars>0 from registration.forms import RegistrationForm from CommentRecaptcha.fields import ReCaptchaField class RegistrationFormRecaptcha(RegistrationForm): recaptcha = ReCaptchaField()
StarcoderdataPython
1651645
#! /usr/bin/env python3 # coding=utf-8 """ Contains all logging related tools and logging settings. """ import argparse import functools import logging import os import pprint import sys # Convert verbose arguments to their corresponding level _string_to_level = { "DEBUG": logging.DEBUG, "INFO": logging.INFO,...
StarcoderdataPython
3335372
<reponame>smevirtual/aperte # Copyright 2018 SME Virtual Network Contributors. 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/LICE...
StarcoderdataPython
3327040
<filename>plugins/titlegiver/test/test_titlegiver.py # coding=utf-8 import threading import urllib import os import json import urllib.parse import unittest import http.server from plugins.titlegiver.titlegiver import Titlegiver __author__ = "tigge" __author__ = "reggna" class Handler(http.server.BaseHTTPRequestHan...
StarcoderdataPython
1720136
<reponame>eddyydde/wikitablestosql import os import csv import bz2 def prepare_parts_using_index(data_directory, file, index, done=0): """ Prepare parts by cutting multistream file according to index. Prepare decompression directory. :param data_directory: path as string :param file:...
StarcoderdataPython
15746
from cdm.objectmodel import CdmCorpusDefinition, CdmManifestDefinition from cdm.storage import LocalAdapter from cdm.enums import CdmObjectType def generate_manifest(local_root_path: str) -> 'CdmManifestDefinition': """ Creates a manifest used for the tests. """ cdmCorpus = CdmCorpusDefinition() ...
StarcoderdataPython
3228000
import math from construct import * # "Why not use PIL" - PIL can read, but, as far as I could tell, won't natively create # real, true, 16 color bmp. You can make a 16 color image just fine, but when you save it, # it'll be formatted as a 256 color image. Maybe I'm wrong! bitmap_struct = Struct( "signature" / C...
StarcoderdataPython
3297613
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is for experiment: random number of splits @author: aaron """ from main import * import glob import multiprocessing as mp import os from extract import * import joblib logger = logging.getLogger('cumul') def parse_arguments(): parser = argparse.Argumen...
StarcoderdataPython
1663015
import math import numpy as np from tidyframe import Possibly @Possibly() def log_possibly(x): return math.log(x) def test_Possibly_basic_success(): assert np.isclose(log_possibly(10), math.log(10)), 'Must result is True' def test_pPossibly_basic_fail(): assert np.isnan(log_possibly(-10)), 'Must resul...
StarcoderdataPython
157745
import os import sys import numpy as np def get_malware_dataset(valid=False): def get_monthly_data(file_path, num_feature=483): '''Each row of `x_mat` is a datapoint. It adds a constant one for another dimension at the end for the bias term. Returns: two numpy arrays, one...
StarcoderdataPython
28163
<gh_stars>1-10 from django.core.exceptions import ValidationError from django.test import TestCase from django_analyses.models.input.types.input_types import InputTypes from tests.factories.input.types.file_input import FileInputFactory class FileInputTestCase(TestCase): """ Tests for the :class:`~django_anal...
StarcoderdataPython
116371
import matplotlib.pyplot as plt import numpy import argparse import json import socket def get_args(): parser = argparse.ArgumentParser( description='Charcoal Dryrot Generate result plots.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-e', ...
StarcoderdataPython
3363870
import os, sys import numpy as np from pyutils.cmd import runSystemCMD from scipy.interpolate import RegularGridInterpolator sys.path.insert(0, '3rd-party/vrProjector/') import vrProjector def dir2samples(path): files = os.listdir(path) files = [fn for fn in files if len(fn.split('.')) and fn.split('.')[-1] i...
StarcoderdataPython
156850
"""Unit tests for Coptic NLP""" import io, re, os, sys from collections import defaultdict from six import iterkeys script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep data_dir = script_dir + "data" + os.sep lib_dir = script_dir + "lib" + os.sep from coptic_nlp import nlp_coptic from lib.stacked_tokeni...
StarcoderdataPython
142031
import ui from os import getcwd, listdir, mkdir, rename from os.path import isdir, join from threading import Thread from random import choice from time import sleep leidos = 0 cambiados = 0 finish = False def map_dirs(directory=getcwd()): _map = [] for file in listdir(directory): _map.append(join(directory, fi...
StarcoderdataPython
3273005
#!/usr/bin/env python3 t = sorted([int(round(100*float(x))) for x in input().split()]) o = int(round(100*float(input()))) best = (t[0] + t[1] + t[2]) worst = (t[1] + t[2] + t[3]) if 3*o < best: print('impossible') elif 3*o >= worst: print('infinite') else: print(f'{(3*o-t[1]-t[2])/100.:.2f}')
StarcoderdataPython
3351166
<filename>python/paddle/fluid/tests/unittests/test_set_value_op.py<gh_stars>1-10 # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
StarcoderdataPython
1690969
initial_number = int(input()) bonus_points = 0 if initial_number <= 100: bonus_points += 5 elif 100 < initial_number <= 1000: bonus_points = initial_number * 0.2 elif initial_number > 1000: bonus_points = initial_number * 0.1 additional_bonus = 0 if initial_number % 2 == 0: additional_bonus += 1 thi...
StarcoderdataPython
3384864
<gh_stars>1-10 import torch import numpy as np import torch.nn.functional as F from torch import nn, optim import torch.nn.utils.rnn as rnn_utils class SentLSTM(nn.Module): def __init__(self, embedding_dim, hidden_dim, batch_size, bi_direction=True): super(SentLSTM, self).__init__() self.hidden_di...
StarcoderdataPython
3369311
<filename>pythonExercicios/ex092.py<gh_stars>0 from datetime import datetime as dt dados = {} dados['Nome'] = input('Nome: ') nasc = int(input('Ano de nascimento: ')) novos_dados = { 'Idade': dt.now().year - nasc, 'Carteira de trabalho': int(input('Carteira de trabalho (0 não tem):'))} dados.update(novos_dados)...
StarcoderdataPython
1732346
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-10-12 13:19 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0004_reviews_average'), ] operations = [ migrations.RemoveField( ...
StarcoderdataPython
3206280
""" Views for OGPFake This view gathers all necessary tags from GET request, then gets information from enviromental variables and renders the final page. <NAME>, 2018, https://github.com/Naeriam """ import os from django.shortcuts import render def ogpfake(request): # Get all necessary tags o...
StarcoderdataPython
3305145
""" support for presenting detailed information in failing assertions. """ import py import sys from _pytest.monkeypatch import monkeypatch from _pytest.assertion import util def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption('--assert', action="store", dest="assertmode", ...
StarcoderdataPython
3207431
<reponame>joshriess/InfraBot<filename>agent/agent.py import requests from time import sleep timeToWait = 300 # Time to wait between callouts (in seconds) while (True): # Get list of commands to run this callout URL = "https://slack.flemingcaleb.com:5000/api/agent/4/command/" r = requests.get(url=URL) ...
StarcoderdataPython
4827558
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from optionaldict import optionaldict from teambition.api.base import TeambitionAPI class Teams(TeambitionAPI): def get(self, id=None, organization_id=None, project_id=None): """ 获取团队 详情请参考 http://d...
StarcoderdataPython
1677832
# stdlib from enum import Enum from typing import List from typing import Optional # third party from google.protobuf.reflection import GeneratedProtocolMessageType from nacl.signing import VerifyKey # relative from ...... import deserialize from ...... import serialize from ......logger import critical from ......lo...
StarcoderdataPython
1633036
<reponame>ada-shen/utility import os import sys import tensorflow as tf BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, 'models')) sys.path.append(os.path.join(BASE_DIR, 'tf_utils')) import tf_util from pointSIFT_util import pointSIFT_module, point...
StarcoderdataPython
3352059
<gh_stars>1-10 import sys sys.path.append('..') from intcode.intcode import IntCodeComputer GRID_RADIUS = 100 BLACK = 0 WHITE = 1 LEFT = 0 RIGHT = 1 # Left moves left through array and vice versa. AROUND = [(0, -1), (1, 0), (0, 1), (-1, 0)] class HullPaintingRobot: def __init__(self, start_on_white=False): ...
StarcoderdataPython
127977
<filename>setup.py<gh_stars>1-10 from setuptools import setup, find_packages setup( name='pyclics-clustering', version='1.0.1.dev0', description="clustering algorithms for CLICS networks", long_description=open("README.md").read(), long_description_content_type='text/markdown', author='<NAME> ...
StarcoderdataPython
1724582
<reponame>rootulp/exercism<filename>python/beer-song/beer.py class Beer: LAST_LINE = ('Go to the store and buy some more, ' '99 bottles of beer on the wall.') @classmethod def song(cls, start, stop): return "\n".join([cls.verse(verse_num) for verse_num in...
StarcoderdataPython
1709147
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from tqdm import tqdm from abc import ABCMeta, abstractmethod import paddle import paddle.nn as nn from paddle.io import DataLoader from paddlemm.models import CMML, ...
StarcoderdataPython
3365976
<gh_stars>0 import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Flatten, Conv3D, Conv3DTranspose, Dropout, ReLU, LeakyReLU, Concatenate, ZeroPadding3D from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import MeanSquared...
StarcoderdataPython
59298
<reponame>6A/asmsq from ..testsource import * # pylint: disable=W0614 class ArmTestSource(TestSource): @property def name(self) -> str: return 'arm' @property def test_cases(self) -> TestCases: yield TestCase('should encode single cps instruction', [ self.make_call('cps',...
StarcoderdataPython
3338878
from mashcima import Mashcima from mashcima.Sprite import Sprite from mashcima.SpriteGroup import SpriteGroup from mashcima.debug import show_images from typing import List import numpy as np # mc = Mashcima([ # "CVC-MUSCIMA_W-01_N-10_D-ideal.xml", # "CVC-MUSCIMA_W-01_N-14_D-ideal.xml", # "CVC-MUSCIMA_W-0...
StarcoderdataPython
1782248
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-11 18:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AnimeSeri...
StarcoderdataPython
3284380
import torch from torch2trt.torch2trt import * from torch2trt.module_test import add_module_test from .size import IntWarper @tensorrt_converter('torch.nn.functional.interpolate') def convert_interpolate(ctx): input = ctx.method_args[0] try: scale_factor = get_arg(ctx, 'scale_factor', pos=2, default=...
StarcoderdataPython
4807784
<filename>src/schedule.py import torch import math class BaseLearningRateSchedule(object): def __init__(self): self.step_num = 0 self.decay_rate = 1. def set_lr(self, optimizer, init_lr): for param_group in optimizer.param_groups: param_group['lr'] = init_lr * ...
StarcoderdataPython
3281099
<filename>apprise/plugins/NotifyGrowl/NotifyGrowl.py # -*- coding: utf-8 -*- # # Copyright (C) 2019 <NAME> <<EMAIL>> # All rights reserved. # # This code is licensed under the MIT License. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
StarcoderdataPython
1709349
<reponame>saikumarkethi/memae-anomaly-detection from __future__ import absolute_import, print_function import torch from torch import nn from models import MemModule class AutoEncoderCov3DMem(nn.Module): def __init__(self, chnum_in, mem_dim, shrink_thres=0.0025): super(AutoEncoderCov3DMem, self).__init__(...
StarcoderdataPython
1607851
""" Starting Template Once you have learned how to use classes, you can begin your program with this template. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.starting_template """ import arcade import random import math from Criteria impor...
StarcoderdataPython
24095
#!/usr/bin/env python # Copyright (c) 2019 Riverbed Technology, Inc. # # This software is licensed under the terms and conditions of the MIT License # accompanying the software ("License"). This software is distributed "AS IS" # as set forth in the License. import csv import sys import string import optparse from co...
StarcoderdataPython
121166
<filename>pyeasytd/entries/json_easy.py from .__init__ import * class JsonEasyEntry: ''' 基于json模型封装实体,适用于规则的多层嵌套json读取 ''' __level_prefix = 'level_' __init_load_status = False __json = None __json_text = None __struct = None __count = None def __init__(self, data: str or dict o...
StarcoderdataPython
144463
# 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 th...
StarcoderdataPython
103772
<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import division import os import numpy as np from os.path import isfile, join from os import listdir import sys sys.path.append('../') from types import SimpleNamespace as Namespace # from SimpleNamespace import SimpleNamespace as Namespace import random import o...
StarcoderdataPython
830
<gh_stars>1-10 def getNumBags(color): if color=='': return 0 numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as f: rules=dict([l.split(' contain') for l in f.read().replace(' bags', '').replace(' bag', '').replace('.',...
StarcoderdataPython
3240413
<filename>tworaven_apps/rook_services/views.py import requests import json from requests.exceptions import ConnectionError from django.http import JsonResponse, HttpResponse, Http404 from django.views.decorators.csrf import csrf_exempt from tworaven_apps.call_captures.models import ServiceCallEntry from tworaven_apps...
StarcoderdataPython
3225726
<filename>src/app/read_text_files.py import os import sys def get_path_to_input_files(): """Return absolute path of 'files' folder.""" try: path = os.getcwd() + "/app/files" # Relative path to working dir expected to contain input files except FileNotFoundError: print("Folder named 'files' ...
StarcoderdataPython
140585
<reponame>Stienvdh/statrick<filename>intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/arista/eos/plugins/modules/eos_bgp_global.py #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2020 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) #######...
StarcoderdataPython
3200611
from rohf import expmat from scipy.linalg.matfuncs import expm from numpy import zeros,identity,array n = 2 I = identity(n,'d') #A = zeros((n,n),'d') #A = I/3. #A = array([[-49,24],[-64,31]],'d') # Example from Moler/Van Loan, doesn't work #A = array([[0,0.5],[0.5,0]],'d') A = array([[1,0.5],[0.5,1]],'d') print A E ...
StarcoderdataPython
3302456
# Generated by Django 3.1 on 2020-08-29 02:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lesson_planner', '0034_auto_20200828_1857'), ] operations = [ migrations.RemoveField( model_name='series', name='start...
StarcoderdataPython