text
string
size
int64
token_count
int64
# refactored from make_play to simplify # by Russell on 3/5/21 #from ttt_package.libs.move_utils import get_open_cells from ttt_package.libs.compare import get_transposed_games, reorient_games from ttt_package.libs.calc_game_bound import calc_game_bound from ttt_package.libs.maxi_min import maximin # find the best mo...
3,957
1,153
#!/usr/bin/env python3 # python 线程测试 import _thread import time from yvhai.demo.base import YHDemo def print_time(thread_name, interval, times): for cnt in range(times): time.sleep(interval) print(" -- %s: %s" % (thread_name, time.ctime(time.time()))) class RawThreadDemo(YHDemo): def __in...
805
296
# constants for configuration parameters of our tensorflow models LABEL = "label" IDS = "ids" # LABEL_PAD_ID is used to pad multi-label training examples. # It should be < 0 to avoid index out of bounds errors by tf.one_hot. LABEL_PAD_ID = -1 HIDDEN_LAYERS_SIZES = "hidden_layers_sizes" SHARE_HIDDEN_LAYERS = "share_hid...
3,108
1,334
# # Copyright 2016-2019 Games Creators Club # # MIT License # import math import pyroslib import pyroslib.logging import time from pyroslib.logging import log, LOG_LEVEL_ALWAYS, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG from rover import WheelOdos, WHEEL_NAMES from rover import normaiseAngle, angleDiference from challenge_uti...
32,025
11,218
PROTO = { 'spaceone.monitoring.interface.grpc.v1.data_source': ['DataSource'], 'spaceone.monitoring.interface.grpc.v1.metric': ['Metric'], 'spaceone.monitoring.interface.grpc.v1.project_alert_config': ['ProjectAlertConfig'], 'spaceone.monitoring.interface.grpc.v1.escalation_policy': ['EscalationPolicy']...
732
266
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contrib.contenttypes.models import ContentType from django.db import models class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = model...
2,929
958
import cv2 from cv2 import * import numpy as np from matplotlib import pyplot as plt ###############################SIFT MATCH Function################################# def SIFTMATCH(img1,img2): # Initiate SIFT detector sift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descri...
5,550
2,185
import dash from dash.exceptions import PreventUpdate import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import dash_table import plotly.express as ex import plotly.graph_objects as go import pandas as pd imp...
17,003
3,753
import pyxon.decode as pd def unobjectify(obj): """ Turns a python object (must be a class instance) into the corresponding JSON data. Example: >>> @sprop.a # sprop annotations are needed to tell the >>> @sprop.b # unobjectify function what parameter need >>> @sprop.c # to be written out....
3,479
1,105
# Segmentation script # ------------------- # This script lets the user segment automatically one or many images based on the default segmentation models: SEM or # TEM. # # Maxime Wabartha - 2017-08-30 # Imports import sys from pathlib import Path import json import argparse from argparse import RawTextHelpFormatter...
19,112
5,132
from dcstats.hedges import Hedges_d from dcstats.statistics_EJ import simple_stats as mean_SD import random import math def generate_sample (length, mean, sigma): #generate a list of normal distributed samples sample = [] for n in range(length): sample.append(random.gauss(mean, sigma)) return ...
1,746
667
from django.urls import path from . import views urlpatterns = [ path('', views.Records, name ="fRec"), ]
110
36
import pytest from spacy.training.example import Example from spacy.util import make_tempdir from spacy import util from thinc.api import Config TRAIN_DATA = [ ("I'm so happy.", {"cats": {"POSITIVE": 1.0, "NEGATIVE": 0.0}}), ("I'm so angry", {"cats": {"POSITIVE": 0.0, "NEGATIVE": 1.0}}), ] cfg_string = """ ...
2,022
709
import asyncio from ..core.common.io import input from .action_creator import ActionCreator class REPL: def __init__(self, action_queue, config, *args, **kwargs): self.action_queue = action_queue self.config = config async def run(self): await asyncio.sleep(1) print("Insert c...
712
196
"""Trainining script for seq2seq text-to-speech synthesis model. usage: train.py [options] options: --data-root=<dir> Directory contains preprocessed features. --checkpoint-dir=<dir> Directory where to save model checkpoints [default: checkpoints]. --hparams=<parmas> Hyper param...
35,606
11,564
#! /usr/bin/python2 import time start = time.time() import pygame, numpy import pygame.camera # Init display screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) pygame.display.set_caption("Magic Mirror") #pygame.mouse.set_visible(False) # Init font pygame.font.init() font_colour = 16, 117, 186 fonts = {40: p...
3,324
1,196
""".. Ignore pydocstyle D400. ======= Resolwe ======= Open source enterprise dataflow engine in Django. """ from resolwe.__about__ import ( # noqa: F401 __author__, __copyright__, __email__, __license__, __summary__, __title__, __url__, __version__, )
288
110
# %% [markdown] # # Testing python-som with audio dataset # %% [markdown] # # Imports # %% import matplotlib.pyplot as plt # import librosa as lr # import librosa.display as lrdisp import numpy as np import pandas as pd import pickle import seaborn as sns import sklearn.preprocessing from python_som import SOM FILE...
8,898
3,372
"""Prediction Engine - Update the data model with the most resent fixtures and results.""" from footy.domain import Competition class UpdateEngine: """Prediction Engine - Update the data model with the most resent fixtures and results.""" def __init__(self): """Construct a UpdateEngine object.""" ...
1,019
239
"""Script to embed pydeck examples into .rst pages with code These populate the files you see once you click into a grid cell on the pydeck gallery page """ from multiprocessing import Pool import os import subprocess import sys from const import DECKGL_URL_BASE, EXAMPLE_GLOB, GALLERY_DIR, HTML_DIR, HOSTED_STATIC_PAT...
2,286
785
import numpy as np import sympy as sp import re import os ###################### # # # 17 16 21 # # 18 15 22 # # 19 14 23 # # 20 01 24 # # 02 08 # # 03 09 # # 04 10 # # 05 11 # # 06 12 # # 07...
45,482
22,135
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key, misp_verifycert import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, misp_verifycert, 'json') def download_last(m, last, o...
1,223
417
from django.conf.urls import include, url from django.views.generic.base import TemplateView from . import views as core_views from .category.urls import urlpatterns as category_urls from .collection.urls import urlpatterns as collection_urls from .customer.urls import urlpatterns as customer_urls from .discount.urls ...
2,949
907
import os import sys import torch import yaml from functools import partial sys.path.append('../../../../') from trainers import trainer, frn_train from datasets import dataloaders from models.FRN import FRN args = trainer.train_parser() with open('../../../../config.yml', 'r') as f: temp = yaml.safe_load(f) data...
1,146
377
import argparse import argparse import os import numpy as np import torch from dataloaders.LoaderBase import LoaderBase import exp.feature.feature_utils as feature_utils def run_with_identifier(unit, corr_val, datasize, rank_names, loader, show_ols=True): loader.clear_cache() # Ex: 'nn_rank:0.01'. Then ext...
6,037
2,035
from gym_pcgrl.envs.reps.representation3D import Representation3D from PIL import Image from gym import spaces import numpy as np from gym_pcgrl.envs.probs.minecraft.mc_render import reps_3D_render """ The wide representation where the agent can pick the tile position and tile value at each update. """ class Wide3DRep...
2,430
660
"""This module contains the general information for AdaptorMenloQStats ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class AdaptorMenloQStatsConsts: MENLO_QUEUE_COMPONENT_N = "N" MENLO_QUEUE_COMPONENT_CPU = "cpu" ...
10,696
4,076
import unittest import pytest from old_password import old_password import csv import re @pytest.mark.parametrize("password,expected_hash", [ (None, None), ("", ""), ("a", "60671c896665c3fa"), ("abc", "7cd2b5942be28759"), ("ä", "0751368d49315f7f"), ]) def test_old_password(password, expected_hash...
980
331
# -*- coding: utf-8 -*- """ ------------------------------------------------- Description : Author : cmy date: 2020/1/2 ------------------------------------------------- """ import datetime import heapq import numpy as np import tensorflow as tf import time from metrics import ndcg_at_k from tr...
6,829
2,343
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 28 19:28:17 2019 @author: Wanling Song """ import mdtraj as md import numpy as np import pandas as pd import argparse import sys from collections import defaultdict import pickle import os import matplotlib matplotlib.use('Agg') import matplotlib.p...
84,211
27,832
# RT by Rext from asyncio import run from discord import Intents, Status, Game, AllowedMentions from core.bot import RT from data import SECRET try: from uvloop import install except ModuleNotFoundError: ... else: install() intents = Intents.default() intents.message_content = True intents.members = True bot = RT...
547
187
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import uuid import random import math import time import typing as t from . import experiment as hip # Demos from the README. If one of those ...
13,014
4,790
"""Ingredient dto. """ class Ingredient(): """Class to represent an ingredient. """ def __init__(self, name, availability_per_month): self.name = name self.availability_per_month = availability_per_month def __repr__(self): return """{} is the name.""".format(self.name)
313
103
import logging import groceries.api as groceries import barcodescanner.scan as barcode def main(): grocy = groceries.GrocyAPIClient() while True: scanner = barcode.Scan() line = scanner.PollScanner() if line != None: response = grocy.consume_barcode(line) loggin...
423
134
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="easy-icm-runner", version="1.0.6", author="Bachir El Koussa", author_email="bgkoussa@gmail.com", description="A wrapper for IBM ICMs Scheduler API Calls", long_description=long_descrip...
790
267
import unittest from molecule import onize_formula, update_equation_with_multiplier, flaten_formula, parse_molecule class MoleculeParserTestCases(unittest.TestCase): def test_onizing_formulas(self): self.assertEqual(onize_formula('H'), 'H1') self.assertEqual(onize_formula('H2O'), 'H2O1') ...
1,784
746
# -*- coding: utf-8 -*- class Config(object): def __init__(self): self.init_scale = 0.1 self.learning_rate = 1.0 self.max_grad_norm = 5 self.num_layers = 2 self.slice_size = 30 self.hidden_size = 200 self.max_epoch = 13 self.keep_prob = 0.8 se...
544
219
{ 'targets': [ { # have to specify 'liblib' here since gyp will remove the first one :\ 'target_name': 'mysql_bindings', 'sources': [ 'src/mysql_bindings.cc', 'src/mysql_bindings_connection.cc', 'src/mysql_bindings_result.cc', 'src/mysql_bindings_statement.cc', ...
859
274
# copyright Chad Dombrova chadd@luma-pictures.com # created at luma pictures www.luma-pictures.com """ ******************************* PyMEL ******************************* PyMEL makes python scripting in Maya work the way it should. Maya's command module is a direct translation of MEL commands into p...
1,272
376
from setuptools import find_packages, setup setup(name='ActT', version='0.6', description='Active Testing', url='', author='', author_email='none', license='BSD', packages=find_packages(), install_requires=[ 'numpy', 'pandas', 'matplotlib','scipy','scikit-learn',...
399
123
# deltat.py time difference calculation for sensor fusion # Released under the MIT License (MIT) # Copyright (c) 2018 Peter Hinch # Provides TimeDiff function and DeltaT class. # The following notes cover special cases. Where the device performing fusion # is linked to the IMU and is running MicroPython no special tre...
3,121
842
# -*- coding: utf-8 -*- """ Sony Colourspaces ================= Defines the *Sony* colourspaces: - :attr:`colour.models.RGB_COLOURSPACE_S_GAMUT`. - :attr:`colour.models.RGB_COLOURSPACE_S_GAMUT3`. - :attr:`colour.models.RGB_COLOURSPACE_S_GAMUT3_CINE`. - :attr:`colour.models.RGB_COLOURSPACE_VENICE_S_GAMUT3`. - ...
11,336
6,231
# -*- coding: UTF-8 -*- '''================================================= @Project -> File :EWC -> network @IDE :PyCharm @Author :Qiao Zhongzheng @Date :2021/6/23 20:28 @Desc : ==================================================''' from tensorflow.keras import Model from tensorflow.keras.layers import Dense,...
723
282
# TODO turn prints into actual error raise, they are print for testing def qSystemInitErrors(init): def newFunction(obj, **kwargs): init(obj, **kwargs) if obj._genericQSys__dimension is None: className = obj.__class__.__name__ print(className + ' requires a dimension') ...
1,909
582
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import os import pprint import unittest import numpy as np # pyre-fixme[21]: Could not find module `pytest`. import pytest import torch from parameterized import parameterized from reagent.core.types import R...
6,997
2,386
""" Created on June 7, 2016 a rule-based user simulator @author: xiul, t-zalipt """ import random class UserSimulator: """ Parent class for all user sims to inherit from """ def __init__(self, movie_dict=None, act_set=None, slot_set=None, start_set=None, params=None): """ Construc...
1,949
688
from .kendall_w import compute_w __version__ = (1, 0, 0)
57
27
from django.contrib import admin from .models import * # Register your models here. admin.site.register(ErrorGroup) admin.site.register(Error)
142
39
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
2,132
756
from rest_framework import serializers from .models import * class CoordinatorSerializer(serializers.ModelSerializer): # ModelID = serializers.CharField(max_length=100, required=True) CourseID = serializers.CharField(max_length=100, required=True) FName = serializers.CharField(max_length=100, required=Fa...
25,419
7,468
""" some math tools """ class MathTools: """ some math tools """ def add(a, b): """ add two values """ return a + b def sub(a, b): """ subtract two values """
209
71
def insertion_sort(l): for i in range(1, len(l)): j = i - 1 key = l[i] while (j >= 0) and (l[j] > key): l[j + 1] = l[j] j -= 1 l[j + 1] = key m = int(input().strip()) ar = [int(i) for i in input().strip().split()] insertion_sort(ar) print(" ".join(map(str, a...
325
137
#!/usrb/bin/env python # Copyright (c) 2019, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # - Redistributions of source code must retain the above copyright notice, # t...
3,279
1,157
# 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 import copy from typing import Any import torch from torch_mlir_torchscript.e2e_test.framework import TestConfig, Tr...
1,244
357
from .enums import PNHeartbeatNotificationOptions, PNReconnectionPolicy from . import utils class PNConfiguration(object): DEFAULT_PRESENCE_TIMEOUT = 300 DEFAULT_HEARTBEAT_INTERVAL = 280 def __init__(self): # TODO: add validation self.uuid = None self.origin = "ps.pndsn.com" ...
2,495
764
#!/usr/bin/env python3 # # Copyright (c) 2019, The OpenThread Authors. # 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 # ...
18,305
5,646
import cv2 import numpy as np from keras.models import model_from_json from keras.preprocessing.image import img_to_array #load model model = model_from_json(open("fer.json", "r").read()) #change the path accoring to files #load weights model.load_weights('fer.h5') #change the path accor...
1,770
767
age = 24 print("My age is " + str(age) + " years ") # the above procedure is tedious since we dont really want to include str for every number we encounter #Method1 Replacement Fields print("My age is {0} years ".format(age)) # {0} is the actual replacement field, number important for multiple replacement fields ...
1,871
723
#!/usr/bin/env python import logging from datetime import datetime logging.basicConfig(level=logging.WARNING) import os import urllib2, base64, json import dateutil.parser def from_ISO8601( str_iso8601 ): return dateutil.parser.parse(str_iso8601) def to_ISO8601( timestamp ): return timestamp.isoformat() de...
5,391
1,711
from typing import Optional import torch from gs_divergence import gs_div def symmetrized_gs_div( input: torch.Tensor, target: torch.Tensor, alpha: float = -1, lmd: float = 0.5, reduction: Optional[str] = 'sum', ) -> torch.Tensor: lhs = gs_div(input, target, alpha=alpha, lmd=lmd, reduction=re...
432
168
import argparse import helper as hp import torch import os import json parser = argparse.ArgumentParser(description = 'train.py') parser.add_argument('--data-dir', nargs = '*', action = "store", default = "./flowers/", help = "folder path for data") parser.add_argument('--save-dir', action = "store", required=True, h...
1,946
649
def Euler0001(): max = 1000 sum = 0 for i in range(1, max): if i%3 == 0 or i%5 == 0: sum += i print(sum) Euler0001()
154
73
''' * Copyright (c) 2022, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause * By Junnan Li ''' import warnings warnings.filterwarnings("ignore") from models.vit import V...
11,020
3,165
import numpy as np from numpy.random import randn import pytest import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm from pandas.core.reshape.concat import concat from pandas.core.reshape.merge import merge @pytest.fixture def left(): """left dataf...
28,524
10,661
# -*- coding: utf-8 -*- from requests import ( get, post, put ) from base import api # noqa: I100 from base.populators import ( # noqa: I100 DatasetCollectionPopulator, DatasetPopulator, wait_on ) class HistoriesApiTestCase(api.ApiTestCase): def setUp(self): super(HistoriesApiT...
11,894
3,613
""" 0461. Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ...
701
240
#! /usr/local/bin/python3 # -*- coding: UTF-8 -*- # 抓取 妹子图 并存储 import urllib.request import os import random def open_url(url): request = urllib.request.Request(url) request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0') ...
2,136
942
print('load extractor_batch') # Utility to run multiple feature extraction # diagrams over many files with multiple threats import pandas as pd import os import sys import glob from tqdm.auto import tqdm from queue import Queue from threading import Thread from datetime import datetime import time im...
7,324
2,253
from .models import Tenant def tenant(request): """ Return context variables required by apps that use django-site-multitenancy. If there is no 'tenant' attribute in the request, extract one from the request. """ if hasattr(request, 'tenant'): tenant = request.tenant else: ten...
393
115
from django import forms from .models import Project class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["title", "describe", "technology"]
185
50
""" Person class """ # Create a Person class with the following properties # 1. name # 2. age # 3. social security number class Person: def __init__(self, name, age, social_number): self.name = name self.age = age self.social = social_number p1 = Person("John", 36, "111-11-1111") print...
361
137
# copyright (c) 2018 paddlepaddle authors. 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 app...
19,452
6,101
#!/usr/bin/env python """Classes to store and manage hunt results. """ from grr.lib import rdfvalue from grr.lib import registry from grr.lib.rdfvalues import structs as rdf_structs from grr_response_proto import jobs_pb2 from grr.server import access_control from grr.server import aff4 from grr.server import data_sto...
4,289
1,213
""" Module for higher level SharePoint REST api actions - utilize methods in the api.py module """ class Site(): def __init__(self, sp): self.sp = sp @property def info(self): endpoint = "_api/site" value = self.sp.get(endpoint).json() return value @property def w...
4,748
1,441
import os import glob import shutil import yaml from IPython import embed import pytest import numpy as np from pypeit.par.util import parse_pypeit_file from pypeit.pypeitsetup import PypeItSetup from pypeit.tests.tstutils import dev_suite_required, data_path from pypeit.metadata import PypeItMetaData from pypeit.s...
6,317
2,364
from copy import copy from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, cast from pypika import Table from pypika.terms import Criterion from tortoise.exceptions import FieldError, OperationalError from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance, RelationalFi...
15,930
4,672
import numpy as np # Change False to True for this block of code to see what it does # NumPy axis argument if True: a = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(a.sum()) print(a.sum(axis=0)) print(a.sum(axis=1)) # Subway ridership for 5 stations on 10 different...
1,372
647
import numpy as np import pickle import os def GenerateFeature_alpha(ligand_name, working_dir): Cut = 12.0 LIGELE = ['C','N','O','S','CN','CO','CS','NO','NS','OS','CCl','CBr','CP','CF','CNO','CNS','COS','NOS','CNOS','CNOSPFClBrI','H','CH','NH','OH','SH','CNH','COH','CSH','NOH','NSH','OSH','CNOH','CNSH','COSH'...
9,956
3,610
import re import sys from email.message import EmailMessage def get_message_by_id(msgs, msg_id): # TODO: handle weird brackets stuff for msg in msgs: if msg["message-id"] == msg_id: return msg return None def strip_prefix(s, prefix): if s.startswith(prefix): s = s[len(prefix):] return s def flatten_heade...
1,105
410
from haven import haven_chk as hc from haven import haven_results as hr from haven import haven_utils as hu import torch import torchvision import tqdm import pandas as pd import pprint import itertools import os import pylab as plt import exp_configs import time import numpy as np from src import models from src impo...
7,930
2,460
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não é possível atualizar ou excluir os resultados de uma junção', '# of International Staff': '# De equipe internacional'...
297,511
93,414
from .. import ba, cb, actor from ..service import account class A0(ba.App): center: cb.CallBackManager a: account.Account def __init__(self, stg: actor.GateWay): a = account.Account() center = cb.CallBackManager() stg.init(a=a, center=center, broker=cb.CallBackManager()) ...
598
196
#%% #Calculate_capacity
25
12
import builtins builtins.foo = 'bar' foo # foo
49
20
""" Schema Validation Tests a dictionary against a schema to test for conformity. Schema definition is similar to - but not the same as - avro schemas Supported Types: - string - a character sequence - format - numeric - a number - min: - max - date - a datetime.date or...
7,802
2,454
from fuzzconfig import FuzzConfig import interconnect import nets import pytrellis import re jobs = [ { "pos": [(47, 0), (48, 0), (49, 0)], "cfg": FuzzConfig(job="PIOROUTEL", family="ECP5", device="LFE5U-45F", ncl="pioroute.ncl", tiles=["MIB_R47C0:PICL0", "MIB_R48C0:PICL1"...
2,350
949
import tensorflow as tf def _is_tensor(x): """Returns `True` if `x` is a symbolic tensor-like object. From http://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/image_ops_impl.py Args: x: A python object to check. Returns: `True` if `x` is a `tf.Tensor` or `tf.Va...
6,841
2,197
# BS mark.1-55 # /* coding: utf-8 */ # BlackSmith plugin # everywhere_plugin.py # Coded by: WitcherGeralt (WitcherGeralt@jabber.ru) # http://witcher-team.ucoz.ru/ def handler_everywhere(type, source, body): if body: args = body.split() if len(args) >= 2: mtype = args[0].strip().lower() if mtype == u'чат...
1,169
537
from utils import TreeNode class Solution: def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool: if p is None and q is None: return True if not p or not q: return False return p.val == q.val and self.is_same_tree(p.left, q.left) and self.is_same_tree(p.right, q....
327
110
# Copyright 2020 Curtin University # # 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 writi...
6,946
1,965
# Copyright 2016 The TensorFlow Authors. 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...
16,283
5,011
# @Author: Manuel Rodriguez <valle> # @Date: 10-May-2017 # @Email: valle.mrv@gmail.com # @Last modified by: valle # @Last modified time: 23-Feb-2018 # @License: Apache license vesion 2.0 from kivy.uix.modalview import ModalView from kivy.uix.button import Button from kivy.properties import ObjectProperty, String...
1,442
500
""" The foo integration instruments the bar and baz features of the foo library. Enabling ~~~~~~~~ The foo integration is enabled automatically when using :ref:`ddtrace-run <ddtracerun>` or :ref:`patch_all() <patch_all>`. Or use :ref:`patch() <patch>` to manually enable the integration:: from ddtrace import pa...
1,122
319
from subprocess import check_output, CalledProcessError from ast import literal_eval from time import sleep from helpers import setup_logger logger = setup_logger(__name__, "warning") current_interface = None #wpa_cli related functions and objects def wpa_cli_command(*command): run = ["wpa_cli"] if current_...
8,194
2,451
#!/usr/bin/env python from __future__ import with_statement import sys, traceback, os, os.path import xml.dom.minidom import logging class Task(object): @staticmethod def waitAll(tasks): pass class FetchFile(Task): def __init__(self, url): self.url = url def _...
17,635
5,181
from __future__ import division import fitsio """ A FITS file is comprised of segments called Header/Data Units (HDUs), where the first HDU is called the 'Primary HDU', or 'Primary Array'. The primary data array can contain a 1-999 dimensional array of 1, 2 or 4 byte integers or 4 or 8 byte floating point numbers usi...
4,169
1,157
#!/usr/bin/env python3 # Copyright 2021 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. """Simple script for updating musl from extern...
1,727
608
from __future__ import absolute_import, division, print_function, unicode_literals import logging # Used in the exec() call below. from scout_apm.core.monkey import monkeypatch_method, unpatch_method # noqa: F401 from scout_apm.core.tracked_request import TrackedRequest # noqa: F401 logger = logging.getLogger(__na...
3,358
961
import random from typing import Optional import factory from common.tests import factories from measures.sheet_importers import MeasureSheetRow class MeasureSheetRowFactory(factory.Factory): """ A factory that produces a row that might be read from a sheet of measures as recognised by the :class:`measu...
3,235
928
from abc import ABC, abstractmethod import collections import pandas as pd from autoscalingsim.utils.error_check import ErrorChecker class Correlator(ABC): _Registry = {} @abstractmethod def _compute_correlation(self, metrics_vals_1 : pd.Series, metrics_vals_2 : pd.Series, lag : int): pass ...
6,077
1,968