id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1763606
<filename>easy/1374-Generate a String With Characters That Have Odd Counts.py """ https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/ Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must c...
StarcoderdataPython
3292458
<gh_stars>1-10 """serialization module. Classes provided include: :class:`ResourceFactory` - Factory for generating :class:`.resources.Resource` subclasses out of JSON data. """ from .fields import Boolean, Date, Number, Object, Symbol, Text, List, MultipleAssets, MultipleEntries from .resources import ResourceType, ...
StarcoderdataPython
65886
# -*- coding: utf-8 -*- # pip install pdfminer.six -i https://pypi.doubanio.com/simple import io from pdfminer.high_level import * sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') def return_txt(): name = sys.argv[1] text = extract_text(name) print(text) if __name__ == '__main__': ...
StarcoderdataPython
93635
import pytest from asgiref.sync import sync_to_async from channels.testing import WebsocketCommunicator from realtime_api.testing import AuthWebsocketCommunicator, create_user from realtime_api.utils import get_group_user_key, close_user_channels from .consumers import GroupTestConsumer def test_group_does_not_exis...
StarcoderdataPython
1657322
from distutils.core import setup from setuptools import find_packages setup( name="pandasql3", version="0.7.3", author="<NAME>", author_email="<EMAIL>", url="https://github.com/dunakeyr/pandasql3/", license="MIT", packages=find_packages(), package_dir={"pandasql": "pandasql"}, packa...
StarcoderdataPython
1609410
<reponame>shashankrnr32/pytkdocs<filename>tests/fixtures/unwrap_getattr_raises.py class TryMe: def __getattr__(self, item): raise ValueError TRY_ME = TryMe()
StarcoderdataPython
4811562
<gh_stars>0 from fabric.api import env, run, sudo, put import collections import json import requests response = requests.get('http://%s:8080/' % optica_ip) hosts = json.loads(response.text) # fill the role list env.roledefs = collections.defaultdict(lambda: []) for hostinfo in hosts['nodes'].values(): env.ro...
StarcoderdataPython
1685862
''' sparse vector based on defaultdict Modifications for Python 3 made by <NAME> ''' __author__ = "lhuang" from collections import defaultdict class svector(defaultdict): def __init__(self, old=None): if old is not None: defaultdict.__init__(self, float, old) else: defau...
StarcoderdataPython
3249943
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # You may find it more helpful to your design to adjust the # functionality, constants and interfaces (if there are an...
StarcoderdataPython
4829338
<gh_stars>0 # -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; with...
StarcoderdataPython
3315408
<filename>crsf_drv/parse_serial.py<gh_stars>0 #!/usr/bin/env python3 from operator import contains import os from typing import Container, final from crsf_parser import CRSFParser from serial import Serial def print_frame(frame: Container) -> None: print(frame) crsf_parser = CRSFParser(print_frame) with Serial...
StarcoderdataPython
71464
from django.conf.urls import include, url import django_eventstream from . import views urlpatterns = [ url(r'^$', views.home), url(r'^events/', include(django_eventstream.urls)), ]
StarcoderdataPython
3244564
################################################################# # falcon-player-controller-uploadr # # Copyright (c) 2017 atomicnumber1 # ################################################################# import os import subprocess import logging import logg...
StarcoderdataPython
4822133
""" IO-Tools -------- Tools for input and output. """ from pathlib import Path from datetime import datetime from typing import Iterable from generic_parser.entry_datatypes import get_instance_faker_meta from generic_parser.entrypoint_parser import save_options_to_config from pylhc_submitter.constants.general import...
StarcoderdataPython
1686273
<filename>tincan/activity.py # 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.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
StarcoderdataPython
3311537
<filename>allencv/tests/predictors/object_detection/region_proposal_network.py from allencv.common.testing import AllenCvTestCase from allencv.data.dataset_readers import ImageAnnotationReader from allencv.predictors import ImagePredictor from allencv.models.object_detection import RPN from allencv.modules.image_encode...
StarcoderdataPython
3394992
""" Cannned responses for glance images """ from __future__ import absolute_import, division, unicode_literals from mimic.canned_responses.json.glance.glance_images_json import (images, image_schema) def get_images(): """ Canned response for...
StarcoderdataPython
4810405
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Fit annual var in single catchment example Created on Tue Apr 27 16:40:46 2021 @author: lizz """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.tsa.ar_model import AutoReg, ar_select_order from mat...
StarcoderdataPython
1609609
<filename>tiny_video_nets/batch_norm.py # coding=utf-8 # Copyright 2021 The Google Research 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/LIC...
StarcoderdataPython
3238161
<reponame>fightTone/CSC-171-Othello-game<gh_stars>0 import pygame, sys, pygame.mixer, time, os from pygame.locals import * EMPTY = 0 BLACK = 1 WHITE = 2 INFINITY = 999999999 MAX = 0 MIN = 1 DEFAULT_LEVEL = 2 HUMAN = "human" COMPUTER = "computer" RANDOM = "random" class Gui: def __init__(self): pygame.in...
StarcoderdataPython
1672355
""" Binary field is an interface used by binary structs. Each field in binary structs must implement: - serialization - deserialization - size property Binary field is an interface for such these things. PrimitiveTypeField is a primitive-ctypes based field, and this file adds the classic primitive types t...
StarcoderdataPython
41583
import os import ast import sys import math import time import string import hashlib import tempfile import subprocess from operator import itemgetter from contextlib import contextmanager from getpass import getpass import random; random = random.SystemRandom() import sdb.subprocess_compat as subprocess from sdb.util...
StarcoderdataPython
1727322
<filename>apt/minimization/minimizer.py<gh_stars>10-100 """ This module implements all classes needed to perform data minimization """ from typing import Union import pandas as pd import numpy as np import copy import sys from scipy.spatial import distance from sklearn.base import BaseEstimator, TransformerMixin, MetaE...
StarcoderdataPython
3309040
# -*- encoding: utf-8 -*- ''' Created on 2012-3-22 @author: Neil ''' from django.db import models class Tag(models.Model): """ 标签的数据模型 """ name = models.CharField(max_length=20, unique=True) used_count = models.IntegerField(default=1) # created_at = models.DateTimeField(default=datetime.datet...
StarcoderdataPython
1642012
#!/usr/bin/env python3 ''' @file listener.py @package py3_listner @author CVH95 @email <EMAIL> @brief Fibonacci listener Copyright (C) 2021 MIT License ''' import rospy from std_msgs.msg import * class Listener: def __init__(self): self.fibonacci = 0 self.subscriber = rospy.Subscr...
StarcoderdataPython
36138
"""Pauses the execution.""" import time from dodo_commands.framework.decorator_utils import uses_decorator class Decorator: def is_used(self, config, command_name, decorator_name): return uses_decorator(config, command_name, decorator_name) def add_arguments(self, parser): # override parser...
StarcoderdataPython
4803286
<filename>spyder/plugins/io_dcm/__init__.py<gh_stars>1000+ # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2009- Spyder Project Contributors # # Distributed under the terms of the MIT License # (see spyder/__init__.py for details) # ---------------...
StarcoderdataPython
1721228
# -*- coding: utf-8 -*- """ Created on Tue Mar 9 12:12:48 2021 @author: rdavi Preprocess datasets, including silence trimming and spliting in 1s chunks """ # %% Import libraries import os import numpy as np import opensmile import pickle import librosa import matplotlib.pyplot as plt # %% Define the dataset d...
StarcoderdataPython
3329321
<gh_stars>1-10 __copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os import sys import pytest from click.testing import CliRunner sys.path.append('..') from app import main def config(tmpdir): os.environ['JINA_DATA_FILE'] = os.path.join(os.path.dirname(_...
StarcoderdataPython
116193
########################################################################## # # Copyright (c) 2017, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
StarcoderdataPython
3228186
#!/bin/python import curses import os from mpd import MPDClient import ffmpeg import pixcat import time import configparser import ueberzug.lib.v0 as ueberzug from PIL import Image, ImageDraw # Get config config = configparser.ConfigParser() config.read(os.path.expanduser("~/.config/miniplayer/config")) if "player" n...
StarcoderdataPython
1702884
<reponame>morlandi/django-email-test # -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-10 17:42 from __future__ import unicode_literals import datetime from django.db import migrations, models import django_email_test.models class Migration(migrations.Migration): dependencies = [ ('django...
StarcoderdataPython
115991
<reponame>e-orlov/autosklearn-zeroconf # -*- coding: utf-8 -*- """ Copyright 2017 <NAME> Created on Sun Apr 23 11:52:59 2017 @author: ekobylkin This is an example on how to prepare data for autosklearn-zeroconf. It is using a well known Adult (Salary) dataset from UCI https://archive.ics.uci.edu/ml/datasets/Adult . ""...
StarcoderdataPython
3398227
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
StarcoderdataPython
3240297
import numpy as np def preprocess(arr): # Set to 0/1 pixels for island calculations b = arr > 0 b = b.astype(int) return b def dfs(arr, x, y, area=False): h, w = arr.shape arr[x][y] = 0 adjacent = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] num = 1 for row, col in adjacent: ...
StarcoderdataPython
1669327
from collections import namedtuple from nameko.extensions import DependencyProvider class ServiceDependencyProvider(DependencyProvider): def make_dependency(self, **services): return namedtuple('{}Dependency'.format(self.__class__.__name__), services.keys())(**services) def get_dependency(self, work...
StarcoderdataPython
171925
# xml.py # ------------------------------------------------------------------------------------------------ # def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): ...
StarcoderdataPython
3362185
from __future__ import absolute_import, division, print_function from cfn_model.model.ModelElement import ModelElement class EC2Instance(ModelElement): """ Ecs instance model """ def __init__(self, cfn_model): """ Initialize :param cfn_model: """ # attr_access...
StarcoderdataPython
1730878
import argparse argparser = argparse.ArgumentParser("python argparse_example.py") argparser.add_argument('-n', '--no-confirm', action='store_true', dest="no_confirm", help="Skip confirming deletion of existing dotfiles " + "that would be overwritten")...
StarcoderdataPython
3221424
from pytube import YouTube import os def download_video(url, name): try: # cria uma instância de YouTube yt = YouTube(url) # seta o nome do vídeo yt.set_filename(name) # obtém o diretório corrente curr_dir = os.path.dirname(os.path.abspath(__file__)) # seleciona por mp4 e pela mais alta resolução ...
StarcoderdataPython
1627885
<gh_stars>0 def uniquePath2(obstacleGrid: list): """ Este algoritmo resuelve el siguiente ejercicio: Unique Path II https://leetcode.com/problems/unique-paths-ii/ Este algoritmo retorna el número de caminos únicos que puede seguir un robot para llegar a la meta. El robot se ubica en la posición superior iz...
StarcoderdataPython
3382106
<filename>Dataset/Leetcode/valid/12/578.py class Solution(object): def XXX(self, num): out = [] def getN (num,str1): if num == 0: out.append(str1) return if num >= 1000: getN(num-1000,str1+'M') elif num >= 900: ...
StarcoderdataPython
168508
from .traj_conv import TrajConvFunction, TrajConv __all__ = ['TrajConvFunction', 'TrajConv']
StarcoderdataPython
190760
# -*- coding: utf-8 -*- __author__ = "<NAME>" __copyright__ = "<NAME>" __license__ = "mit"
StarcoderdataPython
93771
<filename>#Cyber Track's.py #Cyber Track's #modulos import sys import time import socket import random import os #codigo de tiempo from datetime import datetime now = datetime.now() year = now.year day = now.day hour = now.hour minute = now.minute month = now.month #colores G = "\033[16m" D = "\033[16m" T = "\033[39m"...
StarcoderdataPython
1758619
<gh_stars>100-1000 import argparse import logging import os from credentialdigger import PgClient, SqliteClient from dotenv import load_dotenv from . import (add_rules, get_discoveries, scan, scan_path, scan_snapshot, scan_user, scan_wiki) logger = logging.getLogger(__name__) class customParser(argp...
StarcoderdataPython
83963
<reponame>AndreFCruz/scikit-multiflow<filename>src/skmultiflow/drift_detection/ddm.py import numpy as np from skmultiflow.drift_detection.base_drift_detector import BaseDriftDetector class DDM(BaseDriftDetector): """ DDM method for concept drift detection Parameters ---------- min_num_instances: ...
StarcoderdataPython
1745439
# -*- coding: utf-8 -*- from __future__ import absolute_import import unittest from datetime import datetime from pytz import UTC from bqdm.model.dataset import BigQueryAccessEntry, BigQueryDataset from bqdm.model.schema import BigQuerySchemaField from bqdm.model.table import BigQueryTable from bqdm.util import dump...
StarcoderdataPython
62514
<reponame>hayribakici/mopidy-beep<filename>mopidy_beep/__init__.py<gh_stars>0 ''' Mopidy Beep Python module. ''' import os import mopidy __version__ = '0.1' class Extension(mopidy.ext.Extension): ''' Mopidy Beep extension. ''' dist_name = 'Mopidy-Beep' ext_name = 'beep' version = __version_...
StarcoderdataPython
3281131
<filename>pabot/execution_items.py from functools import total_ordering from robot import __version__ as ROBOT_VERSION from robot.errors import DataError from robot.utils import PY2, is_unicode from typing import List, Optional, Union, Dict, Tuple @total_ordering class ExecutionItem(object): isWait = False ...
StarcoderdataPython
102280
from .base import ResourceRecord from ..domains.domain import Domain class PTR(ResourceRecord): class _Binary(ResourceRecord._Binary): @property def full(self): return self.resource_record.ptrdname.binary_raw id = 12 repr = ['ptrdname'] @classmethod def parse_bytes(...
StarcoderdataPython
3325222
<gh_stars>10-100 # flake8: noqa 501 # Disable flake8 line-length check (E501), it makes this file harder to read import struct from .exceptions import UnknownTagError class TiffConstant(int): def __new__(cls, value, *args, **kwargs): return super().__new__(cls, value) def __init__(self, value, cons...
StarcoderdataPython
3346268
#!/usr/bin/env python3 #coding: utf-8 import licant import licant.install from licant.cxx_modules import application from licant.libs import include import os defines = ["NOTRACE=1"] licant.libs.include("crow") application("crowrequest", sources = [ "main.cpp" ], mdepends=["crow", "crow.udpgate"], defines = ...
StarcoderdataPython
1616007
from __future__ import annotations import asyncio import typing from ctc import spec from ... import management from ... import connect_utils from ... import intake_utils from . import blocks_statements from ..block_timestamps import block_timestamps_statements async def async_intake_block( block: spec.Block, ...
StarcoderdataPython
1618722
<reponame>noironetworks/apic-ml2-driver # Copyright (c) 2017 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.o...
StarcoderdataPython
154386
##==============================================================# ## SECTION: Imports # ##==============================================================# import io import sys import os.path as op import auxly.filesys as fsys import qprompt import requests ##===============...
StarcoderdataPython
3381338
<reponame>PythonDataIntegrator/pythondataintegrator from injector import inject from sqlalchemy import func from sqlalchemy.orm import Query from domain.common.specifications.OrderBySpecification import OrderBySpecification from infrastructure.data.RepositoryProvider import RepositoryProvider from infrastructure.depen...
StarcoderdataPython
3240533
<filename>code/sentence_embedding_with_bert_ranking.py ''' Rank the entities based on the sentence similary Steps 1. Load sentence embedding first >> DONE 2. Read the settings file and process it >> DONE 3. Do embedding of question q >> TRIVIAL 4. Do embedding of sentences containing the entities >> WIP 5. Do core...
StarcoderdataPython
3354613
# Modifications Copyright 2022 Tau # Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn class GlobalAveragePooling(nn.Module): """Global Average Pooling neck. Note that we use `view` to remove extra channel after pooling. We do not use `squeeze` as it will also remove the bat...
StarcoderdataPython
3260283
<filename>Implement Trie (Prefix Tree).py class TrieNode: def __init__(self): self.next = {} self.isWord = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): n = self.root for w in word: if w not in n.next: ...
StarcoderdataPython
158001
from sunrisePy import sunrisePy import time import numpy as np ip='172.31.1.148' # ip='localhost' iiwa=sunrisePy(ip) iiwa.setBlueOn() time.sleep(2) iiwa.setBlueOff() try: while True: print(iiwa.getJointsMeasuredTorques()) time.sleep(0.2) except KeyboardInterrupt: iiwa.close() print('an error ...
StarcoderdataPython
1776496
<filename>demo/scripts/shot.py #!/usr/bin/env python """ Recreate tcl script in python 'scripts/shot.tcl' ============== set verify set tree demo set current demo 0 set current demo /increment create pulse 0 set tree demo /shot=0 dispatch /build /monitor=MONITOR dispatch /phase init /monitor=MONITOR """ import MDSpl...
StarcoderdataPython
1610090
<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: from netCDF4 import Dataset, num2date import numpy as np import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as crs from wrf import getvar, get_cartopy, latlon_coords, to_np, cartopy_xlim, cartopy_ylim import pprint import pandas as pd im...
StarcoderdataPython
1684997
#!/usr/bin/env python from collections import defaultdict import itertools def manhattan(a, b=itertools.repeat(0)): return sum([abs(a-b) for a, b in zip(a, b)]) def solve(input): wire1, wire2 = input wire1 = wire1.split(',') wire2 = wire2.split(',') grid = defaultdict(lambda: '.') pos = (0...
StarcoderdataPython
3316215
# import necessary libraries import pandas_datareader as web import pandas as pd import matplotlib.pyplot as plt import numpy as np from datetime import date import optimal_portfolio as opt_func import return_portfolios as ret_port_func import scipy.stats as stats import seaborn as sns import cvxopt as opt ...
StarcoderdataPython
1742777
<reponame>cdgriffith/darkroom #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from threading import Thread from gpiozero import OutputDevice class Enlarger(OutputDevice): def __init__(self, pin): super(Enlarger, self).__init__(pin, initial_value=True) self.printing = False self...
StarcoderdataPython
1751573
# -*- coding: utf-8 -*- # """WLSQM (Weighted Least SQuares Meshless): a fast and accurate meshless least-squares interpolator for Python, for scalar-valued data defined as point values on 1D, 2D and 3D point clouds. A general overview can be found in the README. For the API, refer to wlsqm.fitter.simple and wlsqm....
StarcoderdataPython
21885
import atrlib import pandas as pd # module for calculation of data for renko graph def renko(df): d , l , h ,lbo ,lbc,vol=[],[],[],[],[],[] brick_size = atrlib.brick_size(df) volume = 0.0 for i in range(0,len(df)): if i==0: if(df['close'][i]>df['open'][i]): d.append(...
StarcoderdataPython
1748584
<reponame>khakhulin/DeepPavlov<filename>deeppavlov/deep.py<gh_stars>0 """ Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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.a...
StarcoderdataPython
3277402
## PRINTING A SINGLE CUSTOM CHARACTER ''' Take a look at this code, which prints a single smiley face character to the display: ''' from RPLCD import CharLCD, cleared, cursor # This is the library which we will be using for LCD Display from RPi import GPIO # This is the library which we will ...
StarcoderdataPython
3283503
<filename>openmdao/components/multifi_meta_model.py """Define the MultiFiMetaModel class.""" import numpy as np from openmdao.components.meta_model import MetaModel def _get_name_fi(name, fi_index): """ Generate variable name taking into account fidelity level. Parameters ---------- name : str ...
StarcoderdataPython
1694801
from tests import app @app.route("/error-assert-newline") def error_assert_newline(): return '<p>Hello</p>\n\n'
StarcoderdataPython
38642
""" Solution of the Sellar analytical problem using classic BLISS. (Bi-Level Integrated System Synthesis) MDA solved with a Broyden solver. Global sensitivity calculated by finite-differencing the MDA-coupled system. The MDA should be replaced with solution of the GSE to fully match the ori...
StarcoderdataPython
1676302
<filename>bacteria_selection.py # coding: utf-8 import pandas as pd import os import requests from GOTool.GeneOntology import GeneOntology import pickle DATA_DIRECTORY = '../../../data/bacteria_selection/' GOA_DIRECTORY = DATA_DIRECTORY + 'selection_goa/' if os.path.exists(DATA_DIRECTORY+'proteomes_df.pkl'): prot...
StarcoderdataPython
3247894
# avax-python : Python tools for the exploration of the Avalanche AVAX network. # # Find tutorials and use cases at https://crypto.bi """ Copyright (C) 2021 - crypto.bi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), t...
StarcoderdataPython
75631
<reponame>Kieran-Bacon/Expert-Opinions-Vegetation-Change<gh_stars>0 """ Implements the ModelFile class for use with NetCDF files. """ import warnings import numpy as np from netCDF4 import Dataset from ExpertRep.abstract.ClimateEvalAPI import ModelFile from ExpertRep.tools.geojson_gen import dict_to_geojson class N...
StarcoderdataPython
1660872
from .settings import * PROJECT_APPS = [ 'users.apps.UsersConfig', ] INSTALLED_APPS += [] + PROJECT_APPS AUTH_USER_MODEL = 'users.User'
StarcoderdataPython
3288343
import errno, os, inspect def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise return path def touch(file_path): open(file_path, 'a').close() def to_unix_p...
StarcoderdataPython
3247083
from django.contrib import admin from .models import DeferredAction admin.site.register(DeferredAction, list_display=('token', 'valid_until', 'confirmed', 'is_expired'))
StarcoderdataPython
3207601
class Student: def __init__(self, std): self.count = std def go(self): for i in range(self.count): print(i) return if __name__ == '__main__': Student(5).go()
StarcoderdataPython
1697793
<gh_stars>10-100 # Load prepared track metadata and features REQUIRED_GENRE = None #'Electronic' import pickle with open('tracks_metadata.pkl', 'rb') as f: tracks_metadata = pickle.load(f) with open('track_features.pkl', 'rb') as f: track_features = pickle.load(f) all_tracks = list(tracks_metadata.keys()) d...
StarcoderdataPython
189008
<filename>src/sca3s/backend/acquire/scope/__init__.py<gh_stars>0 # Copyright (C) 2018 SCARV project <<EMAIL>> # # Use of this source code is restricted per the MIT license, a copy of which # can be found at https://opensource.org/licenses/MIT (or should be included # as LICENSE.txt within the associated archive or re...
StarcoderdataPython
76617
import pickle import pathlib import numpy as np from bci3wads.utils import constants class Epoch: def __init__(self, signals, flashing, stimulus_codes, stimulus_types, target_char): self.n_channels = signals.shape[1] self.signals = signals self.flashing = flashing ...
StarcoderdataPython
1611801
<reponame>armedturret/print-oops-AUV from . import ash from . import grm from . import kwd from . import mgn from . import rdi from . import srf from . import sxn from . import tnl from . import ubx from . import vtx from . import nor
StarcoderdataPython
1755267
<filename>SEE/Scripting/2/2b/2b.py import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns student_df = pd.read_csv("StudentsPerformance.csv") print("======Data Headers=======") student_df.head() print("=====Data Decription=====") student_df.i...
StarcoderdataPython
1629855
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import zipfile from zipfile import ZipFile zip_file = 'myfile.zip' with ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zf: # 默认待添加的文件的mtime不能早于1980年 for root, dirs, files in os.walk('conf.d'): for file in files: zf.write(os.path.jo...
StarcoderdataPython
177945
from django.contrib.auth import get_user_model from rest_framework import serializers from knox.models import AuthToken User = get_user_model() username_field = User.USERNAME_FIELD if hasattr(User, 'USERNAME_FIELD') else 'username' class UserSerializer(serializers.ModelSerializer): class Meta: model = Us...
StarcoderdataPython
3360452
# Asignatura: Inteligencia Artificial (IYA051) # Grado en Ingeniería Informática # Escuela Politécnica Superior # Universidad Europea del Atlántico # Caso Práctico (CE_Práctica_01) # En esta práctica se busca el máximo de una función utilizando computación evolutiva # Se utiliza un algoritmo genético # Impor...
StarcoderdataPython
1746516
<filename>tests/test_api.py<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `mlbench_core.api` package.""" import datetime import pytest from mlbench_core.api import ApiClient @pytest.fixture def kubernetes_api_client_node_port(mocker): mock_client = mocker.patch("kubernetes.client....
StarcoderdataPython
3329628
# -*- coding: utf-8 -*- from scrapy.selector import Selector from ..items import BaseItem, ImageItem, SkuItem, Color from scrapy import Request, FormRequest import re import execjs from ..spiders.shiji_base import BaseSpider from urllib import quote class TjzmallSpider(BaseSpider): name = "tjzmall" allowed_d...
StarcoderdataPython
3221610
<filename>vs_utils/features/nnscore.py """ The following code implements a featurizer based on NNScore 2.0.1 ## The following notice is copied from the original NNScore file. # NNScore 2.01 is released under the GNU General Public License (see # http://www.gnu.org/licenses/gpl.html). # If you have any questions, comme...
StarcoderdataPython
1618482
<reponame>lucianogsilvestri/sarkas<filename>setup.py import glob import os import setuptools import sys from configparser import ConfigParser from setuptools.command.develop import develop from setuptools.command.install import install # The following are needed to copy the MSU plot styles in Matplotlib folder # From...
StarcoderdataPython
3221144
#@jacksontenorio8 """Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua média""" n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = float((n1 + n2) / 2) print('A média entre {} e {} é igual a {:.2f}.'.format(n1, n2, m))
StarcoderdataPython
1785451
<reponame>water-law/waterlawblog # -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2019-10-15 13:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depe...
StarcoderdataPython
1771193
from rest_framework.exceptions import APIException, ValidationError, NotFound class ExternalAPIError(APIException): def __init__(self, detail=None, code=None): APIException.__init__(self, detail=None, code=None) if detail is None: self.detail = {'error_code': 1100, 'message': "External...
StarcoderdataPython
3393205
from django.urls import path, re_path import had.app.views.api.v1.persons as api_persons app_name = "app" urlpatterns = [] urlpatterns = [ re_path( r"^persons(/(?P<id>[\w-]+))?/?$", api_persons.PersonApi.as_view(), name="user_api" ) ]
StarcoderdataPython
3349709
from random import randint def generate_account_number (): number = '' for d in range (8): number += str (randint (0, 10)) return number if __name__ == '__main__': print (generate_account_number())
StarcoderdataPython
3256260
from setuptools import setup version = '1.1.1' with open('requirements.txt') as requirements: install_requires = requirements.read().split() setup( name='pyfrappeclient', version=version, author='<NAME>', author_email='<EMAIL>', packages=[ 'frappeclient' ], install_requires=in...
StarcoderdataPython
97150
""" Pylibui test suite. """ from pylibui.controls import Group, Control from tests.utils import WindowTestCase class GroupTest(WindowTestCase): def setUp(self): super().setUp() self.group = Group('my group') def test_title_initial_value(self): """Tests the group's `title` initial v...
StarcoderdataPython
149219
<reponame>Who8MyLunch/WanderBits<gh_stars>0 #!/usr/bin/python from __future__ import division, print_function, unicode_literals import os import unittest from context import wanderbits class Test_Things(unittest.TestCase): def setUp(self): path_module = os.path.dirname(os.path.abspath(__file__)) ...
StarcoderdataPython