id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1750637
import torch import torch.nn as nn import string import os import time import random from torch.functional import Tensor from utils import Utils from recurrent_neural_network import RecurrentNeuralNetwork from typing import List, Tuple, Any class Program(): def __init__(self, learning_rate: float = 0.005, iterations...
StarcoderdataPython
161610
#!/usr/bin/env python3 # 2 srop version from pwn import * binary = context.binary = ELF('./some-really-ordinary-program') binary.symbols['main'] = 0x401022 binary.symbols['midread'] = 0x401006 if args.REMOTE: p = remote('challenge.nahamcon.com', 32629) else: p = process(binary.path) syscall = next(binary.search(...
StarcoderdataPython
122308
<gh_stars>0 from Model.Layer import Layer def create_model_vector_gru(output_length, output_features): model = [ Layer(layer_type='GRU', size=2 * output_features, return_sequences=True), Layer(layer_type='GRU', size=4 * output_features, return_sequences=False), Layer(layer_type='Dro...
StarcoderdataPython
189751
<gh_stars>100-1000 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. # system parameters class mn_DeviceType(models.Model): type_name = models.CharField(max_length=30) class mn_ServerGroup(models.Model): group_name = models.CharField(max_l...
StarcoderdataPython
4820046
house = float(input('Insert the value of the house: R$')) salary = float(input('Buyer salary: R$')) years_to_pay = int(input('How many years it will pay: ')) months = years_to_pay*12 # Converting years to months installments = house/months print('To afford a house of R${:.2f} in {} years the\n installment' 'will ...
StarcoderdataPython
68315
from pyramid.view import view_config from pyramid_oidc.interfaces import IOIDCUtility from ..models import RefreshToken @view_config(route_name='tokenstore_authorizations', renderer='json', request_method='GET', permission='view', cors=True) def authorizations(request): res = [] user_id = reque...
StarcoderdataPython
57492
from tornado import ioloop import time import requests import sys import requests import re s = time.time() maxRequestCount = 1000000000 i = 0 c = 0 # Takes destination ip as command line input if len(sys.argv) > 1: if re.match("^http", sys.argv[1]): ip = sys.argv[1] else: ip = "http://" + sy...
StarcoderdataPython
3391748
from flask import flash, redirect, request, render_template, url_for from flask_login import login_required, login_user, logout_user from datetime import datetime from . import auth from .forms import LoginForm, RegistrationForm from .. import db from ..models import User #global variables company_name = {'name' : 'La...
StarcoderdataPython
3238890
from typing import Optional from fastapi.encoders import jsonable_encoder from dispatch.project import service as project_service from .models import TagType, TagTypeCreate, TagTypeUpdate def get(*, db_session, tag_type_id: int) -> Optional[TagType]: """ Gets a tag type by its id. """ return db_sessi...
StarcoderdataPython
3381596
<filename>tests/torch_tests/unit/test_torch_data_loader.py<gh_stars>10-100 import pytest import numpy as np from tests.torch_tests.unit import BaseUnitTest, TORCH_AVAILABLE, fp class TestTorchDataLoader(BaseUnitTest): def test_pass(self, fp): from deeplite.profiler import Device fp.expecting_common...
StarcoderdataPython
96955
import re try: from importlib.resources import read_text except ImportError: from importlib_resources import read_text class Decompose: def __init__(self): self.entries = dict() self.super_entries = dict() for row in read_text('cjkradlib.data', 'cjk-decomp.txt').strip().split('\n...
StarcoderdataPython
3338794
""" Created on Tuesday 16 Feb 13:44:00 2021 The primary goal of this file is to demonstrate simple python program to classify triangles @author: <NAME> """ from typing import Set def classify_triangle(a, b, c): """ This function returns a string with the type of triangle from three integer values corr...
StarcoderdataPython
1795655
from typing import List from ConfigSpace import Configuration, ConfigurationSpace def sample_configurations(configuration_space: ConfigurationSpace, sample_size: int, historical_configs: List[Configuration], seed=1): configuration_space.seed(seed) result = [] sample_cnt = 0 i...
StarcoderdataPython
1745068
import os import logging log = logging.getLogger(__name__) from hootingyard.config.directories import get_archive_root from hootingyard.utils.generators import get_show_archives, extract_date, WEEKDAYS def main(warn_wednesday=False): archive_root: str = get_archive_root() filenames = set() for year, p...
StarcoderdataPython
4821166
import norsokm506_01 as ns v_sg=9 v_sl=1 mass_g=234.5 mass_L=542.3 vol_g=14.8 vol_l=637 vis_l=1.4 vis_g=0.03 roughness=0.00005 dia=0.475 temp=64 press=37.6 bicarbonate=800 ionstength=56 print(temp) kt=ns.Kt(temp) print(kt) v_sg=9 v_sl=1 mass_g=234.5 mass_l=542.3 vol_g=14.8 vol_l=637 vis_l=1.4 ...
StarcoderdataPython
59567
# coding: utf-8 from __future__ import absolute_import from flask import json from six import BytesIO from swagger_server.models.account_create_update import AccountCreateUpdate # noqa: E501 from swagger_server.models.account_definition import AccountDefinition # noqa: E501 from swagger_server.models.account_defin...
StarcoderdataPython
79685
<gh_stars>0 import unittest from os import path from random import choice from ga4stpg.graph import UGraph, UWGraph from ga4stpg.graph.algorithms import prim from ga4stpg.graph.reader import ReaderORLibrary from ga4stpg.graph.util import is_steiner_tree from ga4stpg.tree.evaluation import EvaluateTreeGraph fr...
StarcoderdataPython
1738574
from collections import Counter def handleCommonExcludeWords(synList, excludeWords, mostCommonCount=66, maxCommonCount=10, addAlphaBeta=False, addHyphenGene=False, removeSyn=None, minSynCount=0): synCounter = Counter() for synonym in synList: for syn in synonym: synCounter[syn] += 1 ...
StarcoderdataPython
3395488
import dtsa2 as dtsa2 import dtsa2.mcSimulate3 as mc3 def fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False): """ fullSimBulkStd(mat, det, e0, nTraj, outPath, dim=5.0e-6, lt=100, pc=1.0, emiSize=512, ctd=False) Use mc3 simulation to simulate an uncoated standa...
StarcoderdataPython
1624862
import sys import pickle import glob import subprocess import os import set_up print('[Grepper for FUNCTION]') if sys.argv[1]=='train': in_dir = set_up.train_folder_path elif sys.argv[1]=='test': in_dir = set_up.test_folder_path else: print('Unknown option') sys.exit() out_dir = set...
StarcoderdataPython
3389039
<filename>Bert/examples/IMDB_classifier/train.py # -*- coding: utf-8 -*- # # File: train.py # Author: SmileTM # Site: s-tm.cn # Github: https://github.com/SmileTM # Time: 07.06.2020 # import tensorflow as tf from Bert import tokenization from data_process import get_dataset from Bert import modeling from Bert import op...
StarcoderdataPython
3249414
from . import embedding from . import classifier from . import encoder from . import selector from . import coocurrence from . import selector2
StarcoderdataPython
4834912
# The MIT License (MIT) # # Copyright (C) 2016 - <NAME> <<EMAIL>> # # 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 limitation the rights # to use, copy...
StarcoderdataPython
180167
<gh_stars>0 from SudokuSolver import SudokuSolver from ImageDigitReader import ImageDigitReader class Main: image = ImageDigitReader() sudoku_board_img = image.get_sudoku_board() sudoku_board = [ [4, 1, 7, 0, 0, 0, 5, 0, 0], [5, 0, 0, 0, 6, 0, 4, 2, 0], [0, 6, 2, 0, 0, 0, 0, 0, 0...
StarcoderdataPython
1779643
from django.db import models from django.contrib.auth.models import User def upload_to(instance, filename): return '%s/%s/%s' % ('profile_photo', instance.user.username, filename) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE, verbose_name...
StarcoderdataPython
95261
class DungeonTile: def __init__(self, canvas_tile, is_obstacle): self.canvas_tile = canvas_tile self.is_obstacle = is_obstacle
StarcoderdataPython
25605
import os.path as osp from .reader.video_reader import VideoReader class ReaderFactory(): video_exts = [".mp4", ".avi", ".mov", ".MOV", ".mkv"] def create(target_input, target_fps): if osp.isfile(target_input): ext = osp.splitext(target_input)[1] if ext in ReaderFactory.video_...
StarcoderdataPython
3376665
from __future__ import absolute_import from datetime import timedelta from celery.schedules import crontab #BROKER_URL = "redis://10.1.9.9:6379" BROKER_URL = "redis://127.0.0.1:6379" #CELERY_RESULT_BACKEND = "redis://10.1.9.9:6379" CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379" CELERY_ENALBE_UTC = True CELERY_TIMEZO...
StarcoderdataPython
1623492
from guests.models import Guest def run(): usernames = set() duplicates_found = False for guest in Guest.objects.all(): if not guest.username: continue if guest.username in usernames: duplicates_found = True print(f'Duplicate username found: {guest.usern...
StarcoderdataPython
1632167
""" Issue: NOTE using Python 2.4, this results in an exe about 4Mb in size. NOTE using Python 2.6, this results in an exe about 5.5Mb in size. E:\Python24\python.exe p2_setup.py py2exe c:\python24\python p2_setup.py py2exe setup.py py2exe Quick-N-Dirty create win32 binaries and zip file script. Zero erro...
StarcoderdataPython
113932
<filename>fapm/__main__.py import hashlib import os import sys import jinja2 from . import cli from . import db from . import download from . import query from .constants import * def md5(value): return hashlib.md5(value.encode()).hexdigest() def pluralize(count, singular, plural=None): return f'{count:,}...
StarcoderdataPython
1627621
<filename>tests/conftest.py<gh_stars>1-10 import os from pathlib import Path import pytest NOTEBOOK_EXT = '.ipynb' ROOT_DIR = 'jupyter-notebooks' # do not look for notebooks in .ipynb_checkpoints dir SKIP_DIRECTORIES = ['.ipynb_checkpoints'] def pytest_addoption(parser): parser.addoption("--path", action="store...
StarcoderdataPython
35505
import numpy as np import pytest from src.models.noise_transformation import average_true_var_real, average_true_var_imag, average_true_cov, \ average_true_noise_covariance, naive_noise_covariance test_cases_real_variance = [ (2 - 3j, 0, 0, 0), (0, 1, 1, np.exp(-2) * (2 * np.cosh(2) - np.cosh(1))), (2...
StarcoderdataPython
1769415
from operator import gt, lt, eq from math import prod from aoc20211216a import * OPS = { 0: lambda *a: sum(a), 1: lambda *a: prod(a), 2: lambda *a: min(a), 3: lambda *a: max(a), 5: gt, 6: lt, 7: eq, } def compute(ver, op, sub, length): return ( ver, op, OPS[op]...
StarcoderdataPython
1727348
#!/usr/bin/python from HAT import IAQ_DAC43608 from HAT import IAQ_Mux from Sensors.IAQ_Sensor import SensorIdEnum from third_party import Adafruit_ADS1x15 import time class AnalogPortController: adc = None dac = None mux = None ######################################### # Store the port that ADC is...
StarcoderdataPython
45097
<gh_stars>10-100 def get_gene_ne(global_variables,gene_dictionary): values_list = [] # gets the ordered samples sample_list = global_variables["sample_list"] for sample in sample_list: values_list.append(gene_dictionary[sample]) return values_list
StarcoderdataPython
1746995
<reponame>YunWGui/LeetCode # !/usr/bin/env python # -*- coding:utf-8 -*- """ Created on Thu Sep 26 21:19:51 2019 @author: <NAME> """ """ Title; 26. Remove Duplicates from Sorted Array 26. 删除排序数组的重复项 Address: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ """ # 方法一: class Solution: def ...
StarcoderdataPython
156702
import torch.utils.data as data from torchvision import transforms from PIL import Image import os import os.path from .auto_augment import AutoAugment, ImageNetAutoAugment IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] def is_image_file(filename): ...
StarcoderdataPython
1609637
import glob import os __all__ = [os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__) + "/*.py")]
StarcoderdataPython
1669247
<gh_stars>0 #!/usr/bin/env python """ Check rabbit for connections older than <time> Usage: rabbit-check-connections.py (-e host) [-h] [-d] [-p port] [-t time] (-u username) (-x password) [--version] Options: -e <host> R...
StarcoderdataPython
148191
from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) door = "closed" passwords = set() class PassWord(Resource): def get(self): global passwords return { "result": "OK", "passwords": list(passwords) } ...
StarcoderdataPython
3269807
""" A set of helper functions that have no other home. """ from math import degrees, radians, pi, sqrt, cos, sin import numpy def centerOfMass(positions, weights): """ Calculate the center of mass of a set of weighted positions. Args: positions: A list of (x,y,z) position tuples weights: A list of pos...
StarcoderdataPython
50253
from problems.fizz_buzz import FizzBuzz def test_fizz_buzz(): output = FizzBuzz.compute() assert output == ['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz', '13', '14', 'fizzbuzz', '16', '17', 'fizz', '19', 'buzz', 'fizz', '22', '23', 'fizz', 'buzz', '26', ...
StarcoderdataPython
3334762
#!/usr/bin/python # -*- coding: utf-8 -*- # Get basic statistics describing the database # Compare a structure to a database from tqdm.autonotebook import tqdm import logging from pymatgen import Structure from pymatgen.analysis.graphs import StructureGraph from pymatgen.analysis.local_env import JmolNN from .utils i...
StarcoderdataPython
3276401
<reponame>anondax/Discord-copy-bot from model.GuildChannelModel import * class TextChannelModel(GuildChannelModel): def __init__(self): GuildChannelModel.__init__(self); self.nsfw = None; self.topic = None; self.slowmode_delay = None; def fillFromChannel(self, channel): ...
StarcoderdataPython
1651068
<reponame>TheoKanning/advent-of-code<filename>2020/2.py with open("inputs/2.txt") as f: input = f.readlines() total_valid = 0 for entry in input: rule, password = entry.split(':') bounds, letter = rule.split(' ') lower_bound, upper_bound = bounds.split('-') if int(lower_bound) <= password.count(l...
StarcoderdataPython
3354243
# Copyright 2014 OpenStack Foundation # 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 applica...
StarcoderdataPython
1611370
import resnet2 as net import numpy as np import cv2 import scipy.io as sio import os from os import listdir import random def Average(inp): a = inp/np.linalg.norm(inp, axis=1, keepdims=True) a = np.sum(a, axis=0) a = a/np.linalg.norm(a) return a path = r'O:\[FY2017]\MS-Challenges\code\evaluation_a...
StarcoderdataPython
198375
<filename>examples/flask/htdocs/main.py """ # Python Flask # http://flask.pocoo.org/docs/1.0/quickstart/#quickstart # Code from # @see Rapid Flask [Video], PacktLib # --- # @see Learning Flask Framework # @see ... # run app server with "python routes.py" # open browser at "localhost:5000" # open browser at "localho...
StarcoderdataPython
75601
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import itertools imp...
StarcoderdataPython
4829356
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
StarcoderdataPython
67490
<gh_stars>1-10 # next is to add accel and see the difference # add stiffness too import tensorflow as tf import numpy as np from scipy import signal, stats from matplotlib import pyplot as plt from all_functions import * import pickle from warnings import simplefilter import matplotlib matplotlib.rcParams['pdf.fontty...
StarcoderdataPython
3214621
<filename>client/commands/v2/language_server_protocol.py<gh_stars>0 # 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 asyncio import dataclasses import enum from typing import List, Ite...
StarcoderdataPython
78180
# -*- coding: utf-8 -*- """ Created on Wed May 27 20:06:01 2015 @author: Thomas """ # Python standard library imports import csv import os def main(): generated = [] for file in os.listdir("reformatted/"): print 'getting data from.. ' + file generate_total = [] generate_2000...
StarcoderdataPython
153293
<filename>research/nets/common.py import sys from collections import defaultdict import numpy as np from torch.utils.tensorboard import SummaryWriter import matplotlib.pyplot as plt import torch as torchvision from torch.optim import Adam from itertools import chain, count import torch as th from torch import distribu...
StarcoderdataPython
3267676
""" mapMotifValidation.py This module runs map versus amino acid residues map motif library validation. Copyright [2013] EMBL - European Bioinformatics Institute 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 th...
StarcoderdataPython
3308231
import tempfile from dagger.dag import DAG from dagger.input import FromNodeOutput, FromParam from dagger.output import FromReturnValue from dagger.runtime.local.invoke import StoreSerializedOutputsInPath, invoke from dagger.task import Task def test__invoke__without_parameters(): dag = DAG( nodes=dict( ...
StarcoderdataPython
1664552
<reponame>CTPUG/pyntnclick # speech.py # Copyright Boomslang team, 2010 (see COPYING File) # Speech playing and cache import re from .sound import get_sound # cache of string -> sound object mappings _SPEECH_CACHE = {} # characters not to allow in filenames _REPLACE_RE = re.compile(r"[^a-z0-9-]+") class SpeechEr...
StarcoderdataPython
1635569
from . import app from flask import make_response, request, render_template from .models.route_service import RouteService from .models.route_data import RouteData manager = RouteService() @app.route('/routes', methods=['GET']) def all_routes(): response_payload = { "routes": manager.all_raw_routes() } return...
StarcoderdataPython
61570
from typing import List, Set from querio.db import data_accessor as da from querio.ml import model from querio.service.save_service import SaveService from querio.ml.expression.cond import Cond from querio.ml.expression.expression import Expression from querio.queryobject import QueryObject from querio.service.utils i...
StarcoderdataPython
20350
<gh_stars>0 #!/usr/bin/python import sensor import lcd import csv import time import os import datetime import sys import re import circular_buffer lcd.init() last_time = datetime.datetime.now() last_minute = last_time.minute probe_minute_01 = circular_buffer.CircularBuffer(size=30) probe_minute_15 = circular_buffe...
StarcoderdataPython
3394278
# -*- coding: utf-8 -*- import os import time import argparse import json import copy import yaml import pandas as pd from tqdm import tqdm from sklearn.metrics import precision_recall_curve, roc_auc_score,\ average_precision_score def create_parser(): # SET THE PARAMETERS parser = argparse.ArgumentParser(...
StarcoderdataPython
1639110
from setuptools import setup setup( name="pipe_helper", version="0.0.1", description="Simple helper for common functionality", author="<NAME>, LUMC", author_email="<EMAIL>", url="https://github.com/lumc-pgx/pipe-helper", license="MIT", platforms=['linux'], packages=["pipe_helper"], ...
StarcoderdataPython
6940
<reponame>snake-biscuits/io_import_rbsp # by MrSteyk & Dogecore # TODO: extraction instructions & testing import json import os.path from typing import List import bpy loaded_materials = {} MATERIAL_LOAD_PATH = "" # put your path here # normal has special logic MATERIAL_INPUT_LINKING = { "color": "Base Color"...
StarcoderdataPython
3221212
<gh_stars>0 from oarepo_model_builder.builders import process from oarepo_model_builder.builders.python import PythonBuilder from oarepo_model_builder.builders.utils import ensure_parent_modules from oarepo_model_builder.stack import ModelBuilderStack class PythonStructureBuilder(PythonBuilder): TYPE = 'python_st...
StarcoderdataPython
3293920
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class MainRo...
StarcoderdataPython
1653120
#!/usr/bin/env python # coding: utf-8 import datetime import nltk from operator import add from pprint import pprint from random import random, uniform import rospy from std_msgs.msg import String import os import csv #nltk.download('punkt') object_ = ['chip', 'senbei', 'pringles', 'peanut', 'candy', 'chewing g...
StarcoderdataPython
126893
<filename>Exercises/iterations.py """while loops, also known as indefinite loops""" # n = 5 # while n > 0: # print(n) # n = n - 1 # print('Blastoff') # print(n) # breaking out of loops # while True: # line = input('> ') # if line == 'done': # break #ends loop and jumps to the end of the code # p...
StarcoderdataPython
3237997
import unittest from Rectangle import * class MyTestCase(unittest.TestCase): def test_something(self): p1 = mak_vec(1, 2) p2 = mak_vec(3, 4) p3 = mak_vec(5, 6) p4 = mak_vec(7, 8) r = mak_rect(mak_vec(0, 0), mak_seg(0, 4), mak_seg(5, 0)) g = mak_picture([mak_seg(p1, ...
StarcoderdataPython
3260323
from rest_framework import serializers from .models import Search, SearchResult class SearchResultSerializer(serializers.ModelSerializer): class Meta: model = SearchResult fields = '__all__' class SearchSerializer(serializers.ModelSerializer): class Meta: model = Search field...
StarcoderdataPython
3317440
<reponame>lahdjirayhan/drive-kesma-library-linker # pylint: disable=wrong-import-position, import-outside-toplevel import logging logging.basicConfig(level=logging.WARNING) from decouple import config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_talisma...
StarcoderdataPython
3365684
# -*-coding:utf-8-*- import numpy as np # PADDING MODE PADDING_SAME = 0 # 与输出一致 PADDING_VALID = 1 # 不做对齐补充 会有损失 # POOLING MODE POOLING_MAX = 0 # 最大 POOLING_AVG = 1 # 平均 POOLING_ECHO = 2 # 原样返回 # 2维卷积 # matrix的层数与filters层数一致 # matrix 单个正方形图层通道 # filters 过滤器集合 可以多个过滤器 # bias 偏移量 集合 # stride filter 移动步长 # pad...
StarcoderdataPython
1693215
<reponame>emirkmo/astropy # Licensed under a 3-clause BSD style license - see LICENSE.rst import os from collections import defaultdict from os.path import join from extension_helpers import import_file from setuptools import Extension # This defines the set of projection functions that we want to wrap. # The key is...
StarcoderdataPython
144742
<filename>invest_natcap/fisheries/fisheries_hst_io.py<gh_stars>0 ''' The Fisheries Habitat Scenarios Tool IO module contains functions for handling inputs and outputs ''' import logging import os import csv import pprint as pp import copy import numpy as np LOGGER = logging.getLogger('invest_natcap.fisheries.hst_io'...
StarcoderdataPython
4813348
def find_min_delta(amount): dot_ind = amount.find(".") if dot_ind < 0: return 1.0 float_len = len(amount) - dot_ind - 1 if float_len <= 0: return 1.0 return float("0." + "0" * (float_len - 1) + "1")
StarcoderdataPython
1753250
# -*- coding: utf-8 -*- """ Copyright 2017-2018 <NAME>. 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 ...
StarcoderdataPython
3378810
import unittest import jsonasobj class ExtendedNamespaceTestCase(unittest.TestCase): """ ExtendedNamespace is a dictionary / namespace combination. Any valid python identifiers are also available as first class members. """ def test_extendednamespace(self) -> None: # Direct constructor ...
StarcoderdataPython
3348077
import json from django.contrib.auth.models import Group from rest_framework import authentication, permissions, serializers, viewsets from exampleapp.models import Author, Comment, Post, Tag from . import filters def update_instance(instance, validated_data): for attr, value in validated_data.items(): ...
StarcoderdataPython
1713762
import pandas as pd from matplotlib import pyplot as plt sample_data = pd.read_csv('C:\\Users\\nikhi\\Desktop\\Data Visualization\\sample_data.csv') plt.xlabel = ("No Idea") plt.ylabel = ("Who KNOWS,seriously!") plt.title = ("Something of Something") plt.plot(sample_data.column_a, sample_data.column_b, 'o') plt.plot(s...
StarcoderdataPython
3249380
# -*- coding: utf-8 -*- # 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, softw...
StarcoderdataPython
3374388
""" This file is public domain, it can be freely copied without restrictions. SPDX-License-Identifier: CC0-1.0 Top Level Wakey-Wakey Testbench """ import sys sys.path.append('../../../py/') import numpy_arch as na import pdm import aco sys.path.append('../../../test/pdm_capture_test/py/') import parse_mic_data impo...
StarcoderdataPython
42496
import gzip import logging import logging.handlers import os from cStringIO import StringIO as IO from spreads.vendor.huey import SqliteHuey from spreads.vendor.huey.consumer import Consumer from spreads.vendor.pathlib import Path from flask import Flask, request from spreads.plugin import (HookPlugin, SubcommandHook...
StarcoderdataPython
4818850
from django.urls import path from .views import ( BlockchainCreateView, BlockchainDeleteView, BlockchainDetailView, BlockchainListView, BlockchainUpdateView, ) app_name = "blockchain" urlpatterns = [ path("", BlockchainListView.as_view(), name="blockchain_list"), path("add/", BlockchainCre...
StarcoderdataPython
3346433
"""A library for decoding HTML fetched from the web into Unicode. Uses BeautifulSoup4.UnicodeDammit internally. It, in turn, uses the 'chardet' module internally if it is available, which is recommended. It is highly recommended to use the HTTP response headers if they are available, since often the correct encoding ...
StarcoderdataPython
1762216
<reponame>PeerXu/fysom3 # coding=utf-8 # # fysom - pYthOn Finite State Machine - this is a port of Jake # Gordon's javascript-state-machine to python # https://github.com/jakesgordon/javascript-state-machine # # Copyright (C) 2011 <NAME> <<EMAIL>>, <NAME> # and oth...
StarcoderdataPython
4818979
import click @click.command('migrate', short_help='exec migrate') @click.option('--database', '-d', help='the database connection to use.') @click.option('--path', '-p', help='the path of migration files') def migrate(database, path): if not click.confirm( 'Are you sure you...
StarcoderdataPython
1762570
<reponame>594422814/ContrastCorr import copy import torch import torch.nn as nn import torch.nn.functional as F from libs.net_utils import NLM_NC_woSoft from libs.utils import * from libs.autoencoder import encoder3, decoder3, encoder_res18, encoder_res50 import pdb class NLM_woSoft(nn.Module): """ Non-local mean ...
StarcoderdataPython
3223461
<reponame>lilies/Cirq # Copyright 2018 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
StarcoderdataPython
1699681
<reponame>dmorand17/csv_utils from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() with open('requirements.txt') as f: requirements = [req for req in f.read().splitlines() if not req.startswith('#')] setup( name='csv...
StarcoderdataPython
3325354
from pwn import * breakAddress = 0x004006dd # Address with compare instruction targetRegister = '$rdx' # Value that we want to identify breakCommand = '''set logging file russian.log set logging on break *{} command 1 # Commenting silent out breaks output (print statements do not display) silent print {...
StarcoderdataPython
3204382
import argparse def parse_args(args): """ Parse the arguments. """ parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.') subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type') subparsers.required =...
StarcoderdataPython
1719269
# Copyright 2021 Open Collector, Inc, # # 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 limitation the rights # to use, copy, modify, merge, publish, d...
StarcoderdataPython
3299291
<reponame>iamfaith/DeepLearning<filename>books/PRML/PRML-master-Python/prml/nn/linalg/logdet.py<gh_stars>1000+ import numpy as np from prml.nn.tensor.constant import Constant from prml.nn.tensor.tensor import Tensor from prml.nn.function import Function class LogDeterminant(Function): def forward(self, x): ...
StarcoderdataPython
3214262
from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty from kivy.uix.popup import Popup from kivy.uix.button import Button from os.path import join, isdir import frontur_utilities.utility_fileloader as df_fileloader class SaveDialog(FloatLayout): save = ObjectProperty(None) tex...
StarcoderdataPython
4831793
"""Calculates erosion rate as a function of the depth-slope product Erosion rate = k_e * ((Tau**a - Tau_crit**a)) k_e = erodibility coefficient Tau = bed shear stress = density of fluid (rho) * gravitational acceleration (g) * water depths (h) * slopes (S) Tau_crit = critical shear stress a = positive exponent ...
StarcoderdataPython
193248
from bs4 import BeautifulSoup from sys import argv import requests, urllib query = argv[1] headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} if len(argv) == 3: version = argv[2] url = 'http://www.biblegateway.co...
StarcoderdataPython
1688197
<reponame>PwC-FaST/fast-webapp # Generated by Django 2.1.2 on 2019-01-02 16:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('core', '0001_initial'), ('farming', '0001_initial'), ] o...
StarcoderdataPython
181120
#!/usr/bin/python import uuid import os import sys import glob import json import ldap ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) ces_dir = os.path.join('/tmp', str(uuid.uuid4()).split('-')[0]) ces_zip = '/opt/dist/gluu/community-edition-setup.zip' cmd = 'unzip -q {} -d {}'.format(ces_zip, ce...
StarcoderdataPython
82072
#!/usr/bin/env python3 from argparse import ArgumentParser import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import to_hex def main(args): cmap = plt.get_cmap(args.cmap) for x in np.linspace(0, 1, num=args.n_colors): print(to_hex(cmap(x), keep_alpha=False)) if __name__ == '...
StarcoderdataPython
41101
"""Console script for r_freeze.""" import argparse import sys from r_freeze.r_freeze import get_packages, write_package_file def main(): """Console script for r_freeze.""" parser = argparse.ArgumentParser() parser.add_argument("dir", type=str, help="Directory to look for") parser.add_argument( ...
StarcoderdataPython