text
string
size
int64
token_count
int64
"""A generic class to build line-oriented command interpreters. Interpreters constructed with this class obey the following conventions: 1. End of file on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A ...
15,015
4,032
from django.contrib import admin from .models import Order, receiverInfo @admin.register(Order) class OrderAdmin(admin.ModelAdmin): date_hierarchy = 'created_at' list_display = ('user', 'code', 'total_price', 'shipping_status', 'created_at') list_display_links = ('user',) list_editable = ('shipping_s...
1,127
367
from node import Node class LinkedList: """ initializes LL """ def __init__(self, iter=[]): self.head = None self._size = 0 for item in reversed(iter): self.insert(item) def __repr__(self): """ assumes head will have a val and we will need this...
2,513
680
import FWCore.ParameterSet.Config as cms process = cms.Process("LIKELIHOODPDFDBREADER") # process.load("MuonAnalysis.MomentumScaleCalibration.local_CSA08_Y_cff") process.source = cms.Source("EmptySource", numberEventsInRun = cms.untracked.uint32(1), firstRun = cms.untracked.uint32(1) ) process.load("Configur...
1,559
611
from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer, AutoConfig from sklearn.model_selection import StratifiedKFold import numpy as np import torch from fast_fine_tuna.dataset import MainDatasetDouble, MainDataset from transformers import AdamW from torch.utils.data import DataLoader i...
9,615
2,887
# Message class Implementation # @author: Gaurav Yeole <gauravyeole@gmail.com> class Message: class Request: def __init__(self, action="", data=None): self.action = action self.data = data class Rsponse: def __init__(self): self.status = False se...
451
133
#!/usr/bin/python from mod_pywebsocket import msgutil import time def web_socket_do_extra_handshake(request): pass # Always accept. def web_socket_transfer_data(request): time.sleep(3) msgutil.send_message(request, "line")
230
83
# # 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...
2,404
694
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is govered by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Convert Monorail PB objects to API PB objects""" import datetime import logging import time ...
17,104
5,725
""" This module contains the rule-based inference (rulebased_deduction engine) """ import itertools from collections import defaultdict from itertools import chain from excut.explanations_mining.descriptions import dump_explanations_to_file from excut.explanations_mining.descriptions_new import Description2, Atom, loa...
10,782
3,090
import torch.utils.data as data from PIL import Image import os import os.path import numpy as np import pdb import glob IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] def is_image_file(filename): return any(filename.endswith(extension) for extensi...
916
373
from floodcomparison.core import floodcomparison
49
14
import logging import random from datetime import timedelta from typing import TYPE_CHECKING from duration import to_iso8601 from pyramid.httpexceptions import HTTPBadRequest, HTTPCreated, HTTPNotFound, HTTPOk from weaver import sort from weaver.config import WEAVER_CONFIGURATION_ADES, WEAVER_CONFIGURATION_EMS, get_w...
7,842
2,474
# # PySNMP MIB module CISCO-VSI-CONTROLLER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VSI-CONTROLLER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
6,722
2,858
import base64 import os import arrow import httpx import streamlit as st import sweat from bokeh.models.widgets import Div APP_URL = os.environ["APP_URL"] STRAVA_CLIENT_ID = os.environ["STRAVA_CLIENT_ID"] STRAVA_CLIENT_SECRET = os.environ["STRAVA_CLIENT_SECRET"] STRAVA_AUTHORIZATION_URL = "https://www.strava.com/oau...
6,282
2,113
#!/usr/bin/env python #shamelessy stolen from: https://gitlab.com/dhj/easyufw # A thin wrapper over the thin wrapper that is ufw # Usage: # import easyufw as ufw # ufw.disable() # disable firewall # ufw.enable() # enable firewall # ufw.allow() # default allow -- allow all # ufw.allow...
3,395
1,117
import libsalt def test(salt_scenario): libsalt.start(salt_scenario) libsalt.setCurrentStep(25200) step = libsalt.getCurrentStep() while step <= 36000: if (step % 100 == 0): print("Simulation Step: ", step) test_funcs() libsalt.simulationStep() step = li...
1,325
468
#MenuTitle: Copy Layer to Layer # -*- coding: utf-8 -*- __doc__=""" Copies one master to another master in selected glyphs. """ import GlyphsApp import vanilla import math def getComponentScaleX_scaleY_rotation( self ): a = self.transform[0] b = self.transform[1] c = self.transform[2] d = self.transform[3] ...
8,348
3,300
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com """ Test of the general tokenizer """ from unit...
3,080
991
# STAR aligner single end mode, second pass # # This module runs the second pass of the STAR aligner 2 path # strategy. The goal is to align reads taking in account splice # junction found in the fist pass.. # # Inputs: # - sample_trim.fastq.gz # - splicing junction files (.tab) # # Output: # ...
1,962
594
from django.db import models class JobOffer(models.Model): company_name = models.CharField(max_length=50) company_email = models.EmailField() job_title = models.CharField(max_length=60) job_description = models.TextField() salary = models.PositiveIntegerField() city = models.CharField(max_leng...
531
166
from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib import messages from .forms import PictureUploadForm,CommentForm from .models import Image,Profile,Likes,Comments from django.contrib.auth.decorators import login_required from django.contrib .auth import authen...
4,926
1,408
"""Create diapivot annotation.""" import logging import pickle import xml.etree.ElementTree as etree import sparv.util as util from sparv import Annotation, Model, ModelOutput, Output, annotator, modelbuilder log = logging.getLogger(__name__) PART_DELIM1 = "^1" # @annotator("Diapivot annotation", language=["swe-1...
4,997
1,555
import os def get_root_path(): current_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(current_path))) ) return os.path.join(root_path, "xbot") def get_config_path(): config_path = os.path.abspath(os.path.join...
534
198
from django.utils.html import format_html from wagtail.wagtailcore import hooks @hooks.register('insert_editor_js') def enable_source(): return format_html( """ <script> registerHalloPlugin('hallohtml'); </script> """ )
274
83
from conftest import QL_URL import requests def test_api(): api_url = "{}/".format(QL_URL) r = requests.get('{}'.format(api_url)) assert r.status_code == 200, r.text assert r.json() == { "notify_url": "/v2/notify", "subscriptions_url": "/v2/subscriptions", "entities_...
440
154
from buildbot.process.remotecommand import RemoteCommand from buildbot.interfaces import WorkerTooOldError import stat class FileExists(object): """I check a file existence on the worker. I return True if the file with the given name exists, False if the file does not exist or that is a directory. Us...
1,981
547
from matplotlib import style from tqdm import tqdm style.use("ggplot") from gym_combat.envs.Arena.CState import State from gym_combat.envs.Arena.Entity import Entity from gym_combat.envs.Arena.Environment import Environment, Episode from gym_combat.envs.Common.constants import * from gym_combat.envs.Qtable import Qtab...
6,349
2,221
"""Hyper-distributions.""" from libqif.core.secrets import Secrets from libqif.core.channel import Channel from numpy import array, arange, zeros from numpy import delete as npdelete class Hyper: def __init__(self, channel): """Hyper-distribution. To create an instance of this class it is class i...
4,132
1,150
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program 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 Foundation, either version 3 of the Lic...
53,568
11,571
from ElementoMapa import ElementoMapa class Puerta (ElementoMapa): def __init__(self): self.abierta= True self.lado2=None self.lado1=None def get_abierta(self): return self.abierta def print_cosas(self): print("hola") def set_abierta(self, value): self.ab...
1,120
380
""" # Step 1 - Create the App # Step 2 - Create the Game # Step 3 - Build the Game # Step 4 - Run the App """ from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import C...
2,421
839
class SceneRelation: def __init__(self): self.on_ground = set() self.on_block = {} self.clear = set() def print_relation(self): print(self.on_ground) print(self.on_block) print(self.clear)
245
80
""" CS 238 Final Project: Bridge RL Agent Eric Lou & Kimberly Tran """ import copy import datetime import numpy as np import random from collections import namedtuple """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' REPRESENTATIONS OF BRIDGE Representing a "Card" as an integer: Cards 0 -> 12 are Club...
18,713
6,617
"""Data Test Suite.""" from aiogithubapi.objects import repository import pytest import os from homeassistant.core import HomeAssistant from custom_components.hacs.hacsbase.data import HacsData from custom_components.hacs.helpers.classes.repository import HacsRepository from custom_components.hacs.hacsbase.configuratio...
1,411
458
from collections import namedtuple from contextlib import contextmanager from threading import Barrier from typing import List, Callable import numpy from ._dtype import DType, combine_types SolveResult = namedtuple('SolveResult', [ 'method', 'x', 'residual', 'iterations', 'function_evaluations', 'converged', '...
44,836
13,203
import re from curtsies.formatstring import fmtstr, FmtStr from curtsies.termformatconstants import ( FG_COLORS, BG_COLORS, colors as CURTSIES_COLORS, ) from functools import partial from ..lazyre import LazyReCompile COLORS = CURTSIES_COLORS + ("default",) CNAMES = dict(zip("krgybmcwd", COLORS)) # hack...
2,736
1,019
# -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BANDPEAK', 's', 5, value) self.add_field('BANDL...
1,277
521
from ..imports import * from .. import utils as U from ..core import GenLearner class NodeClassLearner(GenLearner): """ ``` Main class used to tune and train Keras models for node classification Main parameters are: model (Model): A compiled instance of keras.engine.training.Model train_dat...
5,631
1,557
__author__ = "Yuyu Luo" import json import pandas class VegaZero2VegaLite(object): def __init__(self): pass def parse_vegaZero(self, vega_zero): self.parsed_vegaZero = { 'mark': '', 'data': '', 'encoding': { 'x': '', 'y': { ...
12,168
3,557
"""Library for executing user-defined dance.""" import logging from typing import Any, Dict, Optional, Callable import datetime import ac import ac.blocks from ac import ACs, AC JC = Dict[str, Any] class DanceStartException(Exception): pass class Step: """Base class for all specific dance steps.""" ...
6,254
2,068
"""Provide the ReportableMixin class.""" from ....const import API_PATH class ReportableMixin: """Interface for RedditBase classes that can be reported.""" def report(self, reason): """Report this object to the moderators of its subreddit. :param reason: The reason for reporting. Ra...
780
224
def _jpeg_compression(im): assert torch.is_tensor(im) im = ToPILImage()(im) savepath = BytesIO() im.save(savepath, 'JPEG', quality=75) im = Image.open(savepath) im = ToTensor()(im) return im
218
88
import collections import os.path from zope import component from zope import interface from zope.component.factory import Factory from sparc.configuration import container import mellon @interface.implementer(mellon.IByteMellonFile) class MellonByteFileFromFilePathAndConfig(object): def __init__(self, file_p...
3,158
879
"""Predefined Datasources. """ # toolbox imports from ...datasource import Datasource Datasource.register_instance('imagenet-val', __name__ + '.imagenet', 'ImageNet', section='val') # section='train' Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats', ...
1,157
393
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 15:58:44 2019 @author: babin """ posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215] dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.948, 0.948, 0.886, 0.8...
2,127
1,806
import numpy as np # This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution. class SimpleDataSet(): ''' A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i''' d...
4,999
2,032
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do t...
4,840
1,641
import torch import torch.nn as nn import torch.nn.functional as f from prettytable import PrettyTable from c2nl.modules.char_embedding import CharEmbedding from c2nl.modules.embeddings import Embeddings from c2nl.modules.highway import Highway from c2nl.encoders.transformer import TransformerEncoder from c2nl.decoder...
26,798
7,847
import logging from cattle import Config from cattle.utils import reply, popen from .compute import DockerCompute from cattle.agent.handler import BaseHandler from cattle.progress import Progress from cattle.type_manager import get_type, MARSHALLER from . import docker_client import subprocess import os import time ...
3,344
949
import sys import pytz #import xml.utils.iso8601 import time import numpy from datetime import date, datetime, timedelta from matplotlib import pyplot as plt from exchange import cb_exchange as cb_exchange from exchange import CoinbaseExchangeAuth from abc import ABCMeta, abstractmethod class strategy(object): """...
6,391
1,888
import numpy as np # Perceptron def predict_perceptron(inputs, weights): if np.dot(inputs, weights) > 0: return 1 else: return 0 def predict_perceptron_proper(inputs, weights): def step_function(input): return 1 if input > 0 else 0 def linear_model(inputs, weights): r...
715
243
""" Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator. Modified from train.py in the PyTorch BigGAN repo. """ import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim import utils import train_fns from sync_batchnorm import patch_replication_callback from torch.u...
7,303
2,390
import xlsxwriter import pandas as pd import numpy as np import mysql.connector australia=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Australia') brunei=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Brunei') cambodia=pd.read_excel(r'\Users\jesica\De...
6,452
2,754
#!/usr/bin/env python3 import os import re import glob import boto3 import requests import subprocess from time import sleep AWS_REGION = os.environ['AWS_REGION'] DEPLOY_UUID = os.environ['DEPLOY_UUID'] SERVICE_NAME = os.environ['SERVICE_NAME'] MOUNT_POINT = "/var/lib/" + SERVICE_NAME...
6,837
2,496
import csv import datetime import random import os from parsers.parser_base import ParserBase FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1) FILE_TIME_MICROSECOND = 10 def filetime_to_epoch_datetime(file_time): if isinstance(file_time, int): microseconds_since_file_time_epoch = file_time / FILE_TIME_MIC...
4,412
1,292
from django.http import HttpRequest from django.middleware.csrf import _compare_salted_tokens as equivalent_tokens from django.template.context_processors import csrf from django.test import SimpleTestCase class TestContextProcessor(SimpleTestCase): def test_force_token_to_string(self): request ...
593
199
import sys import das import traceback class ReservedNameError(Exception): def __init__(self, name): super(ReservedNameError, self).__init__("'%s' is a reserved name" % name) class VersionError(Exception): def __init__(self, msg=None, current_version=None, required_version=None): fullmsg = "ersion...
30,141
9,889
#! /usr/bin/python3 from help import * import time # short-forms are used, so as to reduce the .json file size # t : type - d or f # d : directory # f : file # ts : timestamp # dirs : The dictionary containing info about directory contents # time : edit time of the file/folder # s : size of the file/folder # p : full ...
4,829
1,592
# -*- coding: utf-8 -*- # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """ This module implements the 'scan-build' command API. To run the static analyzer against a bui...
31,693
9,190
#!/usr/bin/env python3 # pylint: disable=C0103 # pylint: disable=R0902 # pylint: disable=R0903 # pylint: disable=R0913 """ Définie la classe TableBorder """ class TableBorder: """ Facillite l'usage de l'UNICODE """ def __init__(self, top_left, top_split, top_right, mi...
1,460
551
from django.conf.urls import url from . import views urlpatterns = [ url(r'^register/', views.register), url(r'^login/', views.login), url(r'logout/', views.logout), url(r'search/', views.search) ]
216
81
#!/usr/bin/python # -*- coding: utf-8 -*- """Simple service for SL (Storstockholms Lokaltrafik).""" import datetime import json import logging from datetime import timedelta import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from ho...
28,508
8,283
""" A quick library to deal with searching simbad for info about a SN and parsing the results. Author: Isaac Shivvers, ishivvers@berkeley.edu, 2014 example SIMBAD uri query: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S """ import re from urllib2 import urlopen def get_SN_info( nam...
2,067
707
import os from math import cos from math import sin import Sofa.Core from splib.numerics import Quat, Vec3 from sofacontrol import measurement_models path = os.path.dirname(os.path.abspath(__file__)) class TemplateEnvironment: def __init__(self, name='Template', rayleighMass=0.1, rayleighStiffness=0.1, dt=0.01...
15,647
4,961
""" This file contains meta information and default configurations of the project """ RSC_YEARS = [1660, 1670, 1680, 1690, 1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790, 1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890, 1900, 1910, 1920] # cf. Chapter 4....
2,764
964
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd import util import os.path import pandas as pd import numpy as np import yaml import xa...
21,019
7,593
<<<<<<< HEAD """ 1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. Tools: help function 2. Write a Python program to p...
3,737
1,056
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # """ When a metaclass understands the extra keywords that can be passed during class declaration, it has to override all these to accommodate the change in signature """ class meta(type): ...
2,128
676
from cs1media import * import math def dist(c1, c2): r1, g1, b1 = c1 r2, g2, b2 = c2 return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) def chroma(img, key, threshold): w, h = img.size() for y in range(h): for x in range(w): p = img.get(x, y) if dist(p, key) < threshold: img.set...
434
212
import numpy as np import scipy import scipy.io import pylab import numpy import glob import pyfits def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0): diffrot = 0. ''' This is a simplified version of the class-based routines in spot_model.py. It generates a light curves for dark, p...
3,433
1,253
#!/usr/bin/env python3 """ usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 """ # FIXME: doc -k$N,$N and -n a...
862
317
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, getopt, httplib, urllib, json, os import oauth.oauth as oauth import datetime from configobj import ConfigObj import logging global logger logger = logging.getLogger(os.path.basename(__file__)) import davan.util.application_logger as log_manager #insert your ...
10,561
3,781
from collections import defaultdict import json import re import time from urllib.parse import urlparse import uuid import boto3 import boto3.exceptions import botocore.exceptions import markus import redis.exceptions import requests import requests.exceptions from sqlalchemy import select import sqlalchemy.exc from ...
16,286
4,725
import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "dcn", max_eval_batches = 1, batchsize_eval = 16384, batchsize = 16384, lr = 0.001, vvgpu...
6,636
1,954
import numpy as np from pydrake.common.value import AbstractValue from pydrake.math import RigidTransform from pydrake.perception import BaseField, Fields, PointCloud from pydrake.systems.framework import LeafSystem def _TransformPoints(points_Ci, X_CiSi): # Make homogeneous copy of points. points_h_Ci = np....
4,437
1,345
#!/usr/bin/env python """ @author Hongyi Hu © 2015 Massachusetts Institute of Technology """ import argparse import random import catan.db from catan.data import NodeMessage # test data STATUS_LIST = ['ok', 'injured', 'deceased'] # nodes def gen_nodes(n, db, start_lat, stop_lat, start_long, stop_long): assert...
5,115
1,813
# ------------------------------ # 200. Number of Islands # # Description: # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrou...
2,183
846
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the fseventsd record event formatter.""" from __future__ import unicode_literals import unittest from plaso.formatters import fseventsd from tests.formatters import test_lib class FseventsdFormatterTest(test_lib.EventFormatterTestCase): """Tests for the...
975
303
from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard from keras.models import load_model import random import numpy as np from scipy import misc import gc from keras.optimizers import Adam from imageio import imread from datetime import datetime import os import json import models from...
2,415
778
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'shape': [(3, 4), ()], 'dtype': [numpy.float16, numpy.float32, numpy.flo...
1,445
527
# Generated by Django 3.0.3 on 2020-03-24 09:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('exercises', '0018_photo_file'), ] operations = [ migrations.CreateModel( na...
1,693
478
from dm_control import suite from dm_control.rl.control import flatten_observation from dm_env import StepType import gym import numpy as np from metarl.envs import Step from metarl.envs.dm_control.dm_control_viewer import DmControlViewer class DmControlEnv(gym.Env): """ Binding for `dm_control <https://arxi...
2,773
835
from dagster import check from .house import Lakehouse from .table import create_lakehouse_table_def class SnowflakeLakehouse(Lakehouse): def __init__(self): pass def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata): return None def materialize(self, c...
1,446
452
from maya import cmds import pyblish.api import pype.api import pype.maya.action class ValidateLookNoDefaultShaders(pyblish.api.InstancePlugin): """Validate if any node has a connection to a default shader. This checks whether the look has any members of: - lambert1 - initialShadingGroup - initi...
1,976
536
from flask import Flask # initialize the app app = Flask(__name__) # execute iris function at /iris route @app.route("/iris") def iris(): from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) clf = LogisticRegression( rando...
446
158
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: Jan Profant <jan.profant@phonexia.com> # All Rights Reserved import os import logging import pickle import multiprocessing import numpy as np from sklearn.metrics.pairwise import cosine_similarity from vb...
10,714
3,446
import matplotlib.pyplot as plt import os def data_plotter(lattice_dict, datafile_dir, plot_dir): # total spaces on grid implies grid size total_cells = lattice_dict['E'][0] + lattice_dict['D_a'][0] + lattice_dict['D_b'][0] + lattice_dict['B'][0] n = int(total_cells**0.5) plt.figure(1) plt.plot...
984
389
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,056
282
import datetime import re from .exceptions import ObjectIsNotADate def format_date(value, format="%d %M %Y"): regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value) if regex is not None: date = datetime.date( int(regex.group("year")), int(regex.group("mont...
438
154
import numpy as np import os import logging from sklearn.model_selection import train_test_split DATASET_ROOT_FOLDER = os.path.abspath('datasets') class DataLoader: train = None validation = None test = None mode = None partial_dataset = None @staticmethod def load(train_path=None, valid...
3,966
1,126
# Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. mediaidade = '' nomelista = [] idadelista = [] sexolista = [] homens = [] mulherescommenosde20 =...
1,567
565
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
22,131
8,448
from selenium.webdriver.common.by import By class feature_modal: title_textbox = (By.ID, "feature-name") description_textbox = (By.ID, "description") save_button = (By.XPATH, "/html/body/app/div[3]/div[2]/div/div/div/button[1]")
243
90
from urllib2 import Request, urlopen, URLError import json request = Request('https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/') try: response = urlopen(request) data = response.read() except URLError, e: print 'error:', e stations= json.loads (data) #extract out station 2 stations2 = stations [7] prope...
1,101
419
def hello_world(): """Tests the import.""" return "Hello world!"
73
22
# Generated by Django 2.0.6 on 2018-07-02 19:13 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RenameField( model_name='echo', old_name='own...
748
229
import pytest from unittest import mock from aiohttp import helpers import datetime def test_parse_mimetype_1(): assert helpers.parse_mimetype('') == ('', '', '', {}) def test_parse_mimetype_2(): assert helpers.parse_mimetype('*') == ('*', '*', '', {}) def test_parse_mimetype_3(): assert (helpers.pars...
6,151
2,239
from os.path import join FAAS_ROOT="/lhome/trulsas/faas-profiler" WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads") #FAAS_ROOT="/home/truls/uni/phd/faas-profiler" WSK_PATH = "wsk" OPENWHISK_PATH = "/lhome/trulsas/openwhisk" #: Location of output data DATA_DIR = join(FAAS_ROOT, "..", "profiler_results") SYSTEM_CPU...
372
193
def sum1(a,b): try: c = a+b return c except : print "Error in sum1 function" def divide(a,b): try: c = a/b return c except : print "Error in divide function" print divide(10,0) print sum1(10,0)
211
102