id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1689671
import logging import requests import scrapy from news_spider.items import ToutiaoItem from news_spider.utils.common import get_category_by_name class ToutiaoSpider(scrapy.Spider): name = 'toutiao' allowed_domains = ['www.toutiao.com'] start_urls = [ 'https://www.toutiao.com/api/pc/list/feed?cha...
StarcoderdataPython
54020
<reponame>keelerm84/antidote<gh_stars>0 import typing import pytest from antidote._internal.argspec import Arguments from antidote.core import DependencyContainer, inject from antidote.exceptions import DependencyNotFoundError class Service: pass class AnotherService: pass @pytest.mark.parametrize( ...
StarcoderdataPython
3328735
"""empty message Revision ID: f4b8232fa17e Revises: 0809266d08ca Create Date: 2020-03-20 09:41:21.840221 """ import sqlalchemy_utils from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "0809266d08ca" branch_labels = None depends_on = None def ...
StarcoderdataPython
77894
<reponame>DrakeAxelrod/cybersecurity-association-discord-bot<gh_stars>10-100 import asyncio import os from discord.embeds import Embed from dotenv import load_dotenv import discord from discord.ext import commands, tasks from datetime import datetime import logging logger = logging.getLogger('discord') logger.setLevel...
StarcoderdataPython
1796581
<gh_stars>1-10 """ Builds a longuage model to estimate the liklihood of any sentence """ import os import argparse import pickle from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential, load_model from keras.layers import Embedding, LSTM, Dense, Activation, Dropout from keras.callb...
StarcoderdataPython
12022
<gh_stars>0 # Copyright 2020 OpenRCA 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 # # Unless required by applicable law or agreed...
StarcoderdataPython
35877
<reponame>Lesson-ThienHi/thienhi_shop from datetime import datetime def format_time_filter(): start_time = datetime.now().utcnow().replace(hour=0, minute=0, second=0, microsecond=0).timestamp() end_time = datetime.utcnow().replace(second=0, microsecond=0).timestamp() data = { "start_time": start_ti...
StarcoderdataPython
1643774
<gh_stars>1-10 """ _________________________100. Same Tree_________________________ Difficulty: Easy Likes: 2305 Dislikes: 65 Solution: Available Total Accepted: 592.6K Total Submission: 1.1M Acceptance Rate: 53.4% Tags: Tree, Depth-first Search Given two binary trees, write a function to check if they a...
StarcoderdataPython
106120
''' BITONIC POINT Given an array. The task is to find the bitonic point of the array. The bitonic point in an array is the index before which all the numbers are in increasing order and after which, all are in decreasing order. ''' def bitonic(a, n): l = 1 r = n - 2 while(l <= r): m = (l + r) // 2...
StarcoderdataPython
1752063
#!/usr/bin/env python3 # Copyright (c) 2019, <NAME> # All rights reserved. import argparse import os import re import shutil import tempfile import git # Returns False if there was an error. def checkPackageName(queriedPackageName, performFix=False): if not queriedPackageName: print("You must specify a packag...
StarcoderdataPython
1767484
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 15:07:01 2013 @author: steve """ import numpy as np import mdptoolbox from .utils import SMALLNUM, P_forest, R_forest, P_forest_sparse from .utils import R_forest_sparse, P_rand, R_rand, P_rand_sparse, R_rand_sparse from .utils import P_small, R_small, P_sparse def...
StarcoderdataPython
1606105
import csv import cv2 import numpy as np import math import tensorflow as tf import time from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from keras.preprocessing.image import ImageDataGenerator from keras import regularizers from keras.models import Sequential from keras.layers i...
StarcoderdataPython
1722931
from counter_attack.tests.accuracy import accuracy_test from counter_attack.tests.adversarial_perturbation import adversarial_perturbation_test from counter_attack.tests.attack import attack_test from counter_attack.tests.boundary_distance import boundary_distance_test from counter_attack.tests.parallelization import p...
StarcoderdataPython
3377070
#!/usr/bin/env python import codecs from datetime import datetime import gspread import json from oauth2client.client import GoogleCredentials import os from pymongo import MongoClient import re from dateutil import parser projects_SHEET_KEY = '<KEY>' MONGODB_URL = os.getenv('MONGODB_URL', 'mongodb://127.0.0.1:3001/m...
StarcoderdataPython
3258281
<reponame>WhackoJacko/Jetee import re import paramiko from jetee.runtime.configuration import project_configuration class ServiceDiscoverer(object): def __init__(self, container_name): self.container_name = container_name def extract_port(self, raw_string): res = re.compile(u'.*:(\d+)->22/t...
StarcoderdataPython
1408
from django.urls import path from .views import ProfileView urlpatterns = [ path('', ProfileView.as_view(), name='user-profile'), ]
StarcoderdataPython
20791
<filename>holobot/framework/kernel.py from holobot.framework.lifecycle import LifecycleManagerInterface from holobot.sdk import KernelInterface from holobot.sdk.database import DatabaseManagerInterface from holobot.sdk.integration import IntegrationInterface from holobot.sdk.ioc.decorators import injectable from holobo...
StarcoderdataPython
13857
import requests from custom.api.utils import EndpointMixin class MigrationException(Exception): pass class LogisticsEndpoint(EndpointMixin): models_map = {} def __init__(self, base_uri, username, password): self.base_uri = base_uri.rstrip('/') self.username = username self.passw...
StarcoderdataPython
1660497
import torch from typing import List from torch.distributions import Normal from torch.optim.lr_scheduler import StepLR from torch.optim import Optimizer from torch.nn.functional import mse_loss, softplus from torch.distributions.kl import kl_divergence from alfi.nn import LpLoss from alfi.utilities.torch import is_...
StarcoderdataPython
4293
<reponame>ZhenghengLi/lcls2 """Class :py:class:`QWTable` is a QTableView->QWidget for tree model ====================================================================== Usage :: # Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py from psdaq.control_gui.QWTable import QWTable w = QWTable() Create...
StarcoderdataPython
1767276
<reponame>ismailalmahdi/ST22639<gh_stars>0 __author__ = "<NAME> ST22639" __copyright__ = "Copyright 2018-2019, UNITEN" import os from socket import * serverIP = '127.0.0.1' serverPort = 9999 serverSocket = socket(AF_INET,SOCK_STREAM) serverSocket.bind((serverIP,serverPort)) serverSocket.listen(1) #read file a...
StarcoderdataPython
4812505
class KubeException(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class KubeHTTPException(KubeException): def __init__(self, response, errmsg, *args, **kwargs): self.response = response data = response.json() message = data['message...
StarcoderdataPython
83867
import sys from .helper import cli sys.exit(cli())
StarcoderdataPython
3290347
<gh_stars>1-10 """ Factory functions providing timed loop objects to user. """ from __future__ import absolute_import from gtimer.private.timedloop import TimedLoop, TimedFor from gtimer.public.timer import SET __all__ = ['timed_loop', 'timed_for'] def timed_loop(name=None, rgstr_stamps=None, ...
StarcoderdataPython
43447
# vim: sw=4:ts=4:et from flask import Blueprint main = Blueprint('main', __name__) from . import views, errors
StarcoderdataPython
4820662
<filename>api/graphql/tests/test_terms_of_use.py import json import snapshottest from assertpy import assert_that from api.graphql.tests.base import GrapheneTestCaseBase from terms_of_use.models import TermsOfUse from terms_of_use.tests.factories import TermsOfUseFactory class TermsOfUseQueryTestCase(GrapheneTestCa...
StarcoderdataPython
4831846
<gh_stars>0 import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), "../.env") load_dotenv(dotenv_path) NEXMO_API_KEY = os.getenv("NEXMO_API_KEY") NEXMO_API_SECRET = os.getenv("NEXMO_API_SECRET") TO_NUMBER = os.getenv("TO_NUMBER") import nexmo client = nexmo....
StarcoderdataPython
1709848
# Licensed under a 3-clause BSD style license - see LICENSE.rst from ... import irsa import numpy as np import distutils.version as dv import pytest # this just wrong. give up. # @pytest.mark.skipif(dv.StrictVersion(np.__version__) <= dv.StrictVersion("1.4.1")) # def test_trivial(): # """ just make sure it doesn...
StarcoderdataPython
3293983
<gh_stars>1-10 # -------------------------------------------------------- # Deep Iterative Matching Network # Licensed under The Apache-2.0 License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- from __future__ import print_function, division import sys import ...
StarcoderdataPython
3271711
# Copyright 2019 Illumio, 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 required by applicable law or agreed t...
StarcoderdataPython
120127
import sys import os import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), 'pathfind/build')) from alphazero_general.Game import Game from .QuoridorLogic import QuoridorBoard class QuoridorGame(Game): def __init__(self, n): super().__init__() self.n = n self.action_...
StarcoderdataPython
135241
from __future__ import unicode_literals import logging from django.contrib.contenttypes import generic as ct_generic from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator, URLValidator from django.db import models from django.utils.encoding import p...
StarcoderdataPython
26981
<gh_stars>1-10 # -*- coding: utf-8 -*- """ PaperPlane: a very simple, flat-file, static blog generator. Created on Sat Feb 21 2015 Author: <NAME> """ import codecs, unicodedata import dateutil.parser import os, re, glob import markdown import jinja2 class Page: def __init__(self, markdown_file): self._rea...
StarcoderdataPython
1699964
#!/usr/bin/env python3 def detect_ranges(L): """This functions sorts the given list and returns a transformed list where pairs are used for all the detected intervals""" l = sorted(L) ans = list() start = -1 inside = False ans.append(l[0]) for i in range(1, len(l)): if l[i] == l...
StarcoderdataPython
56883
"""The controller subpackage exposes the main components of the controller. This includes the IOController class itself, but also the classes it uses, like the Authenticator and the JSONResultValidator."""
StarcoderdataPython
3353735
import asyncio import datetime import helo db = helo.G() class Person(helo.Model): id = helo.BigAuto() name = helo.VarChar(length=45, null=False) class Employee(Person): department = helo.Smallint() salary = helo.Float(default=0) class User(Person): email = helo.Email(default='') passwo...
StarcoderdataPython
1649159
<gh_stars>0 #!/usr/bin/env python # coding:utf-8 from __future__ import unicode_literals import traceback import time import json import api_funcs as af import config as ac gen = { 'snapshot_id': "", 'image_id': "", 'instance_id': "", 'ip': "", } def start(disk_id): # 1. 创建快照: 如 69 python 系统盘 ...
StarcoderdataPython
1686175
<reponame>najiji/macpack import argparse import asyncio import re import pathlib import subprocess import re import os import sys class Dependency: def __init__(self, reference, file_path): self.path = file_path self.referred_as = {str(reference)} self.dependencies = [] self.rpaths...
StarcoderdataPython
1825
def construct_tag_data(tag_name, attrs=None, value=None, sorting=None): data = { '_name': tag_name, '_attrs': attrs or [], '_value': value, } if sorting: data['_sorting'] = sorting return data def add_simple_child(data, child_friendly_name, child_tag_name, child_attr...
StarcoderdataPython
55235
# Generated by Django 2.2.1 on 2019-06-02 18:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('daauth', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='permissionsmixin', options={}, ...
StarcoderdataPython
3396535
from __future__ import division import glob, os from dxtbx.model.experiment_list import ExperimentListFactory from libtbx import easy_pickle try: import resource import platform def get_memory_usage(): # getrusage returns kb on linux, bytes on mac units_per_mb = 1024 if platform.system() == "Darwin":...
StarcoderdataPython
1610503
# -*- coding: utf-8 -*- # # <NAME> # orthologue # (c) 1998-2021 all rights reserved # # triangulated surfaces def surface(**kwds): """ Create a surface """ # get the factory from .Surface import Surface # make one and return it return Surface(**kwds) # logically cartesian grids def grid(...
StarcoderdataPython
4829924
__all__ = ['AstroDataHokupaaQUIRC'] from astrodata import factory from .adclass import AstroDataHokupaaQUIRC factory.addClass(AstroDataHokupaaQUIRC)
StarcoderdataPython
1784738
<reponame>danx0r/mongo """Extension to the unittest package to support buildlogger and parallel test execution.""" from __future__ import absolute_import from . import executor from . import suite
StarcoderdataPython
27699
from typing import ( NamedTuple, ) from lahja import ( BaseEvent, ) class RawMeasureEntry(NamedTuple): sent_at: float received_at: float class CrunchedMeasureEntry(NamedTuple): sent_at: float received_at: float duration: float class PerfMeasureEvent(BaseEvent): def __init__(self,...
StarcoderdataPython
3232544
import imgaug as ia from imgaug import augmenters as iaa import numpy as np import random brightness = iaa.Add((-7, 7), per_channel=0.5) contrast = iaa.ContrastNormalization((0.8, 1.6), per_channel=0.5) perspective = iaa.PerspectiveTransform(scale=(0.025, 0.090)) gaussian_noise = iaa.AdditiveGaussianNoise(loc=0, scal...
StarcoderdataPython
174805
<gh_stars>0 from rest_framework.exceptions import ParseError, PermissionDenied from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework.permissions import IsAuthenticated from api.models import Account, AmountOwing, Contact from api.util...
StarcoderdataPython
3316552
<filename>application/routers/biospecimens.py """VBR Biospecimen routes""" from typing import Dict from fastapi import APIRouter, Body, Depends, HTTPException from vbr.api import VBR_Api, measurement from vbr.utils.barcode import generate_barcode_string, sanitize_identifier_string from application.routers.models.acti...
StarcoderdataPython
1783700
<reponame>handyc/openphilology.eu from django.urls import path, re_path from django.conf.urls import url from django.contrib import admin #from django.contrib.auth import views as auth_views #from django.conf.urls.defaults import * #from optools.models import Note from . import views #notes = Note.objects.all() ur...
StarcoderdataPython
3326790
"""Utils for connecting comics series and publishers.""" import enum class Publishers(enum.Enum): """A list of publishers.""" MARVEL_COMICS = enum.auto() DC_COMICS = enum.auto() DCS_YOUNG_ANIMAL = enum.auto() VERTIGO = enum.auto() DARK_HORSE = enum.auto() IDW_PUBLISHING = enum.auto() ...
StarcoderdataPython
1670739
#!/usr/bin/python ''' Author: <NAME> Contact: <EMAIL> This file contains the contents for the server-side queries that complement "msMassQuery". The main function is to perform many queries on the same dataset and report all of the results back to the client. This is done and batches and this code handles the countin...
StarcoderdataPython
73493
from tkinter import * class Carinha: def __init__(self, raiz): self.root = raiz self.canvas=Canvas(self.root, height=200, width=200, takefocus=1, bg='deepskyblue', highlightthickness=0) self.canvas.focus_force() self.canvas.pack() # Desenho da carinha--------------...
StarcoderdataPython
152030
<filename>usr/lib/enigma2/python/Plugins/SatLodge/HistoryZapSelector/HistoryZap.py<gh_stars>0 # -*- coding: utf-8 -*- from . import _ from Screens.Screen import Screen from Screens.EventView import EventViewSimple from Screens.EpgSelection import EPGSelection from Screens.MessageBox import MessageBox from Components.Ac...
StarcoderdataPython
1612691
<gh_stars>0 import tempfile import pytest from noos_inv import utils @pytest.fixture def path(): with tempfile.TemporaryDirectory() as dir_name: yield dir_name class TestCheckPath: def test_invalid_path_raises_error(self): with pytest.raises(utils.PathNotFound): utils.check_pat...
StarcoderdataPython
1677119
"""Implements functionality unique to the Lake Shore Model 335 cryogenic temperature controller""" from enum import IntEnum from .temperature_controllers import TemperatureController, InstrumentException from .temperature_controllers import RelayControlMode, RelayControlAlarm, InterfaceMode, HeaterError, \ CurveFo...
StarcoderdataPython
1716989
from datetime import datetime from api.main import db, ma, bcrypt # Alias common SQLAlchemy names Column = db.Column Model = db.Model relationship = db.relationship roles_users = db.Table( "roles_users", Column("user_id", db.Integer, db.ForeignKey("user.id")), Column("role_id", db.Integer, db.ForeignKey(...
StarcoderdataPython
3392994
# -*- coding: utf-8 -*- """ Created on Mon Sept 12 16:35:13 2019 @author: <NAME> """ from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal class Matlab_treat(QObject): matlabGUI_treatphase_signal = pyqtSignal(int, int, int, str) test_GUI_signal = pyqtSignal() show_instance_signal = pyqtSignal() ...
StarcoderdataPython
1721330
<gh_stars>10-100 """ Problem Difficulty: [Medium] Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C, replace the color of the given pixel and all adjacent same colored pixels with C. For example, given the following matrix, and location pixel of (2, 2), and 'G' for green: B...
StarcoderdataPython
1721355
<reponame>tencentmusic/fab<filename>install/upgrade/server.py from flask import render_template from flask import Flask,request import logging app = Flask(__name__) @app.route('/') def index(): logging.info('>>>>>>>>>>>>>') ip = request.remote_addr print(ip) logging.info(ip) logging.info('<<<<<<...
StarcoderdataPython
3311242
<filename>reservoir_nn/models/transformer_test.py # Copyright 2021 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
StarcoderdataPython
1655676
""" Shapes ------ Utility functions to generate different shapes. """ from typing import List import numpy as np from plofeld.utils.classes import Vector from plofeld.elements import PointCharge def get_regular_polygon(n: int, skew: bool = False, r: float = 1) -> List[Vector]: """Generate the coordinates for a...
StarcoderdataPython
1745465
<reponame>ajmal017/amp #!/usr/bin/env python r""" Run a single DAG model wrapping # Use example: > run_notebook_stub.py \ --dst_dir nlp/test_results \ --experiment_builder "core.dataflow_model.master_experiment.run_experiment" \ --config_builder "nlp.build_configs.build_PTask1088_configs()" \ --num_thr...
StarcoderdataPython
2554
from io import BytesIO from io import StringIO import json from bson.dbref import DBRef import datetime from bson import json_util import logging import base64 jsonCode ={ "building":{ "Essae Vaishnavi Solitaire": { "id": "B1", "division": { "SS"...
StarcoderdataPython
3388786
<gh_stars>1-10 from django.conf import settings from django.db import models from django.utils.translation import gettext_lazy as _ from djangocms_versioning.models import Version class VersionLock(models.Model): created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( settin...
StarcoderdataPython
3260738
#!/usr/bin/env python3 """Check for uniqueness in set.""" def all_unique(lst): """Return whether list contains unique elements.""" return len(lst) == len(set(lst)) X = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6] Y = [1, 2, 3, 4, 5] print(all_unique(X)) print(all_unique(Y))
StarcoderdataPython
3297170
from abc import ABC from typing import Any from parseridge.utils.logger import LoggerMixin class EvalCallback(LoggerMixin, ABC): _order = 0 def on_initialization(self, **kwargs: Any) -> None: pass def on_eval_begin(self, **kwargs: Any) -> None: pass def on_epoch_begin(self, **kwarg...
StarcoderdataPython
1627569
import nltk from nltk.stem.porter import PorterStemmer # All the available stemmers #from nltk.stem.api import StemmerI #from nltk.stem.regexp import RegexpStemmer #from nltk.stem.lancaster import LancasterStemmer #from nltk.stem.isri import ISRIStemmer #from nltk.stem.snowball import SnowballStemmer #from nltk.stem....
StarcoderdataPython
1684340
<reponame>arbakker/geo-snake #!/usr/local/bin/python3 """create_gwc_wms_layer_geoserver.py: create GWC tile layer in GeoServer based on WMS source""" from urllib3.exceptions import ProtocolError import argparse import requests from sys import exit import xml.etree.ElementTree as ET import http.client from util import *...
StarcoderdataPython
3205416
class Config: DELAY_DEALER = 1
StarcoderdataPython
1629126
<filename>embiggen/embedders/tensorflow_embedders/first_order_line.py """First order LINE TensorFlo model.""" from typing import Union, List import tensorflow as tf import pandas as pd from ensmallen import Graph from tensorflow.keras.layers import ( # pylint: disable=import-error,no-name-in-module Dot, Embedding...
StarcoderdataPython
1675284
"""Generate traditional spatial folds""" import os import time from dataclasses import dataclass, field import pandas as pd import numpy as np from tqdm import tqdm import geostatspy.geostats as geostats from scipy.spatial.distance import cdist from src.scv.scv import SpatialCV ULTRACONSERVATIVE = "TraditionalSCV" @...
StarcoderdataPython
4831806
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from uwhoisd.helpers import get_homedir, check_running from subprocess import Popen import time from pathlib import Path from typing import Optional, List, Union import argparse def launch_cache(storage_directory: Optional[Path]=None) -> None: if not storage_direct...
StarcoderdataPython
163142
############################# #### QR Code Generator ###### ############################# import qrcode import cv2 qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) f = open("am_decoded.txt","r") lines = f.readlines() s = "" for line in lines: ...
StarcoderdataPython
132669
import re from cli.export import api_to_dict def _cli_to_schema( api_dict, target, ): pod_api = None for d in api_dict['methods']: if d['name'] == target: pod_api = d['options'] break _schema = { 'properties': {}, 'required': [], } for p ...
StarcoderdataPython
139186
import pathlib from src import misc from src.usermod_funcs import login,makenewaccount,deleteaccount,changepassword,changename import json fullpath = str(pathlib.Path(__file__).parent.absolute())+"/data.json" def parse(user_input): with open(fullpath,"r") as JsonFile: data = json.load(JsonFile) safety ...
StarcoderdataPython
1625658
<reponame>preym17/csit #!/usr/bin/env python # Copyright (c) 2016 Cisco and/or its affiliates. # 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
154642
import torch.nn as nn import torch class Yolo_v2(nn.Module): def __init__(self, num_classes=3, num_boxes=5): super(Yolo_v2, self).__init__() self.num_classes = num_classes self.num_boxes = num_boxes # First Stage self.layer_1 = nn.Sequential(nn.Conv2d(3, 32, 3, 1, 1, bias=False), nn.BatchNorm2d(...
StarcoderdataPython
1749198
<reponame>bmiller/beqdesigner # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'browse_catalogue.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are ...
StarcoderdataPython
1617880
#!/usr/bin/env pytest import numpy as np import pytest import siglib as sl @pytest.mark.parametrize( "x,frame_length,frame_step,pad,pad_value,expected", ( (np.arange(10), 5, 5, True, 0j, np.arange(10, dtype=np.complex).reshape(2, 5)), (np.arange(10), 5, 5, False, 0j, np.arange(10, dtype=np.comp...
StarcoderdataPython
1643752
<gh_stars>0 def permute(nums): """return all possible permutation of a list""" all_permutation = [] return all_permutation def get_(l): if len(l) == 1: return l elif len(l) == 2: return l[::-1] else: nl = l[:-2] nl.append(l[:-1]) nl.append(l[:-2]) ...
StarcoderdataPython
1781506
#!/usr/bin/env python # -*- coding: utf-8 -*- # convert modhmm xml output file into txt file import sys,re,os; # Note 2010-08-26, This code is obsolete now, use the xslt still, but split the # fasta sequence into smaller pieces if it is too big. # the xml file should be read in by better languages to avoid errors. # ...
StarcoderdataPython
3239495
<gh_stars>0 import re from util import Events from AbstractPlugin import AbstractPlugin class Plugin(AbstractPlugin): def __init__(self, pm): super().__init__(pm, "Temperature") self.match = re.compile(r"\-?\d*\.?\d+") @staticmethod def register_events(): return [Eve...
StarcoderdataPython
1792980
<gh_stars>100-1000 from __future__ import division, print_function, absolute_import # rename() ########## import petl as etl table1 = [['sex', 'age'], ['m', 12], ['f', 34], ['-', 56]] # rename a single field table2 = etl.rename(table1, 'sex', 'gender') table2 # rename multiple fields by...
StarcoderdataPython
3219885
<filename>ansible/lib/ansible/utils/module_docs_fragments/return_common.py<gh_stars>0 # Copyright (c) 2016 Ansible, Inc # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundati...
StarcoderdataPython
3288281
<reponame>lvying1991/KBQA-System<gh_stars>1-10 import json from copy import copy from questionanswering.construction.graph import SemanticGraph, WithScore, Edge, DUMMY_EDGE, EdgeList QUESTION_TYPES = {"location", "temporal", "object", "person", "other"} #语句对象 class Sentence: def __init__(self, i...
StarcoderdataPython
27024
#!/usr/bin/env python import json import os import subprocess import sys def fileExistsAndNonEmpty(filename): if not os.path.exists(filename): return False return os.stat(filename).st_size > 0 class AssemblerRunner(object): def __init__(self, sample_id, sample_seq, bam_file): with open("st...
StarcoderdataPython
3347615
import json import os import numpy import pytest from matchms.exporting import save_as_json from matchms.importing import load_from_json from .builder_Spectrum import SpectrumBuilder def test_save_and_load_json_single_spectrum(tmp_path): """Test saving spectrum to .json file""" mz = numpy.array([100, 200, 300...
StarcoderdataPython
1743559
<reponame>iamtheblackunicorn/blogster<filename>posts/apps.py # BLOGSTER by <NAME> # a.k.a. "The Black Unicorn" a.k.a. "<NAME>". # Licensed under the MIT license. from django.apps import AppConfig class PostsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'posts'
StarcoderdataPython
1774536
#Pluginname="WhatsApp (Android)" #Filename="msgstore.db" #Type=App import struct import tempfile import shutil def extractwadatabase(): ctx.gui_setMainLabel("Status: Trying to attach wa database") result={} for datadir in ["/data/com.whatsapp/databases/wa.db","/com.whatsapp/databases/wa.db","/d...
StarcoderdataPython
3395204
<reponame>dguo/churn import sqlite3 import click from pick import pick from tabulate import tabulate from ..util import pick_with_cancel, successful_update_message def _get_issuers(connection): command = 'SELECT id, name FROM card_issuers ORDER BY name' return connection.execute(command).fetchall() def sele...
StarcoderdataPython
145675
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Aerodynamic loads # <NAME> class Loads: def __init__(self): self.ys = [] # spanwise stations self.chds = [] # chord self.data = {} # coordinates and pressure coefficient self.cls = [] # lift self.cms = [] # moment positive no...
StarcoderdataPython
151258
<reponame>VikashK21/Coders_Life # This question is just about the json files that is also known as cache files. # Which we have already used in the previous tasks, the json files. # In the json file we can easily access the data without any network issue.
StarcoderdataPython
1659401
<reponame>silviaclaire/image-classifier-for-flowers import torch from torch import nn from torch import optim from torchvision import models from collections import OrderedDict def create_model(params): assert(all([key in dir(params) for key in ['arch', 'hidden_units', 'learning_rate']])) model = get...
StarcoderdataPython
1653452
<gh_stars>10-100 #!/usr/bin/env python # Copyright (C) 2014. <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # ...
StarcoderdataPython
93876
def test(): def f(x): """ :type x: str """ pass class C(object): def __gt__(self, other): return [] o = object() c = C() f(<warning descr="Expected type 'str', got 'bool' instead">1 < 2</warning>) f(<warning descr="Expected type 'str', got 'boo...
StarcoderdataPython
3358635
<reponame>zedrem/coast_search """ Title: coast_search Author: <NAME> Description: COAST_SEARCH allows you to generate and run queries against the Google Custom Search API. """ from __future__ import print_function from ._version import get_versions from coast_search import query_generator from coast_sear...
StarcoderdataPython
93125
<reponame>Prathyusha-Guduru/Montunes import requests def getLatLong(): res = requests.get('https://ipinfo.io/').json() location = res['loc'].split(',') latitude = location[0] longitude = location[1] return (latitude,longitude) def getLocation(): res = requests.get('https://ipinfo.io/').json() city = res["city...
StarcoderdataPython
3223046
from __future__ import absolute_import from __future__ import print_function import os import sys from conversion_imagenet import TestModels def get_test_table(): return { 'tensorflow' : { # Cannot run on Travis since it seems to consume too much memory. 'nasnet-a_large' : [ ...
StarcoderdataPython
1787229
import itertools as it import numpy as np from vtk_parsing import parse_file_vtk def voxel(edge_length, center): """ returns the data which is needed for plotting the faces of one voxel (a cube) :param edge_length: edge length of the cube :param center: center of gravity of the cube :return: list ...
StarcoderdataPython
3296486
# -*- coding: utf-8 -*- # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use this file except in # compliance with the License. A copy of the License is located at # # http://aws.amazon.com/asl/ # # or in the "licen...
StarcoderdataPython