text
string
size
int64
token_count
int64
# # Copyright (c) 2014, 2016, 2018, 2020 LexisNexis Risk Data Management Inc. # # This file is part of the RadSSH software package. # # RadSSH is free software, released under the Revised BSD License. # You are permitted to use, modify, and redsitribute this software # according to the Revised BSD License, a copy of wh...
5,288
1,538
''' pymmh3 was written by Fredrik Kihlander and enhanced by Swapnil Gusani, and is placed in the public domain. The authors hereby disclaim copyright to this source code. pure python implementation of the murmur3 hash algorithm https://code.google.com/p/smhasher/wiki/MurmurHash3 This was written for the times when y...
14,153
5,862
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import dlite thisdir = os.path.abspath(os.path.dirname(__file__)) class Person: def __init__(self, name, age, skills): self.name = name self.age = age self.skills = skills def __repr__(self): return 'Person(%r, %r, %r)'...
950
350
''' 연속 부분 최대합 nn개의 숫자가 주어질 때, 연속 부분을 선택하여 그 합을 최대화 하는 프로그램을 작성하시오. 예를 들어, 다음과 같이 8개의 숫자가 있다고 하자. 1 2 -4 5 3 -2 9 -10 이 때, 연속 부분이란 연속하여 숫자를 선택하는 것을 말한다. 가능한 연속 부분으로써 [1, 2, -4], [5, 3, -2, 9], [9, -10] 등이 있을 수 있다. 이 연속 부분들 중에서 가장 합이 큰 연속 부분은 [5, 3, -2, 9] 이며, 이보다 더 합을 크게 할 수는 없다. 따라서 연속 부분 최대합은 5+3+(-2)+9 = 15 이다...
807
725
#!/usr/bin/env python3 import unittest from mockdock import dns class DNSTest(unittest.TestCase): def test_build_packet(self): data = b"^4\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01" packet = dns.build_packet(data, "192.168.0.1") expeced_result = b"^4\x81...
505
312
""" Copyright 2019, Amazon Web Services Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
1,490
442
import asyncio import discord from datetime import datetime from operator import itemgetter from discord.ext import commands from Cogs import Nullify from Cogs import DisplayName from Cogs import UserTime from Cogs import Message def setup(bot): # Add the bot...
26,845
8,408
"""Métodos de preprocessamento de testes individuais """ import pandas as pd import numpy as np import math def test_1(df, seed=0): """training: balanced; test: balanced training: 80k (40k 0, 40k 1) test: 20k (10k 0, 10k 1) """ df_ones = df[df['label'] == 1] df_zeros = df[df['label'] ...
6,688
2,720
# This file is automatically generated by the generate_constants_module.py script in wrappers/Python. # DO NOT MODIFY THE CONTENTS OF THIS FILE! from __future__ import absolute_import from . import _constants INVALID_PARAMETER = _constants.INVALID_PARAMETER igas_constant = _constants.igas_constant imolar_mass = _cons...
7,103
3,148
import random import torch.utils.data.sampler class BalancedBatchSampler(torch.utils.data.sampler.BatchSampler): def __init__( self, dataset_labels, batch_size=1, steps=None, n_classes=0, n_samples=2 ): """ Create a balanced batch sampler for label based...
2,857
821
#!/usr/bin/env python """ 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");...
1,416
423
from sklearn import svm, metrics import random import re def split(rows): data = [] labels = [] for row in rows: data.append(row[0:4]) labels.append(row[4]) return (data, labels) def calculate_score(train, test): train_data, train_label = split(train) test_data, test_la...
1,162
438
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_specs2_specs2_fp_2_12", artifact = "org.specs2:specs2-fp_2.12:4.8.3", artifact_sha256 = "777962ca58054a9ea86e294e025453ecf394c60084c28bd61...
2,587
1,343
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a == 0 and b == 0: print("INF") else: if (d - b * c / a) != 0 and (- b / a) == (- b // a): print(- b // a) else: print("NO")
224
95
class resampler: def __init__(self): import pandas as pd from sklearn.preprocessing import LabelEncoder from collections import Counter import numpy as np self.bins = 3 self.pd = pd self.LabelEncoder = LabelEncoder self.Counter = Counter ...
4,265
1,298
import os import pathlib import sklearn.model_selection import tarfile import torch import torchaudio import urllib.request here = pathlib.Path(__file__).resolve().parent def _split_data(tensor, stratify): # 0.7/0.15/0.15 train/val/test split (train_tensor, testval_tensor, train_stratify, testval_strati...
4,920
1,604
from datetime import datetime from typing import List from flask import Blueprint, jsonify, request, json from app.models.products import Product, Category, products_categories from app import db products_blueprint = Blueprint('products', __name__) def create_or_get_categories(p: dict) -> List[Category]...
5,652
1,658
import pytest from httmock import urlmatch, HTTMock from util.config import URLSchemeAndHostname from util.config.validator import ValidatorContext from util.config.validators import ConfigValidationException from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator from test.fixtures i...
1,701
525
# -*- coding: utf-8 -*- """ Created on Fri Mar 15 16:51:16 2019 @author: Silvan """ import numpy as np import scipy import matplotlib.pyplot as plt k=1000 n1=2.0 n2=1.0 alpha=np.pi/6.0 beta=np.arcsin(n2/n1*np.sin(alpha)) ya=1.0 xa=-ya*np.tan(alpha) yb=-1.0 xb=-yb*np.tan(beta) def s(x): ...
2,414
1,362
"""Remove the readthedocs elasticsearch index.""" from __future__ import absolute_import from django.conf import settings from django.core.management.base import BaseCommand from elasticsearch import Elasticsearch class Command(BaseCommand): """Clear elasticsearch index.""" def handle(self, *args, **opti...
444
125
""" BigGAN: The Authorized Unofficial PyTorch release Code by A. Brock and A. Andonian This code is an unofficial reimplementation of "Large-Scale GAN Training for High Fidelity Natural Image Synthesis," by A. Brock, J. Donahue, and K. Simonyan (arXiv 1809.11096). Let's go. """ import datetime impor...
7,574
2,384
# __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ import os import time import random import shutil from glob import glob import traceback import sys from geocamUtil im...
1,693
572
# Ce fichier contient (au moins) cinq erreurs. # Instructions: # - tester jusqu'à atteindre 100% de couverture; # - corriger les bugs;" # - envoyer le diff ou le dépôt git par email.""" import hypothesis from hypothesis import given, settings from hypothesis.strategies import integers, lists class BinHeap: #st...
5,752
2,278
# -*- coding: utf-8 -*- """The ``snewpy.snowglobes`` module contains functions for interacting with SNOwGLoBES. `SNOwGLoBES <https://github.com/SNOwGLoBES/snowglobes>`_ can estimate detected event rates from a given input supernova neutrino flux. It supports many different neutrino detectors, detector materials and in...
22,455
7,406
from typing import List, Tuple from omegaconf import DictConfig import torch import torch.nn as nn import torch.nn.functional as F from rlcycle.common.abstract.loss import Loss class DQNLoss(Loss): """Compute double DQN loss""" def __init__(self, hyper_params: DictConfig, use_cuda: bool): Loss.__in...
4,621
1,616
"""viewer application which allows to interactively view spatio-temporal gap filling results""" import os import argparse from datetime import datetime, timedelta from tkinter import Canvas, Tk, Button, RAISED, DISABLED, SUNKEN, NORMAL import numpy as np from PIL import Image, ImageTk import probgf.media as media cla...
12,518
4,646
#!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from django.forms import ValidationError from django.http import QueryDict from django.test import TestCase from django.test.client import Client from paypal.pro.fields import CreditCardField fr...
4,946
1,859
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 19:46:40 2020 @author: Intel """ def displayPathtoPrincess(n,grid): me_i=n//2 me_j=n//2 for i in range(n): if 'p' in grid[i]: pe_i=i for j in range(n): if 'p'==grid[i][j]: pe...
1,010
398
import matplotlib.pyplot as plt import pybedtools import pandas as pnd import numpy as np import tabix import matplotlib.ticker as ticker from matplotlib.patches import Rectangle from matplotlib.patches import Arrow from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib.cm as cm imp...
65,397
19,778
""" File containing DFA and NFA public classes """ import collections.abc from itertools import product, chain, combinations from string import printable from typing import ( AbstractSet, Container, FrozenSet, Iterable, List, Mapping, MutableMapping, Optional, Set, Tuple, Uni...
31,171
8,635
#!/usr/bin/env python3 import unittest from roman_number_generator import arabic_to_roman class Test(unittest.TestCase): def _start_arabic_to_roman(self): self.assertRaises(ValueError, arabic_to_roman, 4000) self.assertEqual(arabic_to_roman(4), "IV") self.assertEqual(arabic_to_roman(12),...
429
168
from infrastructure.satnogClient import SatnogClient import os class ModuleBase: def __init__(self, working_dir): self.working_dir = working_dir def runAfterDownload(self, file_name, full_path, observation): raise NotImplementedError()
261
74
#!/usr/bin/env python3 # # Oregano - a lightweight Ergon client # CashFusion - an advanced coin anonymizer # # Copyright (C) 2020 Mark B. Lundeberg # # 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 So...
45,537
12,815
import matplotlib.pyplot as plt def countvalues(dataframe, subject): # Filtrem i tractem el dataset economydf = filtrar(dataframe, "economy") # el printem printar(economydf, subject) # Filtrem ara per subject infected i ho desem en un altre df infectedf = filtrar(dataframe, "infected") #...
2,229
861
# Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container CONTAINER = "filipfilmar/ebook-buildenv:1.1" # Use this for quick local runs. #CONTAINER = "ebook-builden...
18,987
6,032
n = int(input()) coelho = rato = sapo = contador = 0 for i in range(0, n): q, t = input().split(' ') t = t.upper() q = int(q) if 1 <= q <= 15: contador += q if t == 'C': coelho += q elif t == 'R': rato += q elif t == 'S': sapo += q po...
715
313
# coding: utf-8 # Copyright (c) 2015 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE file) from kivy.uix.boxlayout import BoxLayout from gravur.common.labelbox import LabelBox # NOQA from gravur.utils import load_widget @load_widget class AmountInput(BoxLayout): pass
299
115
import datetime class Top(object): """class TopSeries stores the information of a series of top commands :: echo -n 'Timestamp: '; date +%F-%H:%M:%S top -b -n1 [-i] [-c] over short intervals to monitor the same set of processes over time. An example input content looks like below, ...
17,156
4,999
# -*- coding: utf8 -*- # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. import os import platform import time import pytest import zmq from zmq.tests import BaseZMQTestCase, skip_pypy class TestDraftSockets(BaseZMQTestCase): def setUp(self): if not zmq.DRAFT_AP...
1,458
478
class APIError(Exception): """ raise APIError if receiving json message indicating failure. """ def __init__(self, error_code, error, request): self.error_code = error_code self.error = error self.request = request Exception.__init__(self, error) def __str__(self): ...
460
130
#coding:utf-8 class SystemDeviceType(object): InnerBox = 1 # 主屏分离的室内主机 InnerScreen = 2 # 主屏分离的室内屏 OuterBox = 3 # 室外机 PropCallApp = 4 # 物业值守 PropSentryApp = 5 # 物业岗亭机 Others = 10 ValidatedList = (1,2,3,4,5) class Constants(object): SUPER_ACCESS_TOKEN = 'YTU3NzV...
367
217
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from django_qbe.exports import formats urlpatterns = patterns('django_qbe.views', url(r'^$', 'qbe_form', name="qbe_form"), url(r'^js/$', 'qbe_js', name="qbe_js"), url(r'^results/bookmark/$', 'qbe_bookmark', name="qbe_bookma...
667
264
# -*- coding:utf-8 -*- # Author: RubanSeven # import cv2 import numpy as np # from transform import get_perspective_transform, warp_perspective from warp_mls import WarpMLS def distort(src, segment): img_h, img_w = src.shape[:2] cut = img_w // segment thresh = cut // 3 # thresh = img_h...
5,264
2,211
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self, starting_vertex, end_vertex): self.graph[starting_vertex].append(end_vertex) def printAllPaths(self, starting_vertex, target_vertex): visitedVertices = defaultdic...
1,347
433
# testing the output of pipegeojson against different input types import berrl as bl import itertools # making line with csv file location line1=bl.make_line('csvs/line_example.csv') # making line with list testlist=bl.read('csvs/line_example.csv') line2=bl.make_line(testlist,list=True) # testing each line geojson ...
1,958
708
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 8 16:19:07 2017 @author: ajaver """ import os import cv2 import sys import glob import threading from functools import partial main_dir = '/Volumes/behavgenom_archive$/Celine/raw/' fnames = glob.glob(os.path.join(main_dir, '**', '*.avi')) fnames =...
912
348
from devito.ir import Call from devito.passes.iet.definitions import DataManager from devito.passes.iet.langbase import LangBB __all__ = ['CBB', 'CDataManager'] class CBB(LangBB): mapper = { 'aligned': lambda i: '__attribute__((aligned(%d)))' % i, 'host-alloc': lambda i, j, k: ...
480
166
#!/usr/bin/env python3 """Test methods about image process Make sure the existance of the images """ from ell import * import numpy as np _filter = Filter.from_name('db4') def test_resize(): chennal=0 c = ImageRGB.open('src/lenna.jpg') d=c.resize(minInd=(-100,-100), maxInd=(100,100)) d.to_image() ...
2,026
907
# PyTorch import torch from torch.utils.data import IterableDataset, DataLoader from donkeycar.utils import train_test_split from donkeycar.parts.tub_v2 import Tub from torchvision import transforms from typing import List, Any from donkeycar.pipeline.types import TubRecord, TubDataset from donkeycar.pipeline.sequence ...
5,991
1,825
import os from tornado.template import Template __SNIPPET__ = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_snippet') def T(name, **kw): t = Template(open(os.path.join(__SNIPPET__, name + '.html'), 'rb').read()) return t.generate(**dict([('template_file', name)] + globals().items() + kw.items()))
316
118
""" Support for getting the disk temperature of a host. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.hddtemp/ """ import logging from datetime import timedelta from telnetlib import Telnet import voluptuous as vol import homeassistant.helpers....
3,857
1,232
import random prefix = [ 'Look at you! ', 'Bless ', 'Bless! ', 'I heard about that! ', 'Amen!', 'You and the kids doing alright?', 'Miss ya\'ll!' ] suffix = [ '. Amen!', '. God bless america', '. God bless!', ' haha', '. love ya!', '. love ya\'ll!', ] def add_pre_suf(sentence): if random.randint(1,10) <= 6: ...
1,402
509
import telegram from django.conf import settings from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.views.generic import View from django.views.decorators.csrf import csrf_exempt from braces.views import CsrfExemptMixin from rest_framework.authentication import Bas...
1,303
368
import os from datetime import datetime from os.path import join import pathlib from tqdm import tqdm import argparse import torch from torch import nn, optim from torch.autograd import Variable import torchvision from torchvision.transforms import Pad from torchvision.utils import make_grid import repackage repackage...
9,053
3,327
from django.conf.urls import url from django.urls import path, include,re_path from . import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), path('projects', views.projects, name='projects'),...
580
196
from six.moves import urllib from kiwi.store.tracking.file_store import FileStore class PluginFileStore(FileStore): """FileStore provided through entrypoints system""" def __init__(self, store_uri=None, artifact_uri=None): path = urllib.parse.urlparse(store_uri).path if store_uri else None s...
407
123
from io import BytesIO import json import urllib.parse from collections import OrderedDict from PIL import Image import numpy as np import pytest @pytest.fixture(scope='module') def flask_app(): from terracotta.server import create_app return create_app() @pytest.fixture(scope='module') def client(flask_a...
12,815
5,295
def base_conv(n, input_base=10, output_base=10): """ Converts a number n from base input_base to base output_base. The following symbols are used to represent numbers: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ n can be an int if input_base <= 10, and a string otherwise. ...
1,695
715
import logging from typing import Dict, List, Optional import numpy as np import qiskit from qiskit.circuit import Barrier, Delay, Reset from qiskit.circuit.library import (CRXGate, CRYGate, CRZGate, CZGate, PhaseGate, RXGate, RYGate, RZGate, U1Gate, ...
13,612
4,239
def help(): return ''' Isotropic-Anisotropic Filtering Norm Nesterov Algorithm Solves the filtering norm minimization + quadratic term problem Nesterov algorithm, with continuation: argmin_x || iaFN(x) ||_1/2 subjected to ||b - Ax||_2^2 < delta If no filter is provided, solves the L1. Continuation is perf...
5,616
1,878
import itertools import BTrees from persistent import Persistent from ZODB.broken import Broken from zope.interface import implementer _marker = object() from .. import exc from ..interfaces import ( IResultSet, STABLE, ) @implementer(IResultSet) class ResultSet(object): """Implements :class:`hypatia.i...
6,952
2,025
# Generated by Django 3.2.3 on 2021-05-30 04:28 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('realtors', '0001_initial'), ] operations = [ migrations.Cr...
2,140
644
import asyncio import discord # Just with a function to add to the bot. async def on_message(message): if not message.author.bot: await message.channel.send(f"{message.author.mention} a envoyé un message!") # A Listener already created with the function from discordEasy.objects import Listener async def on_messa...
483
155
import os import random from flask import Flask, request, send_from_directory from werkzeug.utils import secure_filename from pianonet.core.pianoroll import Pianoroll from pianonet.model_inspection.performance_from_pianoroll import get_performance_from_pianoroll app = Flask(__name__) base_path = "/app/" # base_pat...
4,024
1,434
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from plotly.subplots import make_subplots import logging import json import os import pandas as pd from datetime import datetime from datetime import timedelta fro...
4,965
1,773
# -*- coding: utf-8 -*- __author__ = "Paul Schifferer <dm@sweetrpg.com>" """ """ from flask_rest_jsonapi import ResourceList, ResourceDetail, ResourceRelationship from sweetrpg_library_objects.api.system.schema import SystemAPISchema from sweetrpg_api_core.data import APIData from sweetrpg_library_objects.model.syste...
1,106
351
from robot import __version__ as ROBOT_VERSION import sys import tempfile import textwrap import unittest import shutil import subprocess class PabotOrderingGroupTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmpdir) def ...
6,862
2,138
#!/usr/bin/python # -*- coding: latin-1 -*- """Setup script.""" try: from setuptools import setup except ImportError: from distutils.core import setup try: import pageviewapi version = pageviewapi.__version__ except ImportError: version = 'Undefined' classifiers = [ 'Development Status :: 4...
984
309
#a2_t1b.py #This program is to convert Celsius to Kelvin def c_to_k(c): k = c + 273.15 #Formula to convert Celsius to Kelvin return k def f_to_c(f): fa = (f-32) * 5/9 #Formula to convert Fareheit to Celsius return fa c = 25.0 f = 100.0 k = c_to_k(c) fa = f_to_c(f) print("Celsius of " + str(c) + " is...
416
205
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse, reverse_lazy from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect f...
2,702
693
"""Flask App configuration file.""" import logging import os import dotenv import frontend.constants as constants dotenv.load_dotenv(os.path.join(constants.BASEDIR, "frontend.env")) class Base: """Configuration class used as base for all environments.""" DEBUG = False TESTING = False LOGGING_FO...
1,997
629
# ElasticQuery # File: tests/test_dsl.py # Desc: tests for ElasticQuery DSL objects (Filter, Query, Aggregate) from os import path from unittest import TestCase from jsontest import JsonTest from elasticquery import Query, Aggregate, Suggester from elasticquery.exceptions import ( NoQueryError, NoAggregateError,...
2,961
966
import torch ckp_path = './checkpoints/fashion_PATN/latest_net_netG.pth' save_path = './checkpoints/fashion_PATN_v1.0/latest_net_netG.pth' states_dict = torch.load(ckp_path) states_dict_new = states_dict.copy() for key in states_dict.keys(): if "running_var" in key or "running_mean" in key: del states_dict_new[key]...
360
149
#!/usr/bin/python # Copyright 2016 Preferred Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
3,916
1,184
import json import discord from utils.time import format_time from utils import utilities from discord.ext import commands from discord import Embed class Events(commands.Cog): """Event Handler for RompDodger""" def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self,...
3,115
1,167
import multiprocessing # ========== #Python3 - concurrent from math import floor, sqrt numbers = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] # numbers = [33, 44, 55, 275] def lowest_factor(n, _start=3): if n % 2 == 0: re...
1,333
534
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Project: Nowcasting the air pollution using online search log', author='Emory University(IR Lab)', license='MIT', )
260
78
""" Project Euler Problem 48 Self powers Solved by Ahrar Monsur The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def main(): max_digits = 1000 sum = 0 for i in range(1, max_digits+1): sum += i**i print str(...
339
169
#!/usr/bin/python # -*- coding: utf-8 -*- """ @author: rainsty @file: test.py @time: 2020-01-04 18:36:57 @description: """ import os from pyspark.sql import SparkSession os.environ['JAVA_HOME'] = '/root/jdk' os.environ['SPARK_HOME'] = '/root/spark' os.environ['PYTHON_HOME'] = "/root/python" os.environ['PYSPARK_P...
1,109
443
import numpy as np import timeit def effe(x): y = -x * (x - 1.0) return y numIntervalli = input('inserire il numero di intervalli in [0.0, 1.0] ') deltaIntervallo = 1.0 / float(numIntervalli) print "larghezza intervallo", deltaIntervallo start = timeit.default_timer() xIntervalli = [] yIntervalli = [] i =...
1,042
376
import ast from json_codegen.generators.python3_marshmallow.utils import Annotations, class_name class ObjectGenerator(object): @staticmethod def _get_property_name(node_assign): name = node_assign.targets[0] return name.id @staticmethod def _nesting_class(node_assign): for n...
8,810
2,286
#!/usr/bin/env python # # $Id: ESMP_GridToMeshRegridCsrv.py,v 1.5 2012/04/23 23:00:14 rokuingh Exp $ #=============================================================================== # ESMP/examples/ESMP_GridToMeshRegrid.py #=============================================================================== """...
12,736
5,012
# Copyright 2019 IBM 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 agreed to in writing, ...
1,184
361
import json import re import sys def beautify(name): ''' Loading, filtering and saving the JSON tweet file to a newly generated .txt file :type: name: String :rtype: output: .txt ''' filename = name + '.json' output_name = name + "_filtered.txt" with open(filename, "r", encoding="utf-8")...
3,770
1,468
import BboxToolkit as bt import pickle import copy import numpy as np path1="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/dets.pkl" path2="/home/hnu1/GGM/OBBDetection/data/FaIR1M/test/annfiles/ori_annfile.pkl"# with open(path2,'rb') as f: #/home/disk/FAIR1M_1000_split/val/annfiles/ori_...
1,746
689
import taichi as ti import utils from apic_extension import * @ti.data_oriented class Initializer3D: # tmp initializer def __init__(self, res, x0, y0, z0, x1, y1, z1): self.res = res self.x0 = int(res * x0) self.y0 = int(res * y0) self.z0 = int(res * z0) self.x1 = int(res * ...
938
362
from copy import deepcopy import bifrost as bf from bifrost.pipeline import TransformBlock from bifrost.ndarray import copy_array class CopyBlock(TransformBlock):# $\tikzmark{block-start}$ """Copy the input ring to output ring""" def __init__(self, iring, space): ...
1,265
466
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # Copyright 2017 FUJITSU LIMITED # # 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...
1,540
461
import json your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]' parsed = json.loads(your_json) print(type(your_json)) print(type(parsed)) #print(json.dumps(parsed, indent=4, sort_keys=True))
192
82
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
13,929
4,465
import matplotlib matplotlib.use('Agg') import numpy as np from astropy.tests.helper import pytest from .. import FITSFigure def test_grid_addremove(): data = np.zeros((16, 16)) f = FITSFigure(data) f.add_grid() f.remove_grid() f.add_grid() f.close() def test_grid_showhide(): data = np...
1,624
725
import os, sys class Object: ## @name constructor def __init__(self, V): self.value = V self.nest = [] def box(self, that): if isinstance(that, Object): return that if isinstance(that, str): return S(that) raise TypeError(['box', type(that), that]) ## @name d...
12,910
4,415
import asyncio import logging import aiohttp import uvicorn from fastai.vision import * from starlette.applications import Starlette from starlette.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse # put your url here here model_file_url = 'https://www.dropbox.com/s/...?raw=1' model_f...
2,630
876
from socket import * serverPort = 12001 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('', serverPort)) serverSocket.listen(1) print("the server is ready to receive") while True: connectionSocket,addr = serverSocket.accept() sentence = connectionSocket.recv(1024).decode() sentence = sentence...
402
122
"""This module contains the GeneFlow LocalWorkflow class.""" class LocalWorkflow: """ A class that represents the Local Workflow objects. """ def __init__( self, job, config, parsed_job_work_uri ): """ Instantiate LocalWorkflow class....
1,061
273
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1): """Create LR step scheduler. Args: optimizer (torch.optim): Model optimizer. step_size (int): Frequency for changing learning rate. gamma (float): Fa...
2,849
875
# Copyright 2019 TerraPower, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
10,889
3,406
# Generated by Django 3.1.12 on 2021-07-12 19:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('survey', '0004_lastpage_whatsapp_button'), ] operations = [ migrations.RemoveField( model_name='lastpage', name='wh...
562
182
import aspose.email.mapi.msg as msg from aspose.email.mapi import MapiNote, NoteSaveFormat, NoteColor def run(): dataDir = "Data/" #ExStart: CreateAndSaveOutlookNote note3 = MapiNote() note3.subject = "Blue color note" note3.body = "This is a blue color note"; note3.color = NoteColor.YELLOW note3.height = 500 ...
490
190
import functools from string import Formatter from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, cast, overload, ) if TYPE_CHECKING: from .message import Message, Mess...
6,114
1,760