id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3351688 | """
Snippets for file handling, reading, and parsing.
<NAME>, 2013-2014
"""
import os
def finding_max_nsets(array_of_files, num_of_files):
"""
Find max number of sets
"""
max_num_set= 0
for n in range(num_of_files):
filename = str(array_of_files[n])
... | StarcoderdataPython |
1707588 | sample = """35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576"""
full_input = """33
18
22
44
49
15
12
38
41
46
3
42
37
19
13
7
21
29
34
40
39
35
27
25
48
87
10
16
17
45
18
30
20
22
23
73
24
26
28
53
31
37
51
32
33
34
36
35
54
27
38
39
40
74
70
41
93
144
45
63
87
66
65
55
58
62
72
105
59
76
61
67
6... | StarcoderdataPython |
1698981 | <gh_stars>0
import re
test=re.compile(
r'^'
r'(?!.*(\d)(-?\1){3})'
r'[456]'
r'\d{3}'
r'(?:-?\d{4}){3}'
r'$'
)
for _ in range(int(input())):
print("Valid" if test.search(input().strip()) else "Invalid") | StarcoderdataPython |
8318 | <reponame>richo/groundstation
from broadcast_ping import BroadcastPing
EVENT_TYPES = {
"PING": BroadcastPing,
}
class UnknownBroadcastEvent(Exception):
pass
def new_broadcast_event(data):
event_type, payload = data.split(" ", 1)
if event_type not in EVENT_TYPES:
raise UnknownBroadcastEven... | StarcoderdataPython |
3314933 | import os
import sys
from collections import *
from copy import deepcopy
from itertools import *
# change to dir of script
os.chdir(os.path.dirname(os.path.abspath(__file__)))
input_file = "input.txt"
if "s" in sys.argv:
input_file = "input_small.txt"
try:
with open(input_file) as f:
data = f.read() #... | StarcoderdataPython |
3373355 | # Copyright 2021 The Data Text Grid Reader 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... | StarcoderdataPython |
4840387 | # -*- coding: utf-8 -*-
# 合并腾讯视频极速版离线TS文件
import os
import sys
import logging
import inspect
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from m3u8downloader.downloader import M3U8Downloader
if __name__ == '__main__':
LOG_LEVEL = logging.INFO
log = logging.getLogger()
log.setLevel(LOG_LEVEL)
h... | StarcoderdataPython |
1660663 | import torch
from torch.nn import functional as F
def deep_gambler_loss(outputs, targets, reward):
outputs = F.softmax(outputs, dim=1)
outputs, reservation = outputs[:,:-1], outputs[:,-1]
# gain = torch.gather(outputs, dim=1, index=targets.unsqueeze(1)).squeeze()
gain = outputs[torch.arange(ta... | StarcoderdataPython |
3385326 | <gh_stars>0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,C0114
import sys
import tblob
with open(sys.argv[1], 'rb') as blob_file:
tparser = tblob.tblob()
blob = tparser.parse_blob(blob_file.read())
print(blob)
| StarcoderdataPython |
37048 | class Calculador_de_impostos:
def realiza_calculo(self, orcamento, imposto):
imposto_calculado = imposto.calcula(orcamento)
print(imposto_calculado)
if __name__ == '__main__':
from orcamento import Orcamento, Item
from impostos import ISS, ICMS, ICPP, IKCV
orcamento = Orcamento()
... | StarcoderdataPython |
1739229 | <reponame>dannyvi/py-fly-compile-c<filename>compfly/parse/loader.py
"""Loader do the preceding part of constructing a parser(syntax analyzer).
It read rules from a .grammar definition file, and execute a analyze procedure.
The procedure of loading is below:
1. seperate file by --------------- seperate line into **... | StarcoderdataPython |
1642266 | # Generated by Django 3.0.10 on 2020-09-11 12:00
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("admin_tools_stats", "0007_auto_20200205_1054"),
]
operations = [
migrations.AddField(
model_na... | StarcoderdataPython |
4830664 | <reponame>Atelis/DirectML<gh_stars>100-1000
#!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
import matplotlib.pyplot as plt
import json
import os
import re
import argparse
script_root = os.path.dirname(os.path.realpath(__file__))
parser = argparse.ArgumentParser()
parser.add_argumen... | StarcoderdataPython |
186212 | """
test_tools: tests function in denovo.tools
<NAME> <<EMAIL>>
Copyright 2020-2021, <NAME>
License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0)
ToDo:
Add tests for the remaining functions in tools.
"""
import sys
from typing import (Any, Callable, ClassVar, Dict, Hashable, Iterable, Mapping,
... | StarcoderdataPython |
131155 | import re
import copy
import pickle
import numpy as np
from collections import OrderedDict
import torch
from torch.autograd import Variable
import global_variables as g
def save_checkpoint(state, filename='./checkpoints/checkpoint.pth.tar'):
print('save model!', filename)
torch.save(state, filename)
def sav... | StarcoderdataPython |
3245475 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from data_structures.linked_list import BaseNode, InsertPositions, LinkedList, SearchPositions
class Node(BaseNode):
"""Class implementing a `node` in a singly linked list
Each node contains following parts:
- value
- a pointer to the next node
... | StarcoderdataPython |
1687800 | import logging
from io import StringIO
from typing import Union
from asyncio import TimeoutError
import discord
from discord.ext import commands
from bot import constants
from bot.cogs.utils.embed_handler import authored, failure, success, info
from bot.cogs.utils.checks import check_if_it_is_tortoise_guild
from bot.... | StarcoderdataPython |
3245662 | <reponame>neo2100/BioNIR_Pipeline
# BioNIR Pipline class
# Pipline order:
# 1- documentRetrieval (PubMed APIs or BM25+DB)
# 2- preprocessing: (a- sentence splitting b- co-reference resolution 3- Abbreviation resolution 4- sentence simplification)
# 3- embedding (SBERT or BioASQ SBERT)
# 4- pooling (MEAN, MAX, or CLS, ... | StarcoderdataPython |
1688114 | """Custom methods for device entities."""
from six.moves.urllib.parse import urlparse
from io import StringIO
def download_report_file(self, absolute_url):
"""Download a report file.
:param self: Instance of the entity for which this is being called.
:type self: mbed_cloud.foundation.DeviceEnrollmentBul... | StarcoderdataPython |
82188 | import sys
from torch.utils.data import Dataset, DataLoader
import os
import os.path as osp
import glob
import numpy as np
import random
import cv2
import pickle as pkl
import json
import h5py
import torch
import matplotlib.pyplot as plt
from lib.utils.misc import process_dataset_for_video
class Surreal... | StarcoderdataPython |
4834307 | #Uses RSI to determine if stock overbought or oversold
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
stock = pd.read_csv('AAPL.csv')
stock.set_index(pd.DatetimeIndex(stock['Date']),inplace=True)
delta = stock['Adj Close'].diff(1)
delta.dropna()
up = delta.c... | StarcoderdataPython |
1671773 | <reponame>Ravoxsg/transformers
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. 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/li... | StarcoderdataPython |
1767787 | from rest_framework.permissions import BasePermission
class CanSubscribe(BasePermission):
pass
| StarcoderdataPython |
3320127 | <gh_stars>0
# pylint: disable=missing-module-docstring
#
# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >.
#
# This file is part of < https://github.com/UsergeTeam/Userge > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/uaudith/Userge/blo... | StarcoderdataPython |
3315759 | <gh_stars>1-10
#########
# Copyright (c) 2018 Lumina Communcation Systems Ltd. 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/LIC... | StarcoderdataPython |
139883 | <reponame>dbbxzw-610/bilibili-live-push
import asyncio
import time
from typing import *
class EchoFormat:
th: List[str] = []
td: List[List[str]] = []
first_echo: bool = True
last_update: float = time.time()
def __init__(self) -> None:
pass
def init_th(self, *arg) -> None:
sel... | StarcoderdataPython |
1676246 | <reponame>smalldragonvt/curlify
# coding: utf-8
import os
from setuptools import setup, Command
class CleanCommand(Command):
"""Custom clean command to tidy up the project root."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(sel... | StarcoderdataPython |
109465 | import torch
try:
from torch.utils.data import IterableDataset
except ImportError:
class IterableDataset:
pass
class BatchChecker:
def __init__(self, data, init_counter=0):
self.counter = init_counter
self.data = data
self.true_batch = None
def check(self, batch):
... | StarcoderdataPython |
4802186 | <reponame>ttngu207/Economo-2018
import re
import os
import sys
from datetime import datetime
import numpy as np
import scipy.io as sio
import datajoint as dj
import h5py as h5
from . import reference, subject, utilities
schema = dj.schema(dj.config['custom'].get('database.prefix', '') + 'acquisition')
@schema
clas... | StarcoderdataPython |
3300443 | import ast
import sys
from optparse import OptionParser, OptionGroup
from logger import Logger
from check import check_mod, check_expr
from infer import infer_expr
from ptype import PType
from parse_file import parse_type_decs
from ast_extensions import TypeDecASTModule
import check
import parse_file
import infer
lo... | StarcoderdataPython |
3264384 | <reponame>cloudcalvin/spira<filename>spira/param/__init__.py<gh_stars>0
from .field.typed_integer import IntegerField
from .field.typed_string import StringField
# from .field.typed_float import FloatField
from .field.typed_bool import BoolField
from .field.typed_list import ListField
from .field.layer_list import Laye... | StarcoderdataPython |
3348698 | #%%
msg="hello world"
print(msg)
#%%
| StarcoderdataPython |
3259565 | import numpy as np
from tacs import TACS, elements, constitutive, functions
from static_analysis_base_test import StaticTestCase
import os
'''
Load in a bdf file with tetrahedral elements, apply a load,
and test KSFailure, StructuralMass, and Compliance functions and sensitivities.
This test is based on the "tetrahed... | StarcoderdataPython |
3390422 | # -*- coding: utf-8 -*-
# environment vars
import os
import logging
# webapp utilities
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
# import project modules
import config
from utilities import *
from kudos import *... | StarcoderdataPython |
185629 | #!/usr/bin/env python
import os
import subprocess
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from whoosh.index import open_dir
from whoosh.qparser import QueryParser
from archivo.models import Documento
class Command(BaseCommand):
help = 'Buscar documento... | StarcoderdataPython |
1651263 | <reponame>openstack/murano-pkg-check
# Copyright (c) 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | StarcoderdataPython |
1646662 | <filename>test/programytest/extensions/geocode/test_geocode.py
import unittest
import os
import json
from programy.extensions.geocode.geocode import GeoCodeExtension
from programy.utils.geo.google import GoogleMaps
from programy.context import ClientContext
from programytest.aiml_tests.client import TestClient
class... | StarcoderdataPython |
1687428 | <gh_stars>1-10
class Decoder(object):
"""
A class used to represent a Decoder
"""
@staticmethod
def validate(text):
"""Validate string format for this cipher.
:param text: The cipher-text
:type text: str
:returns: Either the text is in the cipher format or not
... | StarcoderdataPython |
75229 | # See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
# 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/li... | StarcoderdataPython |
4830235 | <filename>software/multifluids_icferst/tools/genpvtu.py
#!/usr/bin/env python
import os
import sys
import tempfile
import vtk
import fluidity.diagnostics.debug as debug
import fluidity.diagnostics.filehandling as filehandling
import fluidity.diagnostics.fluiditytools as fluiditytools
import fluidity.diagnostics.vtuto... | StarcoderdataPython |
3380258 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from .compat import isstr
from .sql import sql_escape
from .log import configure_logging, default_logger
from .argparser import configure_parser, default_parser
from .csv import flatten, unflatten
__all__ = [
'isstr',
'sql_escape',
'configure_... | StarcoderdataPython |
162933 | <reponame>AtjonTV/Python-1.4
# Temporary file name allocation
#
# XXX This tries to be not UNIX specific, but I don't know beans about
# how to choose a temp directory or filename on MS-DOS or other
# systems so it may have to be changed...
import os
# Parameters that the caller may set to override the defaults
te... | StarcoderdataPython |
1634939 | #!/usr/bin/env python3
"""concatenates two matrices"""
def cat_matrices2D(mat1, mat2, axis=0):
"""cat_matrices2D: concatenates two matrices along a specific axis
Args:
mat1: First matrix to concatenate
mat2: Second matrix to concatenate
axis (optional): Defaults to 0.
"""
resu... | StarcoderdataPython |
3393985 | from pathlib import Path
ROOT_DIR = Path(__file__).parent.parent.resolve()
DATA_DIR = ROOT_DIR.joinpath('data')
RESULTS_DIR = ROOT_DIR.joinpath('results')
PLOTS_DIR = ROOT_DIR.joinpath('plots')
UMAPS_DIR = ROOT_DIR.joinpath('umaps')
SCORES_PATH = RESULTS_DIR.joinpath('scores.csv')
TIMES_PATH = RESULTS_DIR.joinpath('... | StarcoderdataPython |
3244750 | import glob
import os
from PIL import Image
from minio import Minio
from minio.error import ResponseError
import logging
import confluent_kafka
import pymongo
import json
from bson.objectid import ObjectId
minio_endpoint = os.environ["MINIO_ENDPOINT"]
minio_access_key = os.environ["MINIO_ACCESSKEY"]
minio_secret_key ... | StarcoderdataPython |
3397897 | <filename>pressure_adapt.py<gh_stars>0
import os
import pandas as pd
import torch
import torch.nn.functional as F
import numpy as np
import time
from featurization.data_utils import load_data_from_df, construct_loader_gf_pressurever, construct_dataset_gf_pressurever, data_prefetcher
from models.transformer import make_... | StarcoderdataPython |
1629322 | <gh_stars>0
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC, expected_conditions
from selenium.webdriver.support.wait import WebDriverWait as wait
from fixtures.params import DEFAULT_PASSWORD
def login(driver, username = 'admin', password = <PASSWORD>):
... | StarcoderdataPython |
5793 | class ICFSError(IOError):
"""Error while making any filesystem API requests."""
| StarcoderdataPython |
3323702 | <filename>websclaping1.py
# import requests
# from bs4 import BeautifulSoup
#
# url='https://news.yahoo.co.jp/flash?p=1'
# res=requests.get(url)
# soup=BeautifulSoup(res.content)
# parent=soup.find('div','newsFeed')
# targets=parent.findAll('div','newsFeed_item_title')
#
# for target in targets:
# print(target.text... | StarcoderdataPython |
145911 | import datetime
from unittest.mock import MagicMock
import pytest
from bloop.models import BaseModel, Column
from bloop.stream.coordinator import Coordinator
from bloop.stream.stream import Stream
from bloop.types import Integer, String
from bloop.util import ordered
from . import build_shards
@pytest.fixture
def ... | StarcoderdataPython |
3359039 | <filename>cassie/misc/rewards/rnn_dyn_random_reward.py
import numpy as np
def jonah_RNN_reward(self):
qpos = np.copy(self.sim.qpos())
qvel = np.copy(self.sim.qvel())
ref_pos, ref_vel = self.get_ref_state(self.phase)
# TODO: should be variable; where do these come from?
# TODO: see magnitude o... | StarcoderdataPython |
3313916 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright (c) 2017, taher and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class StockOUT(Document):
def on_submit(self):
frappe.errprint("in on on_submit")
... | StarcoderdataPython |
1751722 | from enum import Enum
class ReadCommand(Enum):
exhaustTemperature = bytes([0x04, 0x04, 0x14, 0x75])
supplyTemperature = bytes([0x04, 0x04, 0x14, 0x73])
extractTemperature = bytes([0x04, 0x04, 0x14, 0x74])
outdoorTemperature = bytes([0x04, 0x04, 0x14, 0x72])
humidity = bytes([0x01, 0x04, 0x14, 0x70]... | StarcoderdataPython |
22514 | from . import models
from . import serializers
from rest_framework import viewsets, permissions
class CompetitionViewSet(viewsets.ModelViewSet):
"""ViewSet for the Competition class"""
queryset = models.Competition.objects.all()
serializer_class = serializers.CompetitionSerializer
permission_classes ... | StarcoderdataPython |
112904 | <filename>pyradmon/args.py
#!/usr/bin/env python
# PyRadmon - Python Radiance Monitoring Tool
# Copyright 2014 <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.apach... | StarcoderdataPython |
3322879 | <gh_stars>1-10
__all__ = ["Sample", "Generator"]
import random
import itertools
import collections
from dataclasses import dataclass
from typing import Tuple, Sequence, Mapping, Optional
import torch
import utils
from utils import TensorMap
from datasets import Dialog
from datasets import DialogProcessor
from datase... | StarcoderdataPython |
1715843 | import logging
import time
from abc import ABC, abstractmethod
from contextlib import contextmanager
from functools import partial
from pathlib import Path
import numpy as np
from moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriter
from tqdm import tqdm
from PIL import Image
from tao.utils import vis
_GREEN = (... | StarcoderdataPython |
4824712 | <filename>opencti/src/opencti.py
import os
import yaml
import time
import urllib.request
from datetime import datetime
from pycti import OpenCTIConnectorHelper, get_config_variable
class OpenCTI:
def __init__(self):
# Instantiate the connector helper from config
config_file_path = os.path.dirname... | StarcoderdataPython |
178367 | # Author: <NAME>
# Date: 26/06/2018
# Project: TdaToolbox
try: from filtration.imports import *
except: from imports import *
# Time delay embedded procedure
# val refers to a 1D time-serie
# step corresponds to the time-delay
# dimension is the dimension of the time-delay embedding
# point_size refers to the dim... | StarcoderdataPython |
1683029 | """Initial Database Creation
Revision ID: 9c57eb87e918
Revises: None
Create Date: 2016-08-11 22:23:51.191035
"""
# revision identifiers, used by Alembic.
revision = '9c57eb87e<PASSWORD>'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic -... | StarcoderdataPython |
1725312 | <gh_stars>0
import sys
import os
import importlib.util
from collections import deque
from interlib.utility import ImportQueue
from interlib.utility import print_line
from interlib.utility import show_error
from importlib import import_module
def interpret(pseudo_file, python_file, keyword_dict, is_debug_on)... | StarcoderdataPython |
1703364 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from datetime import datetime
from gae_libs.testcase import TestCase
from libs import analysis_status
from model import result_status
from model import tri... | StarcoderdataPython |
1792587 | <filename>orb_simulator/orbsim_language/orbsim_ast/and_node.py
from orbsim_language.orbsim_ast.binary_expr_node import BinaryExprNode
class AndNode(BinaryExprNode):
pass | StarcoderdataPython |
43223 | <filename>wagtail/wagtailsearch/tests.py<gh_stars>1-10
from django.test import TestCase
from django.test.client import Client
from django.utils import timezone
from django.core import management
from django.conf import settings
import datetime
import unittest
from StringIO import StringIO
from wagtail.wagtailcore imp... | StarcoderdataPython |
1704446 | <reponame>aurelienline/scikit-extremes
"""
This module provides utility functions that are used within scikit-extremes
that are also useful for external consumption.
"""
import warnings as _warnings
from numpy.random import randint as _randint
import numpy as _np
import scipy.stats as _st
from scipy import optimize a... | StarcoderdataPython |
43309 | import time
from datetime import datetime
from serial import Serial # Library needed to open serial connection
PIN = 'a5'
PORT = 'COM11'
PORT = Serial(port=PORT, baudrate=9600, timeout=0) # Open the Serial port
def encode_command(command):
return bytearray(command, encoding='utf-8')
print('-' * 50)
print('... | StarcoderdataPython |
3290592 | <filename>lib/python2.7/site-packages/selectable/tests/fields.py
from django import forms
from selectable.forms import fields
from selectable.tests import ThingLookup
from selectable.tests.base import BaseSelectableTestCase
__all__ = (
'AutoCompleteSelectFieldTestCase',
'AutoComboboxSelectFieldTestCase',
... | StarcoderdataPython |
3297911 | # Leetcode 417. Pacific Atlantic Water Flow
#
# Link: https://leetcode.com/problems/pacific-atlantic-water-flow/
# Difficulty: Medium
# Solution using DFS and sets
# Complexity:
# O(M*N) time | where M and N represent the rows and cols of the input matrix
# O(M*N) time | where M and N represent the rows and cols o... | StarcoderdataPython |
1728782 | # Copyright 2020 Google LLC
#
# 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 applicable law or agreed to in writing, ... | StarcoderdataPython |
194841 | """Set up a fake hook for testing purposes."""
import platform
from pathlib import Path
from typing import Dict
import pluggy
import pytest
from edgetest import hookspecs
hookimpl = pluggy.HookimplMarker("edgetest")
class FakeHook:
"""Create a series of fake hooks."""
@hookimpl
def path_to_python(sel... | StarcoderdataPython |
1693706 | <filename>brainiac_priv/brainiac_test_priv/brainiac.py
class brainiac_test_test:
def __init__(self,dark):
self.dark=dark
def test(dark):
print(dark) | StarcoderdataPython |
3348242 | from multiprocessing import Pool
from rdkit.Chem import AllChem
from autode.input_output import xyz_file_to_atoms
from autode.conformer import Conformer
from autode.conf_gen import get_simanl_atoms
from autode.conformers import conf_is_unique_rmsd, get_atoms_from_rdkit_mol_object
from autode.atoms import metals
from au... | StarcoderdataPython |
14901 | <reponame>kkcookies99/UAST
class Solution:
def XXX(self, root: TreeNode) -> bool:
stack = []
cur = root
last = float("-inf")
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if cur.v... | StarcoderdataPython |
3341063 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2020/5/26 18:54
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
---------------------------------... | StarcoderdataPython |
77945 | import torch
import numpy as np
from onnx import numpy_helper
from thop.vision.basic_hooks import zero_ops
from .counter import counter_matmul, counter_zero_ops,\
counter_conv, counter_mul, counter_norm, counter_pow,\
counter_sqrt, counter_div, counter_softmax, counter_avgpool
def onnx_counter_matmul(diction,... | StarcoderdataPython |
4826556 | #! /usr/bin/env python3
# We need this to define our package
from setuptools import setup
# We use this to find and deploy our unittests
import unittest
import os
# We need to know the version to backfill some dependencies
from sys import version_info, exit
# Define our list of installation dependencies
DEPENDS = ["p... | StarcoderdataPython |
1736567 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from cmsplugin_cascade import settings
def remove_duplicates(lst):
"""
Emulate what a Python ``set()`` does, but keeping the element's order.
"""
dset = set()
return [l for l in lst if l not in dset and not dset.add(l)]
def resolve_... | StarcoderdataPython |
97476 | <filename>src/su/aes.py
from Crypto.Cipher import AES
from Crypto.Util import Counter
from binascii import hexlify, unhexlify
import os
__all__ = ["encrypt", "decrypt", "main"]
MODE = AES.MODE_CTR
BS = AES.block_size
KS = AES.key_size[-1]
def _pad_bytes(byte_str, size):
if len(byte_str) > size:
return b... | StarcoderdataPython |
1696460 | <filename>qlink/duplicates_merger.py<gh_stars>1-10
import json
class Merger:
RANDOM_MODE = 0
ENRICH_MODE = 1
def __init__(self, dataframe, duplicates_path, result_path, merger_mode):
self.dataframe = dataframe
with open(duplicates_path, 'r') as fp:
self.duplicates = json.load(... | StarcoderdataPython |
1741918 | <filename>voltha/leader.py<gh_stars>0
#
# Copyright 2017 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | StarcoderdataPython |
44679 | #!/usr/bin/env python
import numpy
import storm_analysis
import storm_analysis.simulator.pupil_math as pupilMath
def test_pupil_math_1():
"""
Test GeometryC, intensity, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = ... | StarcoderdataPython |
1711825 | <reponame>smartdolphin/toxic-comment-classification<gh_stars>1-10
from keras import Model
from keras.layers import Input, Dense, Embedding, Conv1D
from keras.layers import GRU, Bidirectional
from keras.layers import SpatialDropout1D, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import concatenate
from k... | StarcoderdataPython |
3305 | <filename>script.py<gh_stars>0
import os
import pyfiglet
from pytube import YouTube, Playlist
file_size = 0
folder_name = ""
# Progress Bar
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end="\r"):
percent = ("{0:." + str(decimals) + "f}").format(100 *
... | StarcoderdataPython |
103106 | <filename>api/app.py
# -*- encoding: utf-8 -*-
'''
@File : app.py
@Time : 2020/04/29 01:22:13
@Author : white_walker cailiang
@Version : 1.0
@Contact : <EMAIL>
@Desc : None
'''
# here put the import lib
from flask import Flask, request, make_response
from thunder_subtitle.search import search, g... | StarcoderdataPython |
3289089 | #!/usr/bin/env python
# encoding: utf-8
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cur_min = cur_max = 0
pre_min = pre_max = 1
maxval = float("-inf")
for num in nums:
cur_min = min(pre_mi... | StarcoderdataPython |
1741474 | # Copyright (C) by <NAME>. See LICENSE.txt for licensing information.
import os
import imp
import traceback
#try to import module
def __try_module_import(filename):
directory, module_name = os.path.split(filename)
module_name = os.path.splitext(module_name)[0]
try:
fp, pathname, description = imp... | StarcoderdataPython |
1703147 | <gh_stars>1-10
# ============================================================================================================================ #
# PROTEIN STRUCTURE PREDICTION : REINFORCEMENT LEARNING AGENTS #
# =============================================... | StarcoderdataPython |
1641964 | from django.db import models
# Create your models here.
class FileAndImage(models.Model):
createdTime = models.DateTimeField(auto_now_add=True)
filePath = models.CharField(max_length=100,default="")
| StarcoderdataPython |
3359558 | <filename>source/pkgsrc/graphics/py-imaging/patches/patch-PIL_IcnsImagePlugin.py
$NetBSD: patch-PIL_IcnsImagePlugin.py,v 1.1 2014/09/07 09:37:46 spz Exp $
Icns DOS fix -- CVE-2014-3589
from https://github.com/python-pillow/Pillow/commit/205e056f8f9b06ed7b925cf8aa0874bc4aaf8a7d
--- PIL/IcnsImagePlugin.py.orig 2009-11... | StarcoderdataPython |
1740486 | <filename>data collection.py
import threading
import time
from pynput import keyboard
import websocket
import _thread
import json
import ssl
import numpy as np
import pickle
auth_key = ""
values = []
current_keys = set()
is_esc = False
key_mapped_values = {i: [] for i in ["up-left", "up-right", "down-lef... | StarcoderdataPython |
3240182 | from rest_framework.test import APITestCase, APIClient
from django.urls import reverse
from rest_framework.authtoken.models import Token
class NotificationsTest(APITestCase):
"""
Test the metadata APIv2 endpoint.
"""
fixtures = ['dojo_testdata.json']
def setUp(self):
token = Token.objects... | StarcoderdataPython |
84603 | <reponame>ppelleti/berp
print(-1)
print(-0)
print(-(6))
print(-(12*2))
print(- -10)
| StarcoderdataPython |
1730461 | <reponame>jtackaberry/stagehand
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# webradio.py - read webradio attributes
# -----------------------------------------------------------------------------
# $Id$
#
# -----------------------------------------------... | StarcoderdataPython |
1736427 | <gh_stars>0
# O construtor __init__ é um método especial que nos permite inicializar atributos
# no momento em que uma instância é construída. Como vimos no script anterior, os
# atributos são tradicionalmente configurados usando um método set_attribute_val().
class MyNumber(object):
def __init__(self, value): ... | StarcoderdataPython |
3300413 | <reponame>Enestst/codewars
def num_key_strokes(text):
one_type = "qazwsxedcrfvtgb yhnujmik,./l;o'p][`1234567890-\="
sum = 0
for i in text:
if i in one_type: sum += 1
else: sum+=2
return sum
| StarcoderdataPython |
1654493 | <gh_stars>1-10
default_app_config = 'peacecorps.apps.PeaceCorpsConfig' | StarcoderdataPython |
3209924 | <filename>demo_srl_utils.py
import logging
import os
import codecs
import random
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union, Dict
from filelock import FileLock
from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available, RobertaModel, BertPreT... | StarcoderdataPython |
1635868 | <reponame>Valaraucoo/raven
import datetime
import os
import uuid
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db import models
from django.dispatch import receiver
from django.urls import rever... | StarcoderdataPython |
12659 | <reponame>johnjohndoe/c3nav
from django import template
register = template.Library()
@register.filter
def negate(value):
return -value
@register.filter
def subtract(value, arg):
return value - arg
| StarcoderdataPython |
70777 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import rosparam
from std_msgs.msg import String
from intersection_recognition.srv import Scenario
import MeCab
class ScenarioParser:
def __init__(self):
self.hz = 1
self.loop_rate = rospy.Rate(self.hz)
self.scenario_serv... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.