text
string
size
int64
token_count
int64
import cv2 class color: def __init__(self, table, use): self.table = table self.use = use return def process(self, item): if(self.use=='rgb'): size = (64,64) image = cv2.imread(item['path']) if(not isinstance(image, numpy.n...
12,517
4,301
from django.db import models class Post(models.Model): """ Model for Charity or Event Post """ POST_KINDS = [(kind, kind) for kind in ["charity", "event"]] title = models.CharField(max_length=200) content = models.TextField() published_date = models.DateField() created_date = models....
545
173
""" GraphQL queries """ from graphql import GraphQLObjectType from .system_queries import LatestQuery # pylint: disable=invalid-name RootQueryType = GraphQLObjectType( name='Queries', fields=lambda: { 'latest': LatestQuery, } )
251
82
import re from tensorflow.keras.utils import to_categorical from collections import Counter import pandas as pd import torch from sklearn.model_selection import train_test_split, StratifiedKFold from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import numpy as np ###############...
4,781
1,532
import datetime import os import pytz from prometheus_client import CollectorRegistry, Gauge, pushadd_to_gateway class PrometheusMetrics: def __init__(self, logger): self.logger = logger self.registry = CollectorRegistry() self.pushgateway = os.environ.get("PUSHGATEWAY", "localhost:9091")...
9,733
3,120
import mcell as m from parameters import * from subsystem import * from geometry import * # ---- observables ---- viz_output = m.VizOutput( mode = m.VizMode.ASCII, output_files_prefix = './viz_data/seed_' + str(get_seed()).zfill(5) + '/Scene', every_n_timesteps = 1 ) count_a_Cube1 = m.Count( name = ...
2,305
975
#custom_logger.py #Leonardo Duarte import logging #Logging levels INFO = logging.INFO DEBUG = logging.DEBUG WARNING = logging.WARNING ERROR = logging.ERROR def setup(name, **kwargs): log_level=kwargs.get('log_level',INFO) formatter = logging.Formatter(fmt='%(asctime)s templatetool %(levelname)s: %(...
1,372
457
import configparser import os import os.path as op import requests import tempfile import threading import traceback import uuid from CPAC.info import __version__, ga_tracker udir = op.expanduser('~') if udir=='/': udir = tempfile.mkdtemp() temp_dir = True tracking_path = op.join(udir, '.cpac') def get_or_c...
4,403
1,335
from temper import TemperDevice, TemperHandler
47
12
import pytest from mr_provisioner.models import Token from werkzeug.datastructures import Headers @pytest.fixture(scope='function') def token_nonadmin(db, user_nonadmin): token = Token(user_nonadmin.id, None, 'api test token') db.session.add(token) db.session.commit() db.session.refresh(token) re...
894
309
import requests from bs4 import BeautifulSoup import json from urllib import parse from datetime import datetime import time def construct_link(origin, destination): o = parse.urlparse(origin) if destination.startswith('http'): return destination elif destination.startswith('/'): ...
7,509
2,536
from typing import Optional from overrides import overrides import numpy as np import torch from allennlp.training.metrics.metric import Metric class FeverScore(Metric): def __init__(self, nei_label=0, max_select=5) -> None: self.correct_count = 0. self.total_count = 0. self.correct_evid...
3,763
1,074
import requests import getpass import pickle import os import sys # import webbrowser # import time home = os.path.expanduser('~/SPC') # print(home) # $ip=$_SERVER['REMOTE_ADDR'] if os.path.isfile(home+'/Pickles/url.pkl'): fp = open(home+'/Pickles/url.pkl','rb') url = pickle.load(fp) else: exit("First set the serve...
928
384
""" Install the pysteps data in a test environment and create a pystepsrc configuration file pointing to that data. """ if __name__ == "__main__": import argparse from pysteps.datasets import create_default_pystepsrc, download_pysteps_data parser = argparse.ArgumentParser(description="Install pysteps data...
565
177
#!/usr/bin/python # -*- coding: utf-8 -*- """ @File : commander.py @Time : 2019-04-20 11:04 @Author : Bonan Ruan @Desc : """ from core.executer import Executer from core.builder import Builder from core.poc_manager import PoCManager import utils.utils as utils import utils.consts as consts import time clas...
4,723
1,491
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Simple Fun #8: Kill K-th Bit #Problem level: 7 kyu def kill_kth_bit(n, k): b = list(bin(n))[2:] if len(b)>=k: b[(-1)*k]='0' return int(''.join(b),2)
221
104
# coding: utf-8 # # Table of Contents # <p><div class="lev1 toc-item"><a href="#Easily-creating-MAB-problems" data-toc-modified-id="Easily-creating-MAB-problems-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Easily creating MAB problems</a></div><div class="lev2 toc-item"><a href="#Constant-arms" data-toc-modifie...
11,872
4,848
# state file generated using paraview version 5.8.0 # ---------------------------------------------------------------- # setup views used in the visualization # ---------------------------------------------------------------- # trace generated using paraview version 5.8.0 # # To ensure correct image size when batch p...
24,464
10,129
from ansible.errors import AnsibleError class FilterModule(object): def filters(self): return { 'combine_dict_list': self.combine_dict_list, 'search_from_dict_list': self.search_from_dict_list, 'search_item_from_dict_list': self.search_item_from_dict_list, } ...
1,642
498
"""Tests for ru_RU numbers humanizing.""" from pytest_mock import MockerFixture import human_readable def test_int_word(activate_en_abbr: MockerFixture) -> None: """It returns int word number.""" expected = "12.3 B" result = human_readable.int_word(12345591313) assert result == expected
309
111
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter from scrapy.pipelines.files import FilesPipeli...
733
217
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: result = ListNode(val=-1) previous = result while l1 is not None ...
633
192
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.pvpTestv2 from pandac.PandaModules import Point3, VBase3 objectStruct = {'Objects': {'1128540775.81jubutle...
1,778
1,026
# External packages import sys import pandas as pd import ast import os # Internal modules import paperscraper.config as config def main(): # Read input file df_scraped_input = pd.read_csv(config.path_postprocessing_output, sep='\t', index_col=0) unique_authors = set() for index, row in df_scraped_...
954
301
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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 applicab...
2,511
758
#Copyright 2017 Google 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.org/licenses/LICENSE-2.0 # Unless required by applicable law or agree...
7,453
2,292
from flask import Flask, request, abort, jsonify import wechat_sec, http_util import sys import os import logging app = Flask(__name__) app.logger.setLevel(logging.NOTSET) def process(uri, sec=False): run_env = os.getenv('RUN_ENV') req = wechat_sec.req_build(request.json) if run_env in { 'develop', 'mock...
765
272
#!/usr/bin/env python # -*- coding: utf-8 -*- """ archivebot.py - discussion page archiving bot. usage: python archivebot.py [OPTIONS] TEMPLATE_PAGE Bot examines backlinks (Special:Whatlinkshere) to TEMPLATE_PAGE. Then goes through all pages (unless a specific page specified using options) and archives old discu...
23,517
7,367
import os import tempfile from pathlib import Path from django.core.management import call_command def test_call_no_args(): tmp_dir = Path(tempfile.mkdtemp()) call_command("render_workflow_graph", "-d", tmp_dir) assert os.path.exists(str(tmp_dir / "testapp_simpleworkflow.svg")) assert os.path.exists(...
1,911
678
# Generated by Django 2.0.3 on 2018-07-15 11:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_stat'), ] operations = [ migrations.DeleteModel( name='Stat', ), ]
276
101
# Generated by Django 2.2.13 on 2020-07-22 16:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pipeline', '0038_hex_isp_service'), ] operations = [ migrations.AddField( model_name='service'...
1,416
428
import string import sys import os OPERATOR_BOX = "B" OPERATOR_DIAMOND = "D" def print_help(): print ('Usage: python cbparse.py Option Arguments DirectoryPath') print ('Options: ') print (' S: parse chasebench data dir - Source Instance') print (' Arguments: timeline_size') print (' T...
9,914
2,931
import intcode class Springdroid: def __init__(self, instructions): self.instruction_chars = list("\n".join(instructions)) + ["\n"] def run(self): intcode.execute_program(self.get_program(), self.get_input, self.write_output) def get_input(self): ch = self.instruction_chars.pop(0...
1,279
447
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright (c) 2019 loretoparisi@gmail.com # from functools import wraps from .bounded_pool_executor import BoundedThreadPoolExecutor from .bounded_pool_executor import BoundedProcessPoolExecutor _DEFAULT_POOL = BoundedThreadPoolExecutor(max_workers=5) _PROCESS_POOL = Bou...
694
247
from .server import WebsocketServer, ErrMsg name = "protocolws" __version__ = "0.2.1"
87
32
import requests import pprint import os import csv import sys import urllib.request scotch_csv = sys.argv[1] subscription_key = sys.argv[2] search_url = "https://api.cognitive.microsoft.com/bing/v7.0/images/search" scotch_list = [] with open(scotch_csv, newline='') as csvfile: reader = csv.reader(csvfile, delimit...
1,290
452
from . import util __all__ = ["util"]
38
14
from vuabl.data.data_from_other_asset import DataFromOtherAsset from vuabl.utils.layout_reader import LayoutReader import vuabl.parsing.parameters as pparamrs import vuabl.parsing.asset_type as pasttp import re def is_data_from_other_assets_header(line: str) -> bool: return re.match(r"^\s*Data From Other Assets....
2,007
616
import argparse from attention_details import ( AttentionDetailsData, get_token_info, add_token_info, ) from pytorch_pretrained_bert import BertModel, BertTokenizer from flask import render_template, redirect, send_from_directory from flask_cors import CORS from utils.mask_att import strip_attention impo...
7,132
2,397
################################################################################ # Copyright (C) 2013 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ Unit tests for bayespy.utils.misc module. """ import unittest im...
17,119
5,178
#!/usr/bin/env python # This is a VERY simple and naive manual tracker. # If you need something more powerful, Fiji is # absolutely recommended. # Generic import argparse import csv import numpy as np import sys import os # Imaging and visualization from PIL import Image import matplotlib.pyplot as plt # Functions...
1,948
625
from Jumpscale import j from .TelegramBotClient import TelegramBot JSConfigs = j.baseclasses.object_config_collection class TelegramBotFactory(JSConfigs): __jslocation__ = "j.clients.telegram_bot" _CHILDCLASS = TelegramBot
234
84
# Copyright 2021 Grupo Globo # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
10,750
3,492
import numpy as np import scipy.ndimage import os import PIL.Image txtpath = './caricature.txt' lmpath = './WebCaricature/FacialPoints/' impath = './WebCaricature/OriginalImages/' outpath = './Caricature/' def image_align(src_file, dst_file, face_landmarks, output_size=1024, transform_size=4096, enable_padding=True, ...
5,568
2,320
from __future__ import annotations from abc import ABC, abstractmethod from argparse import ArgumentParser, MetavarTypeHelpFormatter from sys import version_info from typing import Any, Callable, Dict, Generic, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar if version_info >= (3, 8): from typing import...
5,153
1,540
import boto import boto.s3 from misc import printProgress, pathLeaf idkeypath = '/home/ubuntu/.s3/AWS_ACCESS_KEY_ID' secretkeypath = '/home/ubuntu/.s3/AWS_SECRET_ACCESS_KEY' bucketname = 'edu-uchicago-rdcep-diles' folder = '' with open(idkeypath) as myfile: id_access_key = myfile.read().replace('\n',...
693
272
import pickle import sys sys.path.append("../../") # nopep8 from Sentence_Encoder.meta_query_encoder import encode import tensorflow.compat.v1 as tf import tensorflow_text import tensorflow_hub as hub import numpy as np tf.disable_eager_execution() sess = tf.InteractiveSession(graph=tf.Graph()) ConvRT_model = hub.Mo...
4,170
1,431
"""Console script for topojoin.""" import os import sys from pathlib import Path import click from topojoin.topojoin import TopoJoin from typing import Union, Dict, Any @click.command() @click.argument("topo_path", type=click.Path(exists=True)) @click.argument("csv_path", type=click.Path(exists=True)) @click.option( ...
2,616
902
import empowermentexploration.utils.data_handle as data_handle import empowermentexploration.utils.helpers as helpers import matplotlib as mpl import matplotlib.colors as c import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.stats import sem mpl.use('Agg') class Visualization(): ""...
16,112
4,823
# -*- coding:utf-8 -* import os import sys import util def GetAllHeader(folder): files = [] for dirpath, dirnames, filenames in os.walk(folder): for file in filenames: if file.endswith('.h') or file.endswith('.hpp'): files.append(os.path.join(dirpath, file)) ...
1,186
390
# + # # Copyright 2018 Analytics Zoo 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 agree...
5,917
1,644
n = int(input(),16) for i in range(1,16): print("%X"%n,"*%X"%i,"=%X"%(n*i),sep="")
88
51
from django.contrib import admin from . import models admin.site.register(models.APIKey) admin.site.register(models.JSONRecord)
129
38
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import pandas as pd import glob import os # %% # Read and format raw data and save to csv # Pattern for the dataset names: TRY_[1-15]_[a,w,s]_[2015,2045] with # 1-15 -> test reference region number # a,w,s -> average, extreme w...
4,882
1,852
structure = [ ('first', 'a Partridge in a Pear Tree.'), ('second', 'two Turtle Doves, '), ('third', 'three French Hens, '), ('fourth', 'four Calling Birds, '), ('fifth', 'five Gold Rings, '), ('sixth', 'six Geese-a-Laying, '), ('seventh', 'seven Swans-a-Swimming, '), ('eighth', 'eight Ma...
1,100
408
# The list is from http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html pluralforms = { 'ay': 'nplurals=1; plural=0;', 'bo': 'nplurals=1; plural=0;', 'cgg': 'nplurals=1; plural=0;', 'dz': 'nplurals=1; plural=0;', 'id': 'nplurals=1; plural=0;', 'ja': 'nplurals=1; plural=0;', 'jbo':...
6,695
3,933
import logging logger = logging.getLogger(__name__) from django.views.generic import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.template import RequestContext, Context, loader from django.http import HttpResponseServerError ...
2,649
745
from Utils.string_utils import clear_spaces as clear def test_validation_all_contacts_info(app, db): ui_contacts_list = app.contact.get_contact_list() db_contacts_list = db.get_contact_list() assert len(ui_contacts_list) == len(db_contacts_list) for ui_contact in ui_contacts_list: db_contact =...
896
301
""" Test obtaining peak audio values with PyAV: time python pyav_audio_vol.py ~/Videos/sample.mp4 Reference: https://ffmpeg.org/doxygen/trunk/group__lavu__sampfmts.html """ import sys import av from numpy import abs, sqrt, vdot, fromiter, float64, uint8, average, frombuffer, mean import matplotlib.pyplot as plt vid...
1,423
553
# Things to Remember # # Python’s standard method resolution order (MRO) solves the problems of superclass # initialization order and diamond inheritance. # # Always use the "super" built-in function to initialize parent classes. class MyBaseClass(object): def __init__(self, value): self.value = value c...
937
268
from flask import Blueprint, request, jsonify from flasgger import Swagger, LazyJSONEncoder from flasgger.utils import swag_from from src.model.test import make_prediction from src.api.config import get_logger _logger = get_logger(logger_name=__name__) prediction_app = Blueprint('prediction_app', __name__) @predict...
1,164
356
# SPDX-FileCopyrightText: 2021 Computer Assisted Medical Interventions Group, DKFZ # SPDX-FileCopyrightText: 2021 Janek Groehl # SPDX-License-Identifier: MIT import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable def col_bar(image, fontsize=None, fontname=None, ticks=None): ax = ...
921
362
import sys import math import json from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__))) + '/utils/') import numpy as np import scipy.special as special from algorithm_utils import get_parameters, set_algorithms_output_data from pearsonc_lib import PearsonCorrelationLocalD...
2,365
848
"""General tables module.""" import logging import re import typing as tp from pathlib import Path from varats.mapping.commit_map import create_lazy_commit_map_loader from varats.plot.plot_utils import check_required_args from varats.utils.settings import vara_cfg if tp.TYPE_CHECKING: import varats.table.table as...
5,245
1,664
from __future__ import annotations from .. import crypto, db, config from ..db import query from ..web import app from .exc import NoSuchUser, BadPermission from typing import Optional import time class User: """ Class representing a user stored in the database. Properties: id - the database pr...
16,436
4,617
name = "scanapi" from scanapi.__main__ import main __all__ = ["main"]
71
26
#!/usr/local/bin/python #fib=[0,1] #for i in range(0,8): # fib.append(fib[-2]+fib[-1]) #print fib #def fibs(n): # fib=[0,1] # for i in range(n-2): # fib.append(fib[-2]+fib[-1]) # return fib #print fibs(5) #def square(x): # 'Calculate x*x.' # return x*x ##print square._doc_ #help(square) #def inc(x): # x[0]=x[...
917
487
#A tuple is a collection which is ordered and unchangeable. In Python tuples are written with #round brackets. #tuple thistuple = ["apple", "banana", "cherry"] print(thistuple) #Access Items thistuple = ["apple", "banana", "cherry"] print(thistuple[1]) #Negative Indexing thistuple = ["apple", "banana", "cherry"] pri...
2,197
934
# -*- coding: utf-8 -*- """ @author: a.grebert """ import draft as fct import numpy as np import string import time import os, sys, shutil import matplotlib.pyplot as plt from xml.dom.minidom import parse import xml.dom.minidom def time_stat(tstart): minutes, seconds= divmod(time.time()-tstart, 60) if minute...
12,208
4,642
"""A python FFMPEG module built from sdpm.""" from __future__ import unicode_literals from sidomo import Container def transcode_file(url): """Any format --> 20000 Hz mono wav audio.""" with Container( 'suchkultur/avconv', memory_limit_gb=2, stderr=False ) as c: for line in...
871
305
# Author: DINDIN Meryll # Date: 02/03/2019 # Project: optimizers SPACE = dict() SPACE['SGD'] = { 'loss': ('choice', ['squared_loss', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive']), 'penalty': ('choice', ['none', 'l1', 'l2', 'elasticnet']), 'alpha': ('uniform_log', (1e-10, 1.0))...
3,401
1,537
import requests url = 'http://localhost:7000/run' data = {'workflow': 'wordcount', 'request_id': '1'} requests.post(url, json=data)
132
49
from werkzeug.contrib.cache import SimpleCache class BasicCache: cache = SimpleCache() def set(self, key, value): self.cache.set(key, value, timeout=50 * 1000) def get(self, key): return self.cache.get(key=key)
243
84
from django.apps import AppConfig class CheapiesgrConfig(AppConfig): name = 'cheapiesgr'
95
32
#!/usr/bin/env python2 """ Utilities for performing stochastic matrix and vector compressions. """ import numpy import misc_c_utils import near_uniform def fri_subd(vec, num_div, sub_weights, n_samp): """ Perform FRI compression on a vector whose first elements, vec[i] are each subdivided into equal segments...
14,626
4,966
# BSD 3-Clause License # # Copyright (c) 2019, Rene Jean Corneille # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, thi...
5,590
2,089
def mutations(input_list): print input_list[0],input_list[1] first = list(input_list[0].lower()) second = list(input_list[1].lower()) try: for ele in second: first.remove(ele) except: return False return True print mutations(["hello","heel"]) print mutations(["Alien","line"])
295
115
Someclass = type('Someclass', (Somebase,), {'x': 23})
54
22
# # Copyright 2020 XEBIALABS # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subli...
2,131
648
import re from ..entidades.modelo_fluxo import Movimento from ..persistencia.database import db from sqlalchemy.orm import aliased, load_only, Load, exc from flask_restful import abort from flask import Response import json def incluir_movimento(parametros): movimento = Movimento(**parametros) movimento.id_mo...
1,599
530
n1 = int(input("digite um valor: [999 para parar] ")) cont = 0 soma = n1 while n1 != 999: soma += n1 cont += 1 n1 = int(input("Digite um valor: ")) print("Você digitou {} numeros e a soma entre eles foi de {}!".format(cont, soma))
243
104
import numpy as np from matplotlib import pyplot as plt import sys import re from os.path import join fs = 100 def stamp_to_seconds(t): h, m, s, ms = [int(x) for x in re.search("(\d+):(\d+):(\d+),(\d+)", t).groups()] return 3600 * h + 60 * m + s + 0.001 * ms good_runs = ["07_02_14", "07_04_45", "08_11_19", "...
2,468
943
def mul(arr): res = arr[0] for i in arr[1:]: res *= i return res def gen_subarray(arr, n): for i in range(1 << n): y = 1 for j in range(n): if i & (1 << j): y *= arr[j] yield y def main(): n, p1, p2 = map(int, input().split(",")) ...
514
209
##Author: Ilia Rushkin, VPAL Research, Harvard University, Cambridge, MA, USA ###################################### ####Estimation functions are below#### ###################################### import numpy as np def knowledge(self, problems, correctness): """ ##This function finds the empirical knowledge ...
9,205
3,122
import os import environ import keep_alive from discord.ext import commands token = os.environ.get("TOKEN") bot = commands.Bot(command_prefix="") for filename in os.listdir("./cogs"): if filename.endswith(".py") and filename != "__init__.py": bot.load_extension(f'cogs.{filename[:-3]}') keep_alive.ke...
352
126
""" command-line interface for scrap2rst """ import sys import logging import argparse from scrap2rst import __version__ from scrap2rst.logging import setup_logger from scrap2rst.converter import convert logger = logging.getLogger(__name__) def get_argparser(): p = argparse.ArgumentParser() p.add_argument('...
953
315
import json import os import os.path import requests import csv import tempfile from io import StringIO import boto3 import time import urllib3 create_table = """ CREATE EXTERNAL TABLE `[OFFER]`( [COLUMNS] [PARTITION] ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' STORED AS INPUTFORMAT 'org.apache...
8,605
2,448
import sys import argparse import pandas as pd import numpy as np import os def get_settings(): parser = argparse.ArgumentParser(description='Script to ensemble submissions.') parser.add_argument('--include_external', help='whether to include external data (1) or not (0).', default=0, type = int) ...
1,920
601
JDs = [] RAs = [] Decs = [] file = open("data.txt", 'r') data = [] for line in file: datum = line.split("\t") JDs.append(float(datum[0])) RAs.append(float(datum[1])) Decs.append(float(datum[2][:-1])) """ import matplotlib.pyplot as plt JDs = [2458281.856678, 2458281.857743, 2458281.85880...
1,927
1,591
#!/usr/bin/env python2.4 """ tray_data provides the data for the tray GUI. It handles the XML data and provides the neccessary interfaces. """ import tray_data import logging from util.trayErrors import PropertyNotFoundError log = logging.getLogger("xml_jtray") log.setLevel(logging.WARN) class J...
7,337
2,115
#!/usr/bin/env python3 import pytest from wellmap import * @pytest.mark.parametrize( 'args, expected', [ (((0,0), 0, 0), []), (((0,0), 0, 1), []), (((0,0), 1, 0), []), (((0,0), 1, 1), [(0,0)]), (((0,0), 2, 1), [(0,0), (0,1)]), (((0,0), 1,...
1,104
550
model = Model(**params) # Init a model with parameters. model.get_params() # Get model parameters. model.set_params(**params) # Set model parameters model.fit(X, y) # Fit the model with a dataset model.score(X, y) # Provides the score for the dataset. model.predict(X) # Make a prediction using fitted model.
318
99
from enum import Enum class noaa_site_label(Enum): DIRECTORY = 'directory:' FILE_LIST = '\n**NEW** Select one file only ' SURFACES = 'select the levels desired:' VARIABLES = 'select the variables desired:'
215
72
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2015 Tom Regan # # 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...
5,202
1,480
import os from urllib.parse import urljoin import requests from requests.auth import HTTPBasicAuth from .models import SourcesResponse from .models import AvailableTimeSeriesResponse from .models import ObservationsResponse FROST_API_KEY = os.environ.get('FROST_API_KEY', None) class APIError(Exception): """ Rais...
11,567
2,975
from tqdm import tqdm from itertools import starmap import requests import time import click import re import os from llvd.utils import clean_name, subtitles_time_format, throttle def download_video(url, index, filename, path, delay=None): """ Downloads a video and saves it by its name plus index for eas...
3,411
1,004
import psycopg2 import calendar import sys import os # TODO: add ability to either add entire year or specific month from command line # TODO: Implement argparse to add functionality to CLI def addYear(cur,year): # Add the months of the specified year into the Database monthList = [] monthNameList = cale...
1,902
623
""" The stellar spin periods and planetary orbital periods originally collected by Penev et al (2018) are shown in Figure~\ref{fig:Pspin_vs_Porb}. We only show hot Jupiter systems with spin period S/N ratios of at least 5, and have colored the hot Jupiters by whether their stellar radius is below or above $1.2R_\odot$....
3,938
1,672
from math import sqrt import matplotlib.pyplot as plt import numpy as np from prettytable import PrettyTable headers = PrettyTable( ['№', 'x1_1', 'x2_1', 'x1_2', 'x2_2', 'function(x1,x2)', 'df']) def table(count, old_function, x1_1, x2_1, x1_2, x2_2, new_function): Tablelist = { '№': count, ...
4,918
2,074
from tcga_encoder.utils.helpers import * from scipy import stats def auc_standard_error( theta, nA, nN ): # from: Hanley and McNeil (1982), The Meaning and Use of the Area under the ROC Curve # theta: estimated AUC, can be 0.5 for a random test # nA size of population A # nN size of population N Q1=theta/...
784
332