text
string
size
int64
token_count
int64
"""<a href="https://projecteuler.net/problem=12" class="title-custom-link">Highly divisible triangular number</a> The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36,...
1,382
523
import sqlite3 import os #DB_FILEPATH = "data/chinook.db" DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "rpg_db.sqlite3") conn = sqlite3.connect(DB_FILEPATH) conn.row_factory = sqlite3.Row print(type(conn)) #> <class 'sqlite3.Connection'> curs = conn.cursor() print(type(curs)) #> <class 'sqlite3....
4,984
1,740
#!/usr/bin/env python3 # ISC License # # Copyright (c) 2019, Bryon Vandiver # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFT...
7,872
3,363
############################################################################### # # Copyright (C) 2012 # ASTRON (Netherlands Institute for Radio Astronomy) <http://www.astron.nl/> # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This program is free software: you can redistribute it and/or modify # it under the term...
15,364
4,306
import re def parse_srt(line_iter): """ Parses SubRip text into caption dicts. Args: line_iter: An iterator that yields lines of a SubRip file. Yields: dict: Caption dicts with `start`, `end` and `text` keys. """ line_iter = iter(line.rstrip('\r\n') for line in line_iter) ...
868
334
from sqlalchemy import func from application import db from application.helpers.error_handlers import ServerError class BaseModel(db.Model): __abstract__ = True def save(self): """save the item to database""" try: db.session.add(self) db.session.commit() except...
1,971
525
import os from unittest.mock import patch import alteia from tests.alteiatest import AlteiaTestBase class ResourcesTestBase(AlteiaTestBase): @classmethod def setUpClass(cls): with patch('alteia.core.connection.token.TokenManager.renew_token') as mock: mock.return_value = None ...
522
167
from ecgdigitize.signal.extraction.viterbi import * if __name__ == "__main__": print(list(interpolate(Point(0,0), Point(5,5))))
137
52
from typing import Any, Dict import boto3 import pytest from s3fs import S3FileSystem from peakina.io.s3.s3_fetcher import S3Fetcher @pytest.fixture def s3_fetcher(s3_endpoint_url): return S3Fetcher(client_kwargs={"endpoint_url": s3_endpoint_url}) def test_s3_fetcher_open(s3_fetcher): dirpath = "s3://acce...
2,711
1,050
# Generated by Django 2.2.7 on 2019-12-02 05:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('consulta', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='generate', new_name='consulta', ), ...
324
116
""" backend/events/tests/test_views.py Tests for the events page views. We use the test client. Read more at https://docs.djangoproject.com/en/2.1/topics/testing/tools/ """ import json from django.test import TestCase class EventsPageViewTests(TestCase): """Events page view tests for route /events/data ""...
802
252
import os import os.path def visit(arg, dirname, names): print dirname, arg for name in names: subname = os.path.join(dirname, name) if os.path.isdir(subname): print ' %s/' % name else: print ' %s' % name print os.mkdir('example') os.mkdir('example/one') f...
497
179
#!/usr/bin/env python # Part of tikplay # Yes, this is a bit of a non-test. from nose.tools import * from tikplay.provider.retriever import Retriever class TestRetriever(object): def __init__(self): self.retriever = Retriever({}) @raises(NotImplementedError) def test_handles(self): self.r...
532
190
import csv import io from datetime import datetime import peewee as pw from flask import Blueprint from flask import g from flask import make_response from flask import redirect from flask import render_template from flask import request from flask import url_for from wtforms import Form from wtforms import IntegerFie...
11,333
3,583
class TreeNode: def __init__(self,val): self.left = None self.right = None self.val = None def invertTree(self,root): if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
268
86
""" Wrap commonly-used torch builtins in nn.Module subclass for easier automatic construction of script """ import torch import torch.nn as nn import torch.nn.functional as F class argmax(torch.nn.Module): def __init__(self): super().__init__() def forward(self, A): return torch.argmax(A) c...
9,115
3,313
# Copyright (c) 2011 - 2017, Intel Corporation. # # 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 agre...
8,068
2,810
import json import logging from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.csrf import csrf_exempt # See note below on saveplaylist import models # Set up logging logger = logging.getLogger("apps")...
6,843
1,940
import os from pathlib import Path import pandas as pd from collections import defaultdict from typing import Dict, List from .config import REQUIRED_D, API_KEY_FILENAME import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def get_required_parameters(service_code: str) -> Lis...
2,868
884
# -*- coding: utf-8 -*- import networkx as nx import pandas as pd #Other nodes connected by one node r=open('input_data/BC-related_RRI_network.txt') ll=r.readlines() r.close() rna_pairs=[] node_to_nodes={} for l in ll: ws=l.strip().split('\t') qx=sorted(ws[0:2]) rna_pairs.append((qx[0],qx[1]...
1,608
692
# -*- coding: utf-8 -*- import abc from macdaily.cls.command import Command from macdaily.util.tools.print import print_info class InstallCommand(Command): @property def cmd(self): return 'install' @property def act(self): return ('install', 'installed', 'installed') @property...
1,518
448
""" FS commandline module. Allows to: - list host filesystems - remove a specific host filesystem - add a specific host filesystem """ from os.path import basename from piotr.cmdline import CmdlineModule, module, command from piotr.user import UserDirectory as ud from piotr.util import confirm @module('fs', 'List, ...
2,632
696
import tracking_pts_logger_master import tracking_pts_logger
61
17
from singlecellmultiomics.modularDemultiplexer.baseDemultiplexMethods import UmiBarcodeDemuxMethod, NonMultiplexable # ScarTrace class ScartraceR1(UmiBarcodeDemuxMethod): def __init__(self, barcodeFileParser, **kwargs): self.barcodeFileAlias = 'scartrace' UmiBarcodeDemuxMethod.__init__( ...
3,133
1,037
from datetime import date, time from django.contrib.postgres.fields import ArrayField from django.db import models from django.utils import timezone from django_fsm import FSMField, transition from rest_framework.reverse import reverse from simple_history.models import HistoricalRecords from bridger.buttons import Ac...
6,151
1,890
#automated error checking for RNAstructure python interface from __future__ import print_function import inspect from functools import wraps from collections import defaultdict debug = False class StructureError(Exception): pass class RNAstructureInternalError(Exception):pass lookup_exceptions = defaultdict(lambda:Runt...
2,975
857
from collections import defaultdict, Counter from itertools import product, permutations from glob import glob import json import os from pathlib import Path import pickle import sqlite3 import string import sys import time import matplotlib as mpl from matplotlib import colors from matplotlib import pyplot as plt fro...
52,691
23,498
from btw_mcp import * package_release("vanilla", "main", directory="ce_release")
81
27
#!/usr/bin/env python # (c) 2020 Sylvain Le Groux <slegroux@ccrma.stanford.edu> import pytest from pytest import approx import numpy as np import torch from IPython import embed from beam_search import Tokenizer, Score, BeamSearch @pytest.fixture(scope='module') def data(): mat = torch.Tensor(np.genfromtxt('data/...
3,449
1,517
__author__ = 'annyz' from pprint import pprint, pformat # NOQA import logging import os import sys from datetime import datetime from hydra.lib import util from hydra.kafkatest.runtest import RunTestKAFKA from hydra.lib.boundary import Scanner from optparse import OptionParser l = util.createlogger('runSuitMaxRate',...
3,404
1,101
from rest_framework import serializers from series.models import Series from villains.models import Villain class VillainSeriesSerializer(serializers.ModelSerializer): name = serializers.CharField() class Meta(object): fields = ('id', 'name',) model = Series class VillainDetailSerializer(s...
722
195
#!/usr/bin/env python """ Writes out map popularity of last two pools.""" from datetime import datetime, timedelta from utils.map_pools import map_type_filter, pools from utils.tools import execute_sql, last_time_breakpoint, map_name_lookup SQL = """SELECT map_type, COUNT(*) as cnt FROM matches WHERE started BETWEEN ...
1,574
515
# -*- coding: utf-8 -*- # Example for using WebDriver object: driver = get_driver() e.g driver.current_url from webframework import TESTDATA from variables import strings from selenium.webdriver.common.by import By from webframework.extension.util.common_utils import * from webframework.extension.util.webtimings import...
5,277
1,889
import getpass import os import platform import psycopg2 import sys import tempfile from glob import glob from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, quote_ident from subprocess import check_output, PIPE, Popen from time import sleep from ._compat import ustr from .utils import is_executable, Uri, Ver...
6,303
1,801
# -*- coding: utf-8 -*- import pandas as pd def save_dict_to_csv(dict_data: dict, csv_path: str): indexes = list(dict_data.keys()) columns = list(list(dict_data.values())[0].keys()) data = [] for row in dict_data: data.append([item for item in dict_data[row].values()]) pd_data = pd.DataFra...
426
153
from rest_framework import serializers from bluebottle.utils.model_dispatcher import get_donation_model from bluebottle.bb_projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer from bluebottle.bb_accounts.serializers import UserPreviewSerializer DONATION_MODEL = get_donation_model() c...
1,187
337
# WORKS BUT ISN'T FAST ENOUGH first_run = True while(True): inp = input().split() if len(inp) == 1: break if first_run: first_run = False else: print() nPlayers, nGames = [int(x) for x in inp] resultsW = [0] * nPlayers resultsL = [0] * nPlayers for i in range( int...
1,035
417
############################################################################### # Copyright 2019 Alex M. # # 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 witho...
9,460
2,766
import numpy as np import torch from torch.optim import Adam from torch.utils.data import DataLoader from tqdm import tqdm class VAE: def __init__( self, train_data, test_data, in_dim, encoder_width, decoder_width, latent_dim, device=None, ): ...
6,201
2,109
import simpy as sp import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import stats, integrate def client(env, lamda, q, tic): meant = 1/lamda while True: t = np.random.exponential(meant) yield env.timeout(t) q.put('job') tic.append(env.now) def ...
1,244
567
word_list = ['pseudolamellibranchiate', 'microcolorimetrically', 'pancreaticoduodenostomy', 'theologicoastronomical', 'pancreatoduodenectomy', 'tetraiodophenolphthalein', 'choledocholithotripsy', 'hematospectrophotometer', 'deintellectualization', 'pharyngoepiglottidean', 'psychophysiologically', 'pathologic...
4,756
1,859
# import all relevant contents from the associated module. from vandal.objects.montecarlo import ( MonteCarlo, MCapp, ) from vandal.objects.eoq import( EOQ, EOQapp, ) from vandal.objects.dijkstra import Dijkstra # all relevant contents. __all__ = [ 'MonteCarlo', 'EOQ', 'D...
363
140
# Django from django.contrib import admin # local Django from authentication.models import User admin.site.register(User)
124
33
class KPDatasets: def __init__(self) -> None: pass def get_train_dataset(self): if "train" not in self.datasets: return None return self.datasets["train"] def get_eval_dataset(self): if "validation" not in self.datasets: return None return se...
480
140
from .__version__ import __version__ from .core import create, remove, launch_shell
84
23
import os from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.flatpages.models import FlatPage from django.test import TestCase from django.test.utils import override_settings class HeyDoAppTest(unittest.TestCase)...
784
225
from flask_restx.fields import String, Boolean, Raw, List, Float, Nested class DataTransferObjects: def __init__(self, ns): self.ns = ns self.general_responses = {200: 'OK', 404: "Resource not found", 400: "Bad Request", ...
1,133
323
from gnews import GNews def get_client(): news_client = GNews() return news_client
91
29
#!/usr/bin/python3 ''' * Copyright (C) 2021 Raúl Osuna Sánchez-Infante * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. ''' ################## #Needed libraries# ################## import matplotlib as mpl mpl.use('TkAgg') import matpl...
13,284
4,998
# -*- coding: utf-8 -*- import json from typing import List from TM1py.Objects.Git import Git from TM1py.Objects.GitCommit import GitCommit from TM1py.Objects.GitPlan import GitPushPlan, GitPullPlan, GitPlan from TM1py.Services.ObjectService import ObjectService from TM1py.Services.RestService import RestService, Resp...
9,147
2,631
from hypothesis import strategies from hypothesis_geometry import planar from tests.bind_tests.hints import (BoundCell, BoundDiagram, BoundEdge, BoundVertex) from tests.bind_tests.utils import (bound_source_cate...
1,419
388
""" @Author: YangCheng @contact: 1248644045@qq.com @Software: Y.C @Time: 2020/7/21 15:22 """ from typing import List from pydantic import BaseModel, Field from tortoise import Tortoise from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator from lib.tortoise.pydantic import json_...
2,381
751
from skimage import img_as_bool, io, color, morphology import matplotlib.pyplot as plt import numpy as np import pandas as pd # Testing process # Import images one = img_as_bool(color.rgb2gray(io.imread('1.jpg'))) cross = img_as_bool(color.rgb2gray(io.imread('cross.jpg'))) grid = img_as_bool(color.rgb2gray(io.imread('...
1,102
401
# global_data.py import os from dotenv import load_dotenv # Read the bot token from the .env file load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DEBUG_MODE = os.getenv('DEBUG_MODE') BOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DB_FILE = os.path.join(BOT_DIR, 'database/room_wizard_db.db') ...
485
219
class AstronautRepository: def __init__(self): self.astronauts = [] def add(self, astronaut): self.astronauts.append(astronaut) def remove(self, astronaut): self.astronauts.remove(astronaut) def find_by_name(self, name: str): for astronaut in self.astronauts: ...
602
184
""" Model Definition """ from tensorflow import keras from tensorflow.keras.applications import ResNet101V2 from tensorflow.keras.layers import ( BatchNormalization, Conv2D, Dense, Dropout, Flatten, LSTM, MaxPool2D, TimeDistributed, Lambda ) import tensorflow as tf from .spatial_transformer.bilinear_sampler i...
1,767
667
#!/usr/bin/env python3 """Generate fake serialized NNs to test the lightweight classes""" import argparse import json import h5py import numpy as np def _run(): args = _get_args() _build_keras_arch("arch.json") _build_keras_inputs_file("variable_spec.json") _build_keras_weights("weights.h5", verbose=...
1,515
578
''' Collection of Windows-specific I/O functions ''' import msvcrt import time import ctypes from platforms import winconstants, winclipboard EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = c...
4,884
1,679
# messenger.py - contains functions to create different kinds of messages like info or error # color the text, usage: print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC BCOLORS = { 'HEADER': '\033[95m', 'OKBLUE': '\033[94m', 'OKGREEN': '\033[92m', 'WARNING': '\033[9...
715
288
import json import RPi.GPIO as GPIO from modules.sensor import getTempC, getHumidity def loadConfig(): with open('./config/pin.json') as data_file: data = json.load(data_file) return data currentPins = loadConfig().values() def bootActuators(): '''Assumes that pi is booting and set off al...
554
203
import json import habu def do_req(uri, *args, **kwargs): route_data = { "/": { "_links": { "people": { "href": "/people" }, "animals": { "href": "/animals" } } }, "/people": { "_links": { "self": { "href":...
1,170
381
import json import os import requests from dotenv import load_dotenv # You have to configure in this file to notify other services def notifyHandler(tweet): notifyDiscord(tweet) return def notifyDiscord(tweet, find_user_info=False): msg = tweet['text'] if ('entities' in tweet and 'urls' in tweet[...
1,162
365
import random import string class Cred: """ This is a class that makes the user credentials for their different accounts """ def __init__(self,account_name,user_name,email,password): """ This will construct an instance of the credentials class """ self.account_name ...
2,245
556
import signal import sys import time import pyupm_grove as grove import pyupm_i2clcd as lcd def interruptHandler(signal, frame): sys.exit(0) if __name__=='__main__': signal.signal(signal.SIGINT, interruptHandler) myLcd = lcd.Jhd1313m1(0, 0x3E,0x62) sensorluz=grove.GroveLight(0) coloR=255 colorG=200 colorB=100...
561
260
from setuptools import setup, find_packages setup( name='FSM', version='0.1', author='Ben Coughlan', author_email='ben@cgsy.com.au', packages=find_packages(), license_file='LICENSE', )
210
76
import random from typing import Tuple, Dict, Any import scipy import itertools import graphviz import numpy as np import pandas as pd from clustviz.pam import plot_pam from pyclustering.utils import euclidean_distance_square from pyclustering.cluster.clarans import clarans as clarans_pyclustering class clarans(cla...
9,553
2,494
from __future__ import absolute_import, print_function, unicode_literals import os import requests from metapub.findit import FindIt from metapub.exceptions import * from requests.packages import urllib3 urllib3.disable_warnings() OUTPUT_DIR = 'findit' CURL_TIMEOUT = 4000 def try_request(url): # verify=False m...
1,507
514
import tensorflow as tf from kgcnn.layers.base import GraphBaseLayer from kgcnn.layers.gather import GatherNodesOutgoing, GatherNodesIngoing from kgcnn.layers.pooling import PoolingLocalEdges from kgcnn.layers.modules import LazySubtract @tf.keras.utils.register_keras_serializable(package='kgcnn', name='DMPNNGatherE...
3,939
1,298
from typing import Callable, Tuple, Union StrOrBytes = Union[str, bytes] StrOrBytesPair = Tuple[StrOrBytes, StrOrBytes] KeysStore = Callable[[], Union[StrOrBytes, StrOrBytesPair]]
181
60
from django.contrib import admin from api.models import Device class DeviceAdmin(admin.ModelAdmin): list_display = ['android_id', 'alias', 'model', 'os_version', 'version', 'created', 'last_seen', 'active'] list_filter = ['active'] search_fields = ['registration_id', 'android_id', 'alias'] admin.site.r...
349
107
# from django.contrib import admin # from django.urls import path from django.conf.urls import url from help import views urlpatterns = [ url(r'^$', views.index) ]
169
53
# coding=utf-8 import random from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from notifications.models import EventType from social_graph import EdgeType try: from hashlib import sha1 as sha_constructor, md5 as md5_constru...
5,299
1,729
from django.urls import path from . import views urlpatterns = [ path('', views.get_percentage, name='get_percentage'), path('get_percentage_value', views.get_percentage_value, name='get_percentage_value'), ]
219
71
# Generated by Django 3.2.8 on 2021-10-12 15:54 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AspectActlog', fields=[ ('id', models.AutoF...
10,866
2,813
"""Schedule multiple flows of a type.""" from .base import BaseHandler class FlowScheduling(BaseHandler): """Schedule multiple flows of a type.""" def execute(self, flow_name, flow_arguments): """Schedule multiple flows of a type, do filter expansion if needed. :param flow_name: flow name t...
712
196
import logging logger = logging.getLogger(__name__) class Notifier: def __init__(self, redis): self.redis = redis async def notify_guilds(self): guilds_set = "guilds" logger.debug("Scanning {}".format(guilds_set)) result = [] async for guild_id in self.redis.isscan(...
1,032
341
from app.helpers.sqlalchemy import db class Role(db.Model): __tablename__ = 'tt' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer)
286
103
# # PySNMP MIB module HUAWEI-CDP-COMPLIANCE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-CDP-COMPLIANCE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:31:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
12,819
5,484
import re from pybb.processors import BaseProcessor from pybb.compat import get_user_model from . import settings class MentionProcessor(BaseProcessor): username_re = r'@([\w\-]+)' format = '@%(username)s' tag = '[mention=%(user_id)s]%(username)s[/mention]' model = get_user_model() def get_user...
1,223
365
import unittest from selenium import webdriver from PageObjectModel.Pages.addAndEditionDataPage import AddAndEditionData_Page from time import sleep url = 'https://buggy-testingcup.pgs-soft.com/' class AddAndEditionDataPage(unittest.TestCase): def setUp(self, browser="mozilla", task="task_3"): if browse...
1,505
474
from q2_api_client.clients.base_q2_client import BaseQ2Client from q2_api_client.endpoints.mobile_ws_endpoints import CalendarEndpoint class CalendarClient(BaseQ2Client): def get_calendar(self): """GET /mobilews/calendar :return: Response object :rtype: requests.Response """ ...
827
234
#!/usr/bin/env python """ Set of utilities to issue/verify/revoke a CG token with REST calls Requires valid username and password either in bash environment or given at the command line. Issue Token: Token can be easily created (and stored to env) with the folloing: # create token using CG_USERNAME, ...
11,477
3,312
from .Generic import GenericHandler class HDInsightHandler(GenericHandler): azure_object = "hdinsight" def execute(self): fqn = self.get_full_resource_name() self.add_context_parameter("resource-group", "group") if fqn == "hdinsight" and self.action == "create": ...
741
203
from audioop import add from erd import * from table import * # This function converts an ERD object into a Database object # The Database object should correspond to a fully correct implementation # of the ERD, including both data structure and constraints, such that the # CREATE TABLE statements generated by the Dat...
30,841
10,786
# Program to self calibrate OTF data import Obit, OTF, Image, OSystem, OErr, OTFGetSoln, InfoList, Table # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Python", 1, 103, 1, ["None"], 1, ["./"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files disk = 1 # Dirty inFullFile = "OTFDirtyFull.fits"...
1,848
784
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup r = requests.get("https://twitter.com/ThePSF", headers={"User-Agent": ""}) if r.status_code == 200: s = BeautifulSoup(r.content, "html.parser") # extract tweets l_tw = [] for p in s.find_all("p", attrs={"clas...
393
155
#!/usr/bin/python # -*- coding: utf-8 -*- import decimal import multiprocessing import random def roundDecimal(v): ''' Sembra che l'arrotondamento di un decimal sia più complicato del previsto ''' return v.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_UP) def maybeStart(startCb, deb...
590
203
# Generated by Django 3.2.4 on 2021-09-24 15:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0016_alter_user_usercode'), ] operations = [ migrations.AlterField( model_name='user', ...
504
176
from django.shortcuts import render def group_list(request): return render(request, 'group_list.html')
105
33
# -*- coding: utf-8 -*- """ Created on Mon Feb 11 09:18:37 2019 @author: if715029 """ import pandas as pd import numpy as np import sklearn.metrics as skm import scipy.spatial.distance as sc #%% Leer datos data = pd.read_excel('../data/Test de películas(1-16).xlsx', encoding='latin_1') #%% Seleccionar datos (a mi e...
1,596
719
import logging class CustomLogger: def __init__(self): pass """ Create logger which name is 'dev' """ def create_logger(self, name='dev', log_file='itao.log', write_mode='w'): logger = logging.getLogger(name) # setup LEVEL logger.setLevel(logging.DEBUG) # setup...
1,187
341
class Serializer: """ send data serially """ def __init__(self): return
99
34
import numpy import rasterio import gdal print('all modules imported') # path to the folder with the ndvi rasters base_path = "/Users/hk/Downloads/gaga/" # shapefile with forest mask forest_mask = base_path + "waldmaske_wgs84.shp" # initialize the necessary rasters for the ndvi calculation. ndvi_2017 = rasterio.open...
2,296
900
def product_from_branch(branch): """ Return a product name from this branch name. :param branch: eg. "ceph-3.0-rhel-7" :returns: eg. "ceph" """ if branch.startswith('private-'): # Let's just return the thing after "private-" and hope there's a # product string match somewhere in...
462
144
import requests url = 'https://notify-api.line.me/api/notify'#LINE NotifyのAPIのURL token = '2RNdAKwlaj69HK0KlEdMX1y575gDWNKrPpggFcLnh82' #自分のアクセストークン ms = "新たなソフトを開くと負担が過剰にかかってしまいます。"#送信する通知内容 def line(message,url,token): post_data = {'message': message} headers = {'Authorization': 'Bearer ' + token} #送信する...
752
372
"""titiler.application""" __version__ = "0.6.0"
49
22
#!/usr/bin/env python import os from collections import defaultdict hosts = {'mill001', 'mill004', 'mill005'} user = 'a7109534' file_location = '/work/a7109534/' #file_location = '/home/ryan/workspace/JGroups' #file_location = '/home/pg/p11/a7109534/' file_wildcard = '*' extension = ".csv" get_file = file_location + f...
550
219
"""Data providers.""" import os try: # try-except statement needed because # pip module is not available in google app engine import pip except ImportError: pip = None import yaml import six from .artifact_store import get_artifact_store from .http_provider import HTTPProvider from .firebase_provider...
3,610
1,022
import numpy as np import pandas as pd from server.model_inference.config import labels from server.model_inference.core_model import get_model_prediction from server.util.prediction_to_json import pandas_to_json def get_predictions(images): ids = list(images.keys()) out = np.hstack((np.asarray(ids)[np.newax...
570
189
import asyncio import json import socket import time from botsdk.util.BotPlugin import BotPlugin from botsdk.util.Error import printTraceBack def getMcRequestData(ip, port): data = (b"\x00\xff\xff\xff\xff\x0f" + bytes([len(ip.encode("utf8"))]) + ip.encode("utf8") + int.to_byte...
7,310
2,228