text
string
size
int64
token_count
int64
import sys from PIL import Image #import ImageChops #import numpy as np #import ImageChops if __name__ == '__main__': srcList = [] targetList = [] colorRate = [] avgColorRate = 0.0 sumColorRate = 0 validCount = 0 # image_src = '/root/Android_Application_source/recomended/0.png' fir...
898
347
""" Web unit tests """ # pylint: disable=too-many-public-methods import time import unittest import requests from testing.communicationhelper import get_json, put_json from testing.functions import are_expected_items_in_list, are_expected_kv_pairs_in_list, \ get_item_from_embedded_dict...
15,484
4,897
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" __sets = {} fro...
862
271
from django.shortcuts import render,HTTpResponse # Create your views here. def indexcore(request): return render(request,'index.html') def nosotros(request): return render(request,'nosotros.html') def indexcore(request): #iniciamos el formulario de contacto FormarContac= ContactForm() #valid...
1,251
368
from setuptools import find_packages, setup setup( name='australian_housing', packages=find_packages(), version='0.2.1', description='"A data science exercise on Australian house approvements"', author='"luphord"', license='MIT', )
257
81
import random squares = [ "Go", "Mediterranean Ave.", "Community Chest", "Baltic Ave.", "Income Tax", "Reading Railroad", "Oriental Ave.", "Chance", "Vermont Ave.", "Connecticut Ave.", "Jail", "St. Charles Place", "Electric Company", "States Ave.", "Virginia ...
4,439
1,596
#!/usr/bin/python3 from coinzdense.signing import SigningKey as _SigningKey from coinzdense.validation import ValidationEnv as _ValidationEnv from coinzdense.wallet import create_wallet as _create_wallet from coinzdense.wallet import open_wallet as _open_wallet def _keys_per_signature(hashlen, otsbits): return 2*(...
7,769
2,400
from collections.abc import Iterable from typing import Callable, Tuple import inspect from .definition import DataFlowInspector from .exceptions import DataFlowFunctionArgsError, DataFlowNotCallableError, DataFlowEmptyError, DataFlowNotTupleError class DataFlowInspect(DataFlowInspector): ''' Function inspectio...
1,296
346
from ants import registration, image_read, image_write, resample_image, crop_image from os import listdir mri_directory = "ADNI_baseline_raw/" template_loc = "MNI152_2009/mni_icbm152_t1_tal_nlin_sym_09a.nii" template = image_read(template_loc) template = resample_image(template, (192, 192, 160), True, 4) #template = ...
891
348
import torch from torch._six import with_metaclass class VariableMeta(type): def __instancecheck__(self, other): return isinstance(other, torch.Tensor) class Variable(with_metaclass(VariableMeta, torch._C._LegacyVariableBase)): pass from torch._C import _ImperativeEngine as ImperativeEngine Variab...
362
108
# coding: utf-8 """ Selling Partner API for Finances The Selling Partner API for Finances helps you obtain financial information relevant to a seller's business. You can obtain financial events for a given order, financial event group, or date range without having to wait until a statement period closes. You ...
15,237
5,034
from .utils import hypothesis_register from . import heparin from . import combinatorial_mammalian_n_linked from . import glycosaminoglycan_linkers from . import combinatorial_human_n_linked from . import biosynthesis_human_n_linked from . import biosynthesis_mammalian_n_linked from . import human_mucin_o_linked __al...
583
224
from elasticsearch import Elasticsearch es = Elasticsearch([ {'host':'localhost','port':8200}, ]) print(es.search(index='ename_test_multiprocess',body={"query":{"match":{"name":str(input())}}})['hits']['hits'])
216
70
from .pastepdb import pastepdb
30
10
# Copyright (C) 2015-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe 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 License, or # (at your opt...
3,370
1,117
# Generated by Django 3.2.4 on 2021-07-14 02:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zalo_base', '0003_auto_20210713_1103'), ] operations = [ migrations.DeleteModel( name='ZaloMessage', ), migratio...
1,372
437
import json import os import re import urllib.request def docx_files_names(): file_path = './static/reports/' files = os.listdir(file_path) names = [] for item in files: if item.endswith('.docx'): names.append(item) return names
272
88
import os from pathlib import Path def get_project_root() -> Path: # kudos to https://stackoverflow.com/a/53465812/2377489 relative_root = Path(__file__).parent.parent return relative_root def get_project_src() -> Path: return get_project_root() / "javusdev" def get_project_data() -> Path: re...
708
256
# Be sure to run this file from the "palm_sweeps" folder # cd examples/palm_sweeps import os import sys from datetime import datetime path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) sys.path.insert(0, path) from somo.sweep import iter_utils config_file = "sweeps/grid_diam_height.yam...
2,043
814
from collections import deque as LL class Process: def __init__(self, parent, priority): self.state = 1 # State: 1=ready / 0=blocked self.parent = parent self.children = LL() self.resources = LL() self.priority = priority self.blocked_on = None class Resource: d...
3,998
1,156
""" General framework for reading/writing data from/to files on the local system. """ import json import random from pathlib import Path ############################################################################### # FILE READING ################################################# ####################...
2,449
716
import gym import torch import numpy as np from pg_methods.interfaces import common_interfaces as common class SimpleStateProcessor(common.Interface): """ Allows one to interface states between a single instance of gym """ def __init__(self, environment_observation_space, one_hot=False, use_cuda=False...
2,394
669
"""Unit test for emlib.py To run: PYTHONPATH=../src python test_emlib.py """ __author__ = "Mike Pekala" __copyright__ = "Copyright 2015, JHU/APL" __license__ = "Apache 2.0" import unittest import numpy as np from sklearn.metrics import precision_recall_fscore_support as smetrics import emlib class TestEmlib...
3,935
1,528
"""Module containing scripts for different feature extraction techniques from raw IMU data.""" from biopsykit.signals.imu.feature_extraction import static_moments __all__ = ["static_moments"]
193
55
#!/usr/bin/python """ Author: Fabio Hellmann <info@fabio-hellmann.de> """ from attr import s, ib from attr.validators import instance_of @s(frozen=True) class BLEDevice(object): """ Device MAC address (as a hex string separated by colons). """ addr = ib(validator=instance_of(str), type=str) "...
727
237
""" 1102. Path With Maximum Minimum Value Medium Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1]. The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4. A path moves some numb...
1,511
622
import pytest import data_pipeline.db.factory as db_factory import data_pipeline.extractor.factory as extractor_factory import tests.unittest_utils as utils import data_pipeline.constants.const as const from pytest_mock import mocker from data_pipeline.db.exceptions import UnsupportedDbTypeError @pytest.fixture() def...
1,436
491
# SurEmCo - C++ tracker wrapper import ctypes from enum import IntEnum import sys import os import numpy import numpy.ctypeslib class Tracker(object): class Mode(IntEnum): MOVING = 0 STATIC = 1 class Strategy(IntEnum): BRUTE_FORCE = 0 KD_TREE = 1 track_input_type = {'dty...
3,424
1,137
# coding=utf-8 from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import Config app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) class Role(db.Model): # 定义表名 __tablename__ = 'roles' # 定义列对象 id = db.Column(db.Integer, primary_key=True) name = db.C...
774
305
from IPython.core.display import display, HTML import translation class translate(object): id_start = 0 def __init__(self, column_types, language_to='en'): self.num_of_columns = len(column_types) + 1 column_types.insert(0, 'original text') self.column_types = column_types self.language_to = language_to...
4,026
1,430
import requests import json import pandas as pd import os from .endpoints import * class Client: endpoints = { "contacts" : contacts, "leases" : leases, "units" : units, "wells" : wells, "custom" : custom, "tracts" : tracts, "payments" : payments } ...
1,315
403
#%% def makeUI(uiNames): import sys, os print('Check the pwd first, It must be at .../SignalPlotter/qt.') print(os.getcwd()) p0 = os.path.dirname(sys.executable) for uiName in (uiNames): print('===== for: ',uiName,' ======') p1 = '"'+p0+'\Scripts\pyuic5.exe'+'" ' p1 += ' -x...
589
226
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup import pandas as pd # 安裝Chrome驅動程式及建立Chrome物件 browser = webdriver.Chrome(ChromeDriverManager().install()) browser.get( "https://old.accupass.com/search/r/0/0/0/0/4/0/00010101/99991231?q=python") ...
1,640
768
from mpcontribs.config import mp_level01_titles from mpcontribs.io.core.recdict import RecursiveDict from mpcontribs.io.core.utils import clean_value, get_composition_from_string from mpcontribs.users.utils import duplicate_check def round_to_100_percent(number_set, digit_after_decimal=1): unround_numbers = [ ...
3,148
1,081
import sys, os sys.path.append("./midlevel-reps") from visualpriors.taskonomy_network import TaskonomyDecoder import torch import torch.nn.functional as F import torch.nn as nn SMOOTH = 1e-6 CHANNELS_TO_TASKS = { 1: ['colorization', 'edge_texture', 'edge_occlusion', 'keypoints3d', 'keypoints2d', 'reshading', 'd...
7,944
2,797
import os,sys import numpy as np import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import pygeos from osgeo import gdal from tqdm import tqdm import igraph as ig import contextily as ctx from rasterstats import zonal_stats import time import pylab as pl from IPython import display import seabo...
21,205
7,801
from channels.auth import AuthMiddlewareStack from knox.auth import TokenAuthentication from django.contrib.auth.models import AnonymousUser from channels.db import database_sync_to_async @database_sync_to_async def get_user(access_token): try: auth = TokenAuthentication() token = access_token.de...
1,238
365
"""Access / change tensor shape.""" import tensorflow as tf import numpy as np from .magik import tensor_compat from .alloc import zeros_like from .types import has_tensor, as_tensor, cast, dtype from .shapes import shape, reshape, flatten, transpose, unstack from ._math_for_indexing import cumprod, minimum, maximum f...
6,841
2,052
from flask import Blueprint, request from aleph.core import db from aleph.model import Alert from aleph.search import DatabaseQueryResult from aleph.views.forms import AlertSchema from aleph.views.serializers import AlertSerializer from aleph.views.util import require, obj_or_404 from aleph.views.util import parse_req...
1,478
506
# 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, software # distributed under th...
11,283
3,251
from keras.models import Sequential from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.layers.core import Activation, Dense, Flatten, Dropout from keras.optimizers import Adam from keras.regularizers import l2 from keras import backend as K def center_normalize(x)...
2,282
965
#!/usr/bin/env python3 import sys import struct import re import os from itertools import chain import warnings import tarfile import sh from tqdm import tqdm from pydebhelper import * from getLatestVersionAndURLWithGitHubAPI import getTargets def genGraalProvides(start=6, end=8): # java 12 still not supported ye...
8,685
3,470
# -*- encoding: utf-8 -*- # # Copyright © 2017 Red Hat, 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 applica...
6,267
2,113
"""Vehicle's app models.""" import uuid from django.db import models from .clients import Client class Vehicle(models.Model): """Model representing a vehicle.""" road_worthiness_path = 'vehicles/certs/road_worthiness' ownership_path = 'vehicles/certs/ownership' photo_path = 'vehicles/photos' id...
1,750
582
""" Entradas compra-->int-->c salidas Descuento-->flot-->d """ c=float(input("digite compra")) #caja negra d=(c*0.15) total=(c-d) #Salidas print("el total a pagar es de :"+str(total))
187
87
#LeetCode problem 429: N-ary Tree Level Order Traversal """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: res=[] h=self.getHeig...
878
284
# importing the requests library import requests import json # api-endpoint URL = "http://127.0.0.1:80/water_mark" # defining a params dict for the parameters to be sent to the API # data is picture data # tagString is the text to embed into picture. data = { "data":"This is the original text", "tagStri...
544
195
import torch import torch.nn.functional as F import torch.nn.init as init from torch import nn, autograd from torch.utils.data import DataLoader from babi import BabiDataset, pad_collate from torch.nn.utils import clip_grad_norm torch.backends.cudnn.benchmark = True torch.backends.cudnn.fastest = True class MemoryC...
9,827
3,228
from lake.models.tba_model import TBAModel from lake.modules.transpose_buffer_aggregation import TransposeBufferAggregation from lake.passes.passes import lift_config_reg import magma as m from magma import * import fault import tempfile import kratos as k import random as rand import pytest def test_tba(word_width=1...
3,444
1,208
#! /usr/bin/python3 import sys, os, time from typing import List, Tuple from itertools import combinations def part1(ids: List[str]) -> int: twice_count = 0 thrice_count = 0 for id in ids: id_counts = { id.count(c) for c in id } twice_count += 2 in id_counts thrice_count += 3 in i...
1,442
517
import pygame def print(text, window): font = pygame.font.SysFont('Times New Roman', 18) header_text = font.render(text,1,(255,255,0)) window.blit(header_text, (1000 + (200/2 - header_text.get_width()/2), 680 + (header_text.get_height()/2)))
275
110
import pkg_resources from . import BrummiRepository DEFAULTS = { 'templates': pkg_resources.resource_filename('brummi', 'templates'), 'out_path': 'docs', } class Config(object): def __init__(self, options): self.options = DEFAULTS.copy() self.options.update(options) def launch(self):...
515
152
from pathlib import Path import numpy as np THIS_FILE = Path(__file__) THIS_DIR = THIS_FILE.parent DEFAULT_CONFIG_FILE = THIS_DIR / 'config' / 'default.yaml' # Width/height of the visual screens IMG_WIDTH = 1242 IMG_HEIGHT = 375 # INTRINISCS = np.array([[649.51905284, 0.00000000, 620.50000000], # ...
730
439
# -*- coding: utf-8 -*- ## @package palette.core.color_transfer # # Color transfer. # @author tody # @date 2015/09/16 import numpy as np from scipy.interpolate import Rbf import matplotlib.pyplot as plt from palette.core.lab_slices import LabSlice, LabSlicePlot, Lab2rgb_py ## Color transfer for ab co...
3,272
1,180
scoult = dict() gols = list() time = list() temp = 0 while True: scoult['Jogador'] = str(input('Qual o nome do jogador: ')) scoult['Número partidas'] = int(input('Quantas partidas foram jogadas? ')) for i in range(0,scoult['Número partidas']): gols.append(int(input(f'Quantos gols foram marcados na p...
1,447
607
# Circles and squares # Each can be rendered in vector or raster form from Section07_Bridge.Brigde.Circle import Circle from Section07_Bridge.Brigde.RasterRenderer import RasterRenderer from Section07_Bridge.Brigde.VectorRenderer import VectorRenderer if __name__ == '__main__': raster = RasterRenderer() vector...
428
133
import numpy as np import torch import torch.nn as nn import torch.optim as optim from utils import init class Explorer(nn.Module): def __init__(self, state_dim, max_action, exp_regularization): super(Explorer, self).__init__() init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init.con...
3,668
1,209
from telethon import events, Button from .login import user from .. import jdbot from ..bot.utils import cmd, TASK_CMD,split_list, press_event from ..diy.utils import read, write import asyncio import re @user.on(events.NewMessage(pattern=r'^setbd', outgoing=True)) async def SetBeanDetailInfo(event): try: ...
3,400
1,248
#!/usr/bin/python import box_requests import requests import os import sys import time import socket import optparse import logging def checktime(path, days): try: r=os.stat(path) except OSError: return False return (time.time() - r.st_mtime) < (days * 86400) def logfailure(msg): print >> sy...
2,409
754
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: Ivar """ from Description import * from Classification import * if __name__ == "__main__": inputdir = "../../../../data/LHA/dataset_1" outputdir = inputdir+"/csv/exp/"+Util.now() template = [ { "name":"RAD", ...
2,663
881
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor from sklearn.neural_network import MLPRegressor from sklearn.linear_model import ElasticNet, Ridge, Lasso, BayesianRidge, HuberRegressor from xgboost import XGBRegressor from lightgbm import LGBMRegressor from pyemits.core....
12,263
3,657
""" knowledge graph representation using neo4j this class uses py2neo with will be the final version """ import os import json from py2neo import Graph, Relationship, NodeMatcher, Node from network_core.ogm.node_objects import Me, Contact, Misc USERTYPE = "User" CONTACTTYPE = "Contact" ROOT_DIR = os.path.dirname(os.p...
7,092
2,100
import numpy as np from .chance import by_chance from .exceptions import EmptyListError def pop_random_entry(lst): if not lst: raise EmptyListError index = np.random.randint(0, len(lst)) return lst.pop(index) def pick_random_entry(lst): if not lst: raise EmptyListError index =...
538
188
import os import pandas as pd from sklearn.linear_model import ElasticNet from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error import argparse import numpy as np import json import joblib from get_data import read_config def evaluate_metrics(actual, pred): r2 = r2_score(actual,pred) ma...
2,355
866
""" Visualisation of maximum/minimum magnitude for GCVS stars. """ import sys import matplotlib.pyplot as plot from pygcvs import read_gcvs if __name__ == '__main__': try: gcvs_file = sys.argv[1] except IndexError: print('Usage: python plot_magnitudes.py <path to iii.dat>') else: ...
961
305
# Generated by Django 3.0.5 on 2020-04-21 07:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('stock', '0027_stockitem_sales_order'), ] operations = [ migrations.RenameField( model_name='stockitem', old_name='sales_orde...
382
135
"""weideshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
1,595
522
#!/usr/bin/env python3 import os import sys import configparser import fileinput import netorlogging import datetime from shutil import copyfile def _netor_config(): """ It is used for updating the Neto home directory in the configuration files and scripts. This is useful, if you want to have 2 working ...
18,023
5,544
import pytest from zoo.auditing.models import Issue from zoo.auditing.check_discovery import Effort, Kind, Severity pytestmark = pytest.mark.django_db @pytest.fixture def scenario(mocker, repository_factory, issue_factory, check_factory, fake_path): owner, name, sha = "games", "lemmings", "GINLNNIIJL" repo...
4,780
1,586
# -*- coding: utf-8 -*- import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello))
134
52
from random import randint from typing import Optional from behavioral.command.data import Trader from behavioral.command.logic.generators import ItemsGenerator class TraderGenerator: __MIN_GOLD = 0 __MAX_GOLD = 450 def __init__(self) -> None: self._items_generator = ItemsGenerator() def _g...
755
231
# -*- coding: utf-8 -*- """ Created on Sat Aug 29 00:07:11 2015 @author: Shamir """ def CalculateValidData(): # Calculate the number of missing values in the array number_of_nan = len(readFile.values[m][pandas.isnull(readFile.values[m])]) length_of_array = len(readF...
11,119
2,920
def main(): content_pages = auto_populate_content_files() for page in content_pages: filepath = page['filepath'] output = page['output'] title = page['title'] # Read content of html pages content = open(filepath).read() # Invoke function to return finished_page (base.html with filled in content) fi...
1,919
686
#!/usr/bin/env python """Informatics Matters Job Tester (JOTE). Get help running this utility with 'jote --help' """ import argparse import os import shutil import stat from stat import S_IRGRP, S_IRUSR, S_IWGRP, S_IWUSR import subprocess import sys from typing import Any, Dict, List, Optional, Tuple from munch impo...
35,113
9,952
""" Subclass of the BaseCredContainer used for reading secrets from bitwarden password manager. This class wraps the bitwarden CLI. See: https://bitwarden.com/help/article/cli/#using-an-api-key Note that only the Enterprise version of bitwarden can (supported) hit the REST API. In contrast, the API key that can be ...
18,636
5,191
import colorednoise as cn import librosa import numpy as np def get_waveform_transforms(config: dict, phase: str): transforms = config.get("transforms") if transforms is None: return None else: if transforms[phase] is None: return None trns_list = [] for trns_co...
7,027
2,524
from django.db import models from registeration.models import User from chatroom.models import Chatroom class Message(models.Model): chatroom = models.ForeignKey(Chatroom, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) text = models.TextField() parentMes...
438
137
from __future__ import absolute_import import unittest import logging import copy import pickle from plyplus.plyplus import STree logging.basicConfig(level=logging.INFO) class TestSTrees(unittest.TestCase): def setUp(self): self.tree1 = STree('a', [STree(x, y) for x, y in zip('bcd', 'xyz')]) def te...
1,095
378
MAJOR_COLORS = ["White", "Red", "Black", "Yellow", "Violet"] MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"] def get_color_from_pair_number(pair_number): zero_based_pair_number = pair_number - 1 major_index = zero_based_pair_number // len(MINOR_COLORS) minor_index = zero_based_pair_number % ...
1,563
605
import discord_self_embed from discord.ext import commands bot = commands.Bot(command_prefix=".", self_bot=True) @bot.event async def on_ready(): print("ready") @bot.command(name="embed") async def embed_cmd(ctx): embed = discord_self_embed.Embed("discord.py-self_embed", description="A way for selfbots to se...
611
206
import re import copy from operator import itemgetter import music21 as m21 class Core: meter_len = 192 notes = {'C': 60, 'D': 62, 'E': 64, 'F': 65, 'G': 67, 'A': 69, 'B': 71} percussion = { 35: 'AcousticBassDrum', 36: 'BassDrum1', 37: 'SideStick', 38: 'AcousticSnare', 39: 'HandClap', 40: ...
8,823
3,265
# pylint: disable=no-name-in-module,too-many-arguments import json import re import typing from urllib.parse import urlparse import warnings from requests import Response from fastapi.testclient import TestClient from pydantic import BaseModel import pytest from starlette import testclient from optimade import __api...
6,302
1,808
# -*- coding: utf-8 -*- """ Created on 2018/11/5 @author: susmote """ import time import requests import json # 查看自己关注的超话 if __name__ == '__main__': username = input("请输入用户名: ") password = input("请输入密码: ") login_url = "https://passport.weibo.cn/sso/login" headers = { "Referer": "https://...
3,673
1,411
import requests import logging logger = logging.getLogger(__name__) def send_notifications(notifiers, message): for notifier in notifiers: notifier.send_notification(message) class Pushover: def __init__(self, api_token, user_key): self.api_token = api_token self.user_key = user_key...
1,163
363
from django.urls import path, include from apps.xero_workspace.views import ScheduleSyncView urlpatterns = [ path('<int:workspace_id>/expense_group/', include('apps.fyle_expense.job_urls')), path('<int:workspace_id>/settings/schedule/trigger/', ScheduleSyncView.as_view(), name="schedule_trigger"), ]
311
105
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ...
43,058
13,550
#!/usr/bin/env python3 # # Plots the power spectra and Fourier-space biases for the HI. # import warnings from mpi4py import MPI rank = MPI.COMM_WORLD.rank #warnings.filterwarnings("ignore") if rank!=0: warnings.filterwarnings("ignore") import numpy as np import os, sys import matplotlib.pyplot as plt fro...
15,806
7,461
from ndfinance.strategies import Strategy, PeriodicRebalancingStrategy from ndfinance.brokers.base import order from ndfinance.brokers.base.order import * from ndfinance.strategies.utils import * class SameWeightBuyHold(Strategy): def __init__(self): super(SameWeightBuyHold, self).__init__() self....
3,999
1,301
# Shortest Unique Prefix # https://www.interviewbit.com/problems/shortest-unique-prefix/ # # Find shortest unique prefix to represent each word in the list. # # Example: # # Input: [zebra, dog, duck, dove] # Output: {z, dog, du, dov} # where we can see that # zebra = z # dog = dog # duck = du # dove = dov # NOTE : Ass...
1,662
571
from flask import Flask, render_template, send_from_directory import serial import serial.tools.list_ports import threading app = Flask(__name__) def run_server(): app.run(host=bind_ip, debug=True, port=bind_port) @app.route('/') def index(): return render_template('_basic.html', ports=serialhandler.get_port_list(...
1,975
800
from agave_mock_server import app as application if __name__ == "__main__": application.run(host="0.0.0.0", ssl_context="adhoc")
134
49
from PIL import Image import numpy as np import torch import torchvision.transforms.transforms as transforms import os from config import cfg def preprocess_img(img_path): """ Loads the desired image and prepares it for VGG19 model. Parameters: img_path: path to the image Returns: ...
3,304
1,056
import os import platform import sys from os.path import relpath sys.path.append('/usr/local/bin/dot') sys.path.append('/usr/bin/dot') from graphviz import Digraph # struttura dati class node: def __init__(self, id, istruction, *nxt_node): self.id = id self.ist = istruction self.next_node...
5,179
1,399
from .ChangeNotificationMessage import ChangeNotificationMessage import json def requestBatchOfPagesAndReturnRemainingCountLib( pageLimit, lastProcessedID, clientAPIInstance, loginSession, processIndividualMessage ): params = { "limit": str(pageLimit) } if lastProcessedID is not None: params["...
2,466
714
import keras import numpy as np from schafkopf.players.data.load_data import load_data_bidding from schafkopf.players.data.encodings import decode_on_hot_hand import matplotlib.pyplot as plt x_test, y_test = load_data_bidding('../data/test_data.p') x_train, y_train = load_data_bidding('../data/train_data.p') modelpat...
1,821
729
"""Ce script est un exemple de matplotlib""" import numpy as np def moving_average(x, n, type='simple'): """ compute an n period moving average. type is 'simple' | 'exponential' """ x = np.asarray(x) if type == 'simple': weights = np.ones(n) else: weights = np.exp(np.li...
8,338
5,339
import os import sys # Add relevant ranger module to PATH... there surely is a better way to do this... sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) from pymycobot import utils port = utils.get_port_list() print(port) detect_result = utils.detect_port_of_basic() print(detect_result)
309
111
# Generated by Django 3.2.5 on 2021-08-04 18:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
3,347
1,034
# Generated by Django 4.0.1 on 2022-02-21 03:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("users", "0010_alter_user_picture"), ] operations = [ migrations.AlterField( model_name="user", name="username", ...
385
132
from pathlib import Path from common import DeviceNode, get_property_value from PyFlow.Core.Common import * from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper class NeuralNetworkNode(DeviceNode): def __init__(self, name): super(NeuralNetworkNode, self).__init__(name) self.input = self.cre...
1,742
506