id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
6645742
<filename>scripts/er_unmatched_test.py<gh_stars>0 #%% [markdown] # # A density-based test # Here, we compare the two unmatched networks by treating each as an Erdos-Renyi network # and simply compare their estimated densities. #%% [markdown] # ## The Erdos-Renyi (ER) model # The [**Erdos-Renyi (ER) model** # ](https:/...
StarcoderdataPython
3396154
import openmc_source_plotter as osp import openmc # initialises a new source object my_source = openmc.Source() # sets the location of the source to x=0 y=0 z=0 my_source.space = openmc.stats.Point((0, 0, 0)) # sets the direction to isotropic my_source.angle = openmc.stats.Isotropic() # sets the energy distribution...
StarcoderdataPython
1920799
from django.contrib import admin from .models import GamebeaterProfile, GameOwnership admin.site.register(GamebeaterProfile) admin.site.register(GameOwnership)
StarcoderdataPython
102295
import sys, json, os, subprocess as sp, getpass, logging, argparse from pathlib import Path import paramiko # silence deprecation warnings # https://github.com/paramiko/paramiko/issues/1386 import warnings warnings.filterwarnings(action='ignore',module='.*paramiko.*') logger = logging.getLogger() logger.setLevel(log...
StarcoderdataPython
398201
<filename>license.py import sys import datetime if len(sys.argv) != 3: print >>sys.stderr, 'Usage: license.py version_num filename' version = sys.argv[1] year = datetime.date.today().year s = """\ LICENSE AGREEMENT FOR MATPLOTLIB %(version)s -------------------------------------- 1. This LICENSE AGREEMENT is be...
StarcoderdataPython
337947
<filename>example.py<gh_stars>100-1000 from pretrained.cifar100 import cifar100 model = cifar100(model='resnet18') model.test() # model.test('....test') # model.train('...train)
StarcoderdataPython
3295042
"""LinePredictor class""" from typing import Tuple, Union import numpy as np from text_recognizer.models import LineModelCtc from text_recognizer.datasets import EmnistLinesDataset import text_recognizer.util as util class LinePredictor: """Given an image of a line of handwritten text, recognizes text contents....
StarcoderdataPython
11328255
#!/usr/bin/env python """ for block as a family example """ import ecf as ecflow from ecf import (Family, Task, Inlimit, Label, Limit, Repeat, Edit) PARAMS = ["u", "v", "t", "r", "q", "w"] def process(): """ provide leaf task """ return Task("process") def family_for(): """ for family """ return ( ...
StarcoderdataPython
3572766
import utils def main(): """Main.""" hex1 = '1c0111001f010100061a024b53535009181c' hex2 = '686974207468652062756c6c277320657965' hex3 = '746865206b696420646f6e277420706c6179' xor = utils.xor(bytearray.fromhex(hex1), bytearray.fromhex(hex2)) assert ''.join([chr(c).encode('hex') for c in xor]) =...
StarcoderdataPython
3261411
with open("./datas/lsjz/005161.csv", encoding="utf-8") as f: print(len(f.readlines()))
StarcoderdataPython
9771969
import bs4 as bs import pickle import requests import datetime as dt import os import pandas as pd import pandas_datareader.data as web import matplotlib.pyplot as plt from matplotlib import style #from mplfinance import candlestick_ohlc from mplfinance.original_flavor import candlestick_ohlc import matplotlib.dates a...
StarcoderdataPython
4841713
<filename>transform_binary_payload/src-payload-decoders/python/dragino_lwl01.py<gh_stars>1-10 import base64 def dict_from_payload(base64_input: str, fport: int = None): """ Decodes a base64-encoded binary payload into JSON. Parameters ---------- base64_input : str ...
StarcoderdataPython
3368013
""" collections.Counter() A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values. Sample Code >>> from collections import Counter >>> >>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3] >>> print Counter(myList) Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) >>> >>> print C...
StarcoderdataPython
1755005
<reponame>StevenHuang2020/ML #python3 #steven 04/03/2020 import matplotlib.pyplot as plt import numpy as np gAlpha = 100 def setPlot(): plt.xticks(np.linspace(0,10,15)) plt.yticks(np.linspace(-4000,4000,15)) def plotXY(x,y): plt.plot(x,y) #plt.show() def getTreeBranch(startPt,slope): drawLen = 1...
StarcoderdataPython
6567628
import unittest from pathlib import Path from pangtreebuild.pangenome import graph from pangtreebuild.pangenome.builders import maf2poagraph from pangtreebuild.pangenome.parameters import msa from pangtreebuild.tools import pathtools def nid(x): return graph.NodeID(x) def bid(x): return graph.BlockID(x) class Ma...
StarcoderdataPython
1941243
from unittest import TestCase from slackbot.owners import CarOwners import os TEST_CSV = os.path.join(os.path.dirname(__file__), 'dummy_owners.csv') class TestCarOwners(TestCase): @classmethod def setUpClass(cls): # Make a new file each time with open(TEST_CSV, 'w') as f: f.write...
StarcoderdataPython
7392
import django_filters from django.forms import TextInput from src.accounts.models import User from src.application.models import Quiz, StudentGrade class UserFilter(django_filters.FilterSet): username = django_filters.CharFilter(widget=TextInput(attrs={'placeholder': 'username'}), lookup_expr='icontains') fi...
StarcoderdataPython
149991
<filename>apps/core/views.py from django.views.generic import TemplateView from directory.models import Organisation from resources.models import Resource from .mixins import ResourcesViewMixin class HomeView(TemplateView, ResourcesViewMixin): template_name = 'core/home.html' def get_context_data(self, **k...
StarcoderdataPython
9688080
<filename>otcextensions/tests/unit/osclient/vpc/v2/test_peering.py<gh_stars>1-10 # 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 r...
StarcoderdataPython
362382
#!/usr/bin/env python3 import numpy as np from argparse import ArgumentParser from math import inf from os import fstat from sklearn.linear_model import LinearRegression from tqdm import tqdm, trange # Argparse initializations argument_parser = ArgumentParser(description = 'Molecular Dynamics Residence Time') argume...
StarcoderdataPython
1866043
# Copyright (c) 2021 MIT # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES ...
StarcoderdataPython
173360
<filename>medium/python/c0355_777_swap-adjacent-in-lr-string/00_leetcode_0355.py # DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #777. Swap Adjacent in LR String #In a string composed of 'L', 'R', and '...
StarcoderdataPython
8040410
<reponame>filmceadmin/VideoSesDonustur<filename>bot/translation.py class Translation(object): DOWNLOAD_PROGRESS = "`█`" UPLOAD_PROGRESS = "`░`" START_TEXT = """Merhaba {0}\nŞimdi bana sesi olmayan bir video gönder. 👉 @hextr""" PROGRESS = """` Yüzde : {0}% Tamamlanan: {1} Toplam...
StarcoderdataPython
8127625
<filename>mayhem/datatypes/common.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # # mayhem/datatypes/structure.py # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code...
StarcoderdataPython
1723535
<reponame>saurabh896/python-1 from PIL import Image,ImageDraw,ImageFont im = Image.open("pic.jpg") x,y = im.size font = ImageFont.truetype("verdana.ttf", x/3) dr = ImageDraw.Draw(im) dr.text((3*x/4,0),font=font,text="4",fill="#FF0000") im.save("pictuer_has_number.jpg")
StarcoderdataPython
366500
from collections.abc import Iterable from virtualbox.exceptions import NoSuchIndex # Wrappers def restrictRange(min, max, keyword): def decorator(function): def check(*args, **kwargs): if min <= kwargs[keyword] < max: return function(*args, **kwargs) raise NoSuchI...
StarcoderdataPython
5072777
from typing import * import argparse import sys import os.path import dataclasses import json @dataclasses.dataclass class DurationEvent: name: str timestep: float duration: float @staticmethod def from_json(jobj: Mapping): return DurationEvent(jobj['name'], jobj['ts'], jobj['dur']) @data...
StarcoderdataPython
3221228
#!/usr/bin/env python3 @app.route('/api/v1/insert_weight', methods=['GET']) def insert_weight_v1(): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor) cur.execute("""INSERT INTO weights...
StarcoderdataPython
6463465
<reponame>pragneshrana/Reinforcement-Learning from gym import Env from gym.envs.registration import register from gym.utils import seeding from gym import spaces import numpy as np from math import sqrt class chakra(Env): metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_secon...
StarcoderdataPython
1986956
<filename>scripts/insert-copyright-header.py #!/usr/bin/env python # Copyright (c) 2014 Azavea. # # 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...
StarcoderdataPython
1959603
from django.contrib import admin from .models import Member, Post, Comment, CreditCard, Filter, Image # Register your models here. admin.site.register(Member) admin.site.register(Post) admin.site.register(Comment) admin.site.register(CreditCard) admin.site.register(Filter) admin.site.register(Image)
StarcoderdataPython
11228234
import os import sys from inspect import signature from os.path import abspath, dirname, relpath import pandas as pd from aaai20.utils import debug_print, run_script VERBOSITY = 0 def main(csv_fname, cmd_idx): """ Run single command from csv file that specifies many commands. The command that should be...
StarcoderdataPython
3347221
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2017-12-25 14:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20170105_...
StarcoderdataPython
3353524
from __future__ import absolute_import, print_function, unicode_literals from flask import ( Flask, make_response, jsonify, request, render_template, send_from_directory, abort, redirect, ) from flask_cors import CORS from JavPy.functions import Functions import json import os from JavPy...
StarcoderdataPython
11364940
<reponame>gaborbernat/toxn import logging import os from contextlib import contextmanager from pathlib import Path from typing import Any, Dict, Generator, List, Tuple from toxn.config.models.task.base import TaskConfig from toxn.config.models.venv import Install from toxn.util import Loggers def install_params(batc...
StarcoderdataPython
11343512
<gh_stars>0 #capitalize function --- first letter in uppercase s1 = "indian brave soldiers..." print(s1) # -- CA1 print(s1.capitalize()) # -- CA2 s2 = 'India' print(s2.capitalize()) # -- CA3 s3 = '31 is my age' print(s3.capitalize()) # -- CA4
StarcoderdataPython
5064298
from cms.app_base import CMSAppConfig from djangocms_versioning.datastructures import VersionableItem from .models import App2PostContent, App2TitleContent class CMSApp1Config(CMSAppConfig): djangocms_moderation_enabled = True djangocms_versioning_enabled = True moderated_models = (App2PostContent, App2...
StarcoderdataPython
6447526
<reponame>dikien/Machine-Learning-Newspaper # -*- coding: UTF-8 -*- from time import time from step3_feature_engineering import preprocess_2 from sklearn.svm import SVC from sklearn.cross_validation import cross_val_score, KFold from sklearn import grid_search features, labels, vectorizer, selector, le = preprocess_2...
StarcoderdataPython
328714
<filename>migrations/versions/5f3ea30d645d_initial_migration.py """Initial Migration Revision ID: 5<PASSWORD>d Revises: <PASSWORD> Create Date: 2019-12-02 18:49:02.495171 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = '<PASSWORD>' ...
StarcoderdataPython
9652237
# ____ # ####################-=|NOTE|=-###################### #U SHOULD INPUT YOUR E-MAIL AND PASSWORD TO <PASSWORD># #THIS IS FOR NORMAL DISCORD USERS... # #Programmed By Cylops. (Lyceion) # ####################################################...
StarcoderdataPython
11309182
<reponame>WarwickAnimeSoc/aniMango # Generated by Django 2.2.13 on 2020-09-15 16:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stream', '0001_initial'), ] operations = [ migrations.AddField( model_name='viewcounter', ...
StarcoderdataPython
5142502
import torch import torch.nn as nn from ..model import BaseMuZeroNet class MuZeroNet(BaseMuZeroNet): def __init__(self, input_size, action_space_n, reward_support_size, value_support_size, inverse_value_transform, inverse_reward_transform): super(MuZeroNet, self).__init__(inverse_value_tr...
StarcoderdataPython
1937792
<reponame>NeonOcean/Environment from _collections import defaultdict from _weakrefset import WeakSet from collections import namedtuple from alarms import add_alarm_real_time, cancel_alarm, add_alarm from clock import interval_in_real_seconds from indexed_manager import CallbackTypes from routing.route_enums import Rou...
StarcoderdataPython
252396
<filename>seth/crypto.py import struct import hashlib import subprocess import re from binascii import hexlify, unhexlify from seth.args import args, hexdump from seth.consts import TERM_PRIV_KEY class RC4(object): def __init__(self, key): x = 0 self.sbox = list(range(256)) for i in range(...
StarcoderdataPython
1636718
import pandas as pd dados = pd.read_csv('/home/laumzav/PycharmProjects/Python_study/AlCuOn/Pandas/aluguel.csv', sep=';') dados.head(10) dados.dtypes tipos = list(dados['Tipo'].drop_duplicates()) residencial = ['Quitinete', 'Casa', 'Apartamento', 'Casa de Condomínio', 'Flat', 'Casa de Vila', 'Loft'] dados['Residencial'...
StarcoderdataPython
4833288
# global import abc from typing import Optional, Union # local import ivy class ArrayWithLosses(abc.ABC): def cross_entropy( self: ivy.Array, pred: Union[ivy.Array, ivy.NativeArray], axis: Optional[int] = -1, epsilon: Optional[float] = 1e-7, *, out: Optional[ivy.Ar...
StarcoderdataPython
1839262
################################################################################################################### # # A P I B L U E P R I N T # # THIS IS THE BUSINESS LOGIC BLUEPRINT PACKAGED # ################################################################################################################### from ...
StarcoderdataPython
1714411
<reponame>Eszti/tuw-nlp import datetime import json import sys import traceback import graphviz import stanza from flask import Flask, request from graphviz import Source import networkx as nx from networkx.readwrite import json_graph from tuw_nlp.grammar.text_to_4lang import TextTo4lang from tuw_nlp.graph.fourlang im...
StarcoderdataPython
368525
<reponame>imperial-genomics-facility/IGFPortal import typing import logging from typing import Tuple, Any from .. import db from ..models import RawSeqrun, SampleSheetModel def fetch_samplesheet_for_seqrun(seqrun_id: str) -> Any: try: result = \ db.session.\ query( ...
StarcoderdataPython
6643035
""" 推理文件 """ # Copyright 2021 Huawei Technologies Co., Ltd # # 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 la...
StarcoderdataPython
1831697
from pymongo import MongoClient client = MongoClient("localhost", 27017) gobDb = client["GoBDB"] jobCollection = gobDb["Jobs"] categories = jobCollection.aggregate([ { '$project': { 'category': '$attributes.category_name', 'title': '$attributes.title' } } ]) print(list...
StarcoderdataPython
200348
import sys environment = sys.argv[1] region_name = sys.argv[2] app_code = sys.argv[3] version = sys.argv[4] def regionCode(region_name): return f"{region_name[0:1]}{region_name[-1:]}" def resourceEnv(app_code, version, env): return f"{app_code}-env{version}-{env}" def resourceEnvCompact(app_code, version, e...
StarcoderdataPython
6450848
<reponame>microsoft/SpeedyRec # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import time import logging import random import torch from tqdm.auto import tqdm import torch.optim as optim import sys, traceback from torch.nn.parallel import DistributedDataParallel as DDP import torch.d...
StarcoderdataPython
1746827
"""Deep Pictorial Gaze architecture.""" from typing import Dict import numpy as np import scipy import tensorflow as tf from core import BaseDataSource, BaseModel from datasources import UnityEyes import util.gaze class DPG(BaseModel): """Deep Pictorial Gaze architecture as introduced in [Park et al. ECCV'18]."...
StarcoderdataPython
12864554
<reponame>CONABIO-audio/irekua-dev-tools<gh_stars>0 import click from irekua_dev_tools.utils import load_config from irekua_dev_tools.utils import get_working_directory from irekua_dev_tools.utils import load_environment_variables from irekua_dev_tools.utils import load_repository_info from . import git from . import...
StarcoderdataPython
3360451
# -*- coding: utf-8 -*- # Copyright (c) 2019, Aptitude technologie and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe import _ from frappe.model.rename_doc import rename_doc from shei.shei.docty...
StarcoderdataPython
6659543
import logging from kismetclient.utils import csv from kismetclient.exceptions import ServerError log = logging.getLogger(__name__) def kismet(client, version, starttime, servername, dumpfiles, uid): """ Handle server startup string. """ log.info('Server: ' + ' '.join([version, starttime, serve...
StarcoderdataPython
5149913
<gh_stars>0 from . import RequestOptions from . import Sort class Pager(object): """ Generator that takes an endpoint (top level endpoints with `.get)` and lazily loads items from Server. Supports all `RequestOptions` including starting on any page. Also used by models to load sub-models (users in a g...
StarcoderdataPython
5181133
<reponame>he134543/XLake import pandas as pd import numpy as np from glob import glob def Net_Loading(inflows_path, outflows_path): # inflows_path = 'Inflows' g_inflow_path = inflows_path + '/*.csv' g_outflow_path = outflows_path + '/*.csv' inflows_names = glob(g_inflow_path) outflows_names = ...
StarcoderdataPython
3283385
import sys from typing import List, Union import numpy as np import _robustats def weighted_median( x: Union[List[float], np.ndarray], weights: Union[List[float], np.ndarray] ) -> float: """Calculate the weighted median of an array with related weights. For arrays with an even number of ele...
StarcoderdataPython
8004561
<filename>magic_method.py<gh_stars>1-10 """class People: def __init__(self, name, age): self.name = name self.age = age def __del__(self): print("deleted") person = People("james", 25) """ class Square: def __init__(self, side1, side2): self.side1 = side1 self....
StarcoderdataPython
8161170
import jiminy.api class ModelCreator(jiminy.api.Creator): """Polygonal geometry""" name = "modelDefault" label = "Model" family = "tailcoat.model" icon = "cubes"
StarcoderdataPython
6576557
""" Custom component to integrate with OctoPrint. For more details about this component, please refer to https://github.com/fredrikbaberg/octoprint_hass """ import os from datetime import timedelta import logging import voluptuous as vol from homeassistant import config_entries import homeassistant.helpers....
StarcoderdataPython
23109
<reponame>tallywiesenberg/dating-data-dividend from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from .extensions import db class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, n...
StarcoderdataPython
4823642
import numpy as np import math as m def Jacobian(dh,rho): T=ConstructTransform(dh) t=ExtractOrients(T[-1][0:3,0:3]) zs=[np.dot(t,np.array([0,0,1,1]))[0,0:3] for t in T] On=np.dot(T[-1],np.array([0,0,0,1])) Os=[(On-np.dot(T[i],np.array([0,0,0,1])))[0,0:3] for i in range(len(T))] j=np.zeros([6,len(zs)]) fo...
StarcoderdataPython
11211998
# Copyright 2021 The NetKet 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
StarcoderdataPython
1669961
"""merge things Revision ID: 20d6b579456d Revises: 5d2bb32c6e04, 9<PASSWORD> Create Date: 2022-02-02 12:33:13.933500 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = ('5d2bb32c6e04', '<PASSWORD>') branch_labels = None depends_on = None ...
StarcoderdataPython
11212661
import requests import base64 import hmac import time api_key = "XAS6NTiO2rTbE0Gl2W3nvQ" secret_key = "<KEY>" api_url = "http://localhost:5003/api?" command = "list" secret_key = str.encode(secret_key) timestamp = str(int(time.time())) msg = "apikey=" + api_key + "&" + "command=" + command + "&" + "time=" + time...
StarcoderdataPython
6439032
<reponame>rpurnama/pycodes<gh_stars>1-10 import time import getpass import sys print """ db d8b db d88888b db .o88b. .d88b. .88b d88. d88888b 88 I8I 88 88' 88 d8P Y8 .8P Y8. 88'YbdP`88 88' 88 I8I 88 88ooooo 88 8P 88 88 88 88 88 88ooooo ...
StarcoderdataPython
173887
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import GenericRepr, Snapshot snapshots = Snapshot() snapshots['test_args 1'] = [ ( 'trace_func', ( GenericRepr('sentinel.frame'), 'call', ...
StarcoderdataPython
9627785
<filename>src/tw-mapgen.py import tkinter as tk from create_layered import create_layered from pathlib import Path config = [ ('filename', str(Path.cwd().joinpath('newmap.map')), str), ('base map size', '300', int), ('block length (max tunnel size)', '20', int), ('min wall thickness (per side)', '1', ...
StarcoderdataPython
5106012
from random import choice from typing import Any, Dict from django.http.request import HttpRequest from django.http.response import HttpResponse, Http404 from django.shortcuts import redirect, render from django.views.generic.base import ContextMixin, View from django.views.generic.detail import DetailView from django...
StarcoderdataPython
3509466
""" Sphere simulation and position tools Geometry simulation: * :py:func:`simulate_spheres_in_sphere`: Simulate a random sphere packing of hard spheres of identical radius inside a larger sphere Neighbor counting: * :py:func:`nearest_neighbors`: Calculate the distance to the nth closest point to a given set...
StarcoderdataPython
15068
import json import logging LOGGER = logging.getLogger(__name__) def start(self): self.start_consuming() def on_message(self, channel, method, properties, body): """ Invoked by pika when a message is delivered from the AMQP broker. The channel is passed for convenience. The basic_deliver object tha...
StarcoderdataPython
1741332
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function __author__ = "bl" import logging, sys, unittest, os from silvaengine_utility import Utility from dotenv import load_dotenv load_dotenv() setting = { "region_name": os.getenv("region_name"), "aws_access_key_id": os.getenv("aws_ac...
StarcoderdataPython
3436984
<filename>workshop/forms.py import datetime from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit from django import forms from django.contrib.auth.forms import AuthenticationForm from .models import Customer, Employee, Vehicle, Task, Invoice # TODO: make time...
StarcoderdataPython
4878023
import cv2 import numpy as np # 去除汗孔 def remove_pore(im, pore_size_max): """" :param im: 需要去除汗孔的图像 :param pore_size_max: 汗孔面积的最大值(经验值) :return: 处理后图像 """ # cv2.RETR_EXTERNAL:只检测外轮廓 # cv2.CHAIN_APPROX_NON:存储所有的轮廓点 image, contours, hierarchy = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2....
StarcoderdataPython
8975
<reponame>thongnbui/MIDS_251_project #!/usr/bin/python import json import argparse from influxdb import InfluxDBClient parser = argparse.ArgumentParser(description = 'pull data for softlayer queue' ) parser.add_argument( 'measurement' , help = 'measurement001' ) args = parser.parse_args() client_influxdb = InfluxDB...
StarcoderdataPython
3564323
<reponame>gregmbi/polyaxon #!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
StarcoderdataPython
199406
# Generated by Django 3.0.5 on 2020-05-25 04:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('part', '0042_auto_20200518_0900'), ('stock', '0042_auto_20200523_0121'), ] operations = [ migration...
StarcoderdataPython
1637123
""" Higher-level types for interacting with Myria relations """ from dateutil.parser import parse from itertools import izip from myria import MyriaConnection, MyriaError from myria.schema import MyriaSchema class MyriaRelation(object): """ Represents a relation in the Myria system """ DefaultConnection = M...
StarcoderdataPython
6415659
<filename>pman/pman/core.py import imp import fnmatch import os import shutil import subprocess import sys import time from collections import OrderedDict import configparser from . import toml from . import creationutils class PManException(Exception): pass class NoConfigError(PManException): pass clas...
StarcoderdataPython
6640131
<gh_stars>0 #!/usr/bin/env python3 import os import argparse import time import sys from threading import Thread, Lock global txns global clients clients = 100 txns = 100 # ==================== Notes and information ==================== # This script will run multiple instances (threaded) of the the...
StarcoderdataPython
6444750
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
StarcoderdataPython
3597593
from setuptools import setup, find_packages setup(name="naomi_bot", packages=find_packages(exclude=("naomi-bot-env")))
StarcoderdataPython
11248953
import numpy as np import bandits_lab.algorithms as algs import bandits_lab.bandit_definitions as bands import sim_utilities as sim """ Code for the experiments in the paper Adaptation to the range in K-armed bandits. """ np.random.seed(0) K = 10 T = 100000 n_tests = 100 """ Definitions of the problems cons...
StarcoderdataPython
1991125
#encoding:utf-8 import requests import json count_all = 0 hit = 0 fout = open('request.out_ik_balance','w') dict_query_all = dict() dict_recall_hit = dict() dict_predict_all = dict() jiexi_count = 0 fei_chui_lei = ['qa','baike','chat'] count_vertical = 0 count_non_vertical = 0 pre_count_vertical = 0 pre_count_non_v...
StarcoderdataPython
9730097
#!/usr/bin/python # 1. Calculer la somme d'une ligne # 2. Calculer la somme d'une colonne # 3. Calculer la somme de deux diagonales def somme_ligne(tab, n): som = 0 for i in range(len(tab[0])): som += tab[n][i] return som def somme_colonne(tab, n): som = 0 for i in range(len(tab)): ...
StarcoderdataPython
9659876
# -*- coding: utf-8 -*- """ Created on Thu Dec 10 14:49:27 2020 @author: celine.gross """ from collections import Counter with open('input_day10.txt', 'r') as file: puzzle = [int(x.strip()) for x in file] print(puzzle[:10]) # Part 1 def count_jolt_differences(data, start=0, end=+3): data.extend([start, ma...
StarcoderdataPython
1615491
import torch import torch.nn as nn from torch.cuda.amp import GradScaler, autocast from torchattacks.attack import Attack class FastBIM(Attack): def __init__(self, model, eps=4/255, alpha=1/255, steps=0): super().__init__("FastBIM", model) self.eps = eps self.alpha = alpha ...
StarcoderdataPython
11282704
<gh_stars>0 ''' /processes ''' from flask_restful_swagger_2 import Resource, swagger from flask_restful.reqparse import RequestParser from flask_restful.utils import cors from flask import request from . import rpc from .src.auth import auth from .src.response import * from .src.request import ModelRequestParser from...
StarcoderdataPython
5160041
<gh_stars>0 import os from casual.make.platform.platform_unix import CommonUNIX from casual.make.platform.registry import RegisterPlatform @RegisterPlatform("linux") class Linux( CommonUNIX): def pre_make(self): path = os.path.dirname( os.path.realpath(__file__)); print ...
StarcoderdataPython
9659234
<gh_stars>10-100 """ This module provides functions for generating dashboard tags. These functions are simple wrappers on top of the lxml `ElementMaker` API. These functions can be combined with additional HTML tags to produce the required XML to define dashboards. >>> import lxml.etree >>> from argusclient.da...
StarcoderdataPython
5101619
"""Transform Gas Demands. From: ID,DT,Usage 1565,33501,0 To: id datetime demand 1565 2009-12-02 00:30:00 0 """ from pathlib import Path from typing import Iterable import dask.dataframe as dd from dask.diagnostics import ProgressBar def _read_raw_txt_files(dirpath: str) -> Iterable[dd...
StarcoderdataPython
6612965
<gh_stars>10-100 #!/usr/bin/env python # -*- coding: ASCII -*- """ :Author: <NAME> :Contact: <EMAIL> :Date: *27.03.2008 """ import math class EDict: def __init__(self): self._internal_dict = {} self._sorted_keys = [] self._is_sync = True def __len__(self): return len(self._internal_dict.keys(...
StarcoderdataPython
11393485
# **************************************************************************** # contains: rule.split_inside_bracke -> see ^method-description # rule.or_split -> split an or separated pattern elements # author: @Hakim-Beldjoudi (hbFree) NOV 2019 # *************************************************************...
StarcoderdataPython
280179
<filename>data/example/split_words_tags.py __author__ = "<NAME>" from pathlib import Path import numpy as np def senttodoc(): file_path = 'wnut17/' for n in ['train','dev','test']: words = [] tags = [] sents = [] sent = '' sent_tags = '' with Path(file_path + n...
StarcoderdataPython
3233373
import enum from datetime import datetime, date from ..time import Frequency _aggregation_lookup = {} class Aggregation(enum.Enum): """ Supported aggregations in the API. Includes simple implementations of the different aggregation types for learning purposes. """ #: Calculate the mean value ...
StarcoderdataPython
1914895
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import random, math, os, time import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt import matplotlib.ticker as ticker from...
StarcoderdataPython
11328574
<reponame>bytepl/tracardi from pprint import pprint from tracardi.domain.event_metadata import EventMetadata, EventTime from tracardi.service.notation.dot_accessor import DotAccessor from tracardi.domain.context import Context from tracardi.domain.event import Event from tracardi.domain.flow import Flow, FlowSchema f...
StarcoderdataPython