text
string
size
int64
token_count
int64
import os import re import random from scipy.misc import imread import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS d = os.path.dirname(__file__) text_files = os.path.join(d, 'text_files') images = os.path.join(d, 'images') paths = [fn for fn in next(os.walk(text_files))[2]] # Creat Normal w...
1,418
528
""" Copyright (C) 2022 Martin Ahrnbom Released under MIT License. See the file LICENSE for details. This module describes 2D/3D tracks. GUTS's output is a list of instances of these classes. """ import numpy as np from filter import filter2D, filter3D from options import Options, Filter2DParams, Fi...
13,176
4,232
from datetime import datetime, timedelta from dimagi.utils import parsing as dateparse from casexml.apps.stock.consumption import ( ConsumptionConfiguration, compute_daily_consumption_from_transactions, ) to_ts = dateparse.json_format_datetime now = datetime.utcnow() def ago(days): return now - timedel...
753
223
import kopf import time from utils import get_all_federation_clusters, rescheduleApp # Create app rescheduler @kopf.daemon('fogguru.eu', 'v1', 'appreschedulers', initial_delay=5) def create_fn(stopped, **kwargs): CHECK_PERIOD = 60 RESCHEDULE_PERIOD = 31 * 60 while not stopped: # for now just resche...
1,007
335
# -*- coding:utf-8 -*- # 1.导入拓展 from flask import Flask from flask_restful import Api import config from app.api.view.auth import wx_login from app.api.view.talk import Reply # 2.创建flask应用实例,__name__用来确定资源所在的路径 app = Flask(__name__) app.config.from_object(config.DevelopmentConfig) api = Api(app) # 3.定义全局变量 # 4.定义路由和视...
538
257
import numpy.random as rand import numpy as np import pandas as pd import random import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation from Particle import Particle #Initialization of the plots fig = plt.figure(figsize=(20,10)) axes = [None...
6,904
2,184
#ASAPY import requests __URL_GLOBAL = "https://www.urionlinejudge.com.br"; def printme(pagina): body = getCorpo(__URL_GLOBAL+"/judge/pt/problems/view/"+pagina); iInicio = find_str(body, "<iframe"); pos = (body[iInicio:]); iFim = find_str(pos, ">")+1; tupla = pos[:iFim]; page2 = getAttr(tupl...
1,334
559
#!/bin/python3 import math import os import random import re import sys # # Generator method to buld a list containing only the elements with diff <= 1 # def genSucessors(pivot, array): for i in array: if (abs(pivot - i) <= 1): yield i # # Complete the 'pickingNumbers' function below. # # The...
876
309
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.distributed.ClockDelta import * import ButterflyGlobals import random class DistributedButterflyAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("Distri...
2,911
923
# Name: # Date: # proj01: A Simple Program # Part I: # This program asks the user for his/her name and grade. #Then, it prints out a sentence that says the number of years until they graduate. print "Hello" Your_Name = raw_input("What's your name?") print "Your name is "+ Your_Name Your_Grade = raw_input("What Grade ...
1,637
553
from io import IncrementalNewlineDecoder from django.db import models # Classe de departamento class Departamento(models.Model): id = models.IntegerField(primary_key=True, editable=False) nome = models.CharField(max_length=255, blank=False) numero_projetos = models.IntegerField(default=0) # Quantidade de p...
1,113
344
""" https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/ Tags: Weekly-Contest_281; Brute-Force; Easy """ class Solution: def countEven(self, num: int) -> int: ans = 0 for i in range(1, num + 1): s = str(i) # Digit Sum ...
422
160
import argparse import os import torch import matplotlib.pyplot as plt from torch.utils.data.distributed import DistributedSampler from torch import distributed as dist from torch import optim from tqdm import tqdm from torch_ema import ExponentialMovingAverage from cifr.core.config import Config from cifr.models.bui...
9,054
2,990
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/Colin/Documents/hackedit/data/forms/main_window.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def...
14,930
4,939
from django.db import models import uuid from product.models import Product from django.contrib.auth.models import User # Create your models here. class Order(models.Model): generated_order_id = models.CharField(max_length=100, default=uuid.uuid4, unique=True) products = models.ManyToManyField(Product, rel...
1,314
401
from .uniswap_v2_deltas import * from .uniswap_v2_events import * from .uniswap_v2_metadata import * from .uniswap_v2_spec import * from .uniswap_v2_state import *
164
73
#!/usr/bin/env python3 import rospy import serial from std_msgs.msg import Float32 tt_arduino = serial.Serial("/dev/ttyUSB0", 9600) rospy.init_node('torque_test_stand', anonymous = False) pub = rospy.Publisher('/test_equipment/measured_torque', Float32, queue_size=10) r = rospy.Rate(10) print('Torque Test Stand Nod...
558
223
from django.db import connection from django.utils.unittest import skipIf from tenant_schemas.tests.models import Tenant, DummyModel from tenant_schemas.tests.testcases import BaseTestCase from tenant_schemas.utils import get_public_schema_name try: from .app import CeleryApp except ImportError: app = None e...
3,862
1,236
from __future__ import annotations import ast import pytest from flake8_pie import Flake8PieCheck from flake8_pie.pie804_no_unnecessary_dict_kwargs import PIE804 from flake8_pie.tests.utils import Error, ex, to_errors EXAMPLES = [ ex( code=""" foo(**{"bar": True}) """, errors=[PIE804(lineno=2, c...
1,273
526
from ...reqs import publications from .. import main class Post(main._all["publication"]): """ Имитирует объект поста. """ __slots__ = ( "pages", "best_comment", "rubric_id", "rubric_name" ) def __init__(self, content): """ Создать класс...
6,161
1,920
import logging import numpy as np from glob import glob from os.path import getmtime, isfile from os import remove from thyme import Trajectory from thyme.parsers.monty import read_pattern, read_table_pattern from thyme.routines.folders import find_folders, find_folders_matching from thyme._key import * from thyme.pa...
4,393
1,717
from rest_framework.mixins import CreateModelMixin from rest_framework.viewsets import GenericViewSet class CreateUserLinkedModelMixin(CreateModelMixin, GenericViewSet): """ Set the user related to an object being created to the user who made the request. Usage: Override the class and set the `.q...
802
231
"""191. Number of 1 Bits https://leetcode.com/problems/number-of-1-bits/ """ class Solution: def hammingWeight(self, n: int) -> int: def low_bit(x: int) -> int: return x & -x ans = 0 while n != 0: n -= low_bit(n) ans += 1 return ans
308
114
import pyClarion.base as clb import pyClarion.numdicts as nd import unittest import unittest.mock as mock class TestProcess(unittest.TestCase): @mock.patch.object(clb.Process, "_serves", clb.ConstructType.chunks) def test_check_inputs_accepts_good_input_structure(self): process = clb.Process( ...
1,249
420
import math from decimal import Decimal from typing import Any from typing import Dict from typing import Optional from typing import Sequence from typing import Tuple from service_capacity_modeling.interface import AccessConsistency from service_capacity_modeling.interface import AccessPattern from service_capacity_m...
10,499
3,000
from kmmi.exposure.exposure import *
36
14
import random import requests def clean_proxies(): proxies = [] with open('proxies', 'r') as handle: contents = handle.read().strip() for proxy in contents.split('\n'): proxies.append(proxy) proxy2 = [] print(proxies) for proxy in proxies: try: response = requests.get('https://google.com', proxies={'...
1,251
462
# chromoSpirals.py # ---------------- # Code written by Peter Derlien, University of Sheffield, March 2013 # Draws spiralling patterns of circles using the Golden Angle. # ---------------- # Import from the numpy and matplotlib packages. import numpy as np import matplotlib.pyplot as plt import matplotlib from matplot...
2,263
876
from django.shortcuts import render,redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form=TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form....
1,045
348
#!/usr/bin/python """ Split logged data into separate "channels" usage: ./splitter.py <log file> <GPS|0..3|all> """ import sys FIRST_LINE = "id,timeMs,accX,accY,accZ,temp,gyroX,gyroY,gyroZ\n" GPS_SEPARATOR_BEGIN = chr(0x2) GPS_SEPARATOR_END = chr(0x3) def checksum( s ): sum = 0 for ch in s: ...
3,779
1,367
#!/usr/bin/env python # -*- coding: utf-8 -*- import jinja2 import webapp2 import logging import threading from mandrill_email import * from webapp2_extras import routes from cookie import * from settings import * from decorators import * from functions import * from google.appengine.api import taskqueue from google.ap...
11,267
3,357
from railrl.data_management.simple_replay_pool import SimpleReplayPool from railrl.predictors.dynamics_model import FullyConnectedEncoder, InverseModel, ForwardModel import tensorflow as tf import time import numpy as np from sandbox.rocky.tf.optimizers.penalty_lbfgs_optimizer import PenaltyLbfgsOptimizer from railrl.m...
36,253
15,324
from configparser import ConfigParser import re def getConfiguration(): configParser = ConfigParser() configParser.read("config.ini") return configParser def getQrCode(): config = getConfiguration() qrCode = config.get("login", "qrCode", fallback=None) qrCode = _checkQrCode(config, qrCode) ...
620
205
# coding: utf-8 """ Thingsboard REST API For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. OpenAPI spec version: 2.0 Contact: info@thingsboard.io Generated by: https://github.com/swagger-api/swagger-co...
1,969
584
#!/usr/bin/env python """ A variety of push utility functions """ from pylib.util.git_util import GitUtil __author__ = 'edelman@room77.com (Nicholas Edelman)' __copyright__ = 'Copyright 2013 Room77, Inc.' class PushUtil(object): @classmethod def get_deployspec_name(cls, cluster_name): """given a cluster re...
585
196
import enum from shardingpy.parsing.lexer import lexer from shardingpy.parsing.lexer import token class MySQLKeyword(enum.IntEnum): SHOW = 1 DUAL = 2 LIMIT = 3 OFFSET = 4 VALUE = 5 BEGIN = 6 FORCE = 7 PARTITION = 8 DISTINCTROW = 9 KILL = 10 QUICK = 11 BINARY = 12 C...
1,899
912
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4,...
1,937
1,315
# __BEGIN_LICENSE__ # Copyright (c) 2015, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The xGDS platform is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance...
6,067
1,835
from .pycrunchbase import ( CrunchBase, ) from .resource import ( Acquisition, Address, Category, Degree, FundingRound, Fund, Image, Investment, IPO, Job, Location, News, Organization, Page, PageItem, Person, Product, Relationship, StockExc...
732
279
from dropconnect_tensorflow.dropconnect_tensorflow import DropConnectDense, DropConnectConv2D, DropConnect
107
27
def none_check(value): if value is None: return False else: return True def is_empty(any_type_value): if any_type_value: return False else: return True
202
63
import unittest from hstrat.helpers import is_nonincreasing class TestIsNondecreasing(unittest.TestCase): # tests can run independently _multiprocess_can_split_ = True def test_empty(self): assert is_nonincreasing([]) def test_singleton(self): assert is_nonincreasing(['a']) ...
995
327
import numpy as np import matplotlib.pyplot as plt from docx import Document from docx.shared import Cm import math def split_file(file): """split the file by different queries into seperate list element and return one list as a whole. """ answer = [[]] j = 0 for i in file: if i == "\n": ...
8,984
3,044
import csv import re import netifaces as ni from twisted.internet import defer from twisted.names import client from pygear.logging import log from pygear.core.six.moves.urllib.parse import urlparse, urljoin from .interfaces import ITaskStorage csv.register_dialect('pipes', delimiter='|') client_callback_schemes = ...
2,745
966
import os import json import math from neuralparticles.tensorflow.tools.hyper_parameter import HyperParameter, ValueType, SearchType from neuralparticles.tensorflow.tools.hyper_search import HyperSearch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import keras from neuralparticles.tensor...
6,437
2,470
from twilio.rest import Client from scrapper import get_body from os import environ account_sid = environ['ACCOUNT_SID'] auth_token = environ['AUTH_TOKEN'] phone_num = '+9779862074364' def send_sms(): client = Client(account_sid, auth_token) sms = client.messages.create( from_= '+17725772292', ...
413
160
# app/jwt.py from os import environ as env from itsdangerous import ( TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired, ) def generate_jwt(claims, expiration=172800): s = Serializer(env.get("SECRET_KEY"), expires_in=expiration) return s.dumps(claims).decode("utf-8") ...
575
202
""" HTTP client module. """ import requests from requests.auth import HTTPBasicAuth from requests_kerberos import HTTPKerberosAuth from . import errors class KRBAuth: """ Kerberos authenticaton type. """ principal = None hostname_override = None def __init__(self, principal=None, hostname_override=None)...
1,918
585
from django.shortcuts import render from django.views.generic.edit import CreateView from .models import Users from .forms import UserForm from django.contrib.auth.views import LoginView # представление для создания пользователя class UserCreateView(CreateView): form_class = UserForm success_url = '/users_crea...
532
156
from collections import defaultdict from copy import copy import re import json from django.conf import settings from django.test import override_settings, TestCase import responses from prison.models import PrisonerLocation from prison.tests.utils import ( load_prisoner_locations_from_dev_prison_api, random_...
5,105
1,634
from metrics.preprocess import edgefeat_converter, fulledge_converter, node_converter from metrics.common import fulledge_compute_f1, edgefeat_compute_f1, node_compute_f1, node_total from metrics.mcp import fulledge_total as mcp_fulledge_total, edgefeat_total as mcp_edgefeat_total from metrics.tsp import tsp_edgefeat_c...
7,885
2,392
""" Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
1,538
482
from . import wallet_pb2_grpc as wallet_grpc from . import wallet_pb2 as wallet __all__ = [ "wallet_grpc", "wallet", ]
128
55
import particle.processing as processing particles = 480 test_params = { "particle_count": 2 * [particles], # (3 * np.arange(8, 150, 16)).tolist(), "gamma": [0.05], "G": ["Smooth"], "scaling": ["Local"], "D": [1.0], "phi": ["Gamma"], "initial_dist_x": [ "one_cluster", "t...
678
274
from BridgePython import Bridge bridge = Bridge(api_key='myapikey') class PongHandler(object): def pong(self): print ("PONG!") bridge.store_service("pong", PongHandler()) bridge.get_service("ping").ping() bridge.connect()
238
78
from django.shortcuts import render def index(request): try: return render(request, 'home/index.html', {'user': request.session['user']}) except KeyError: return render(request, 'home/index.html', {'user': None})
239
71
import torch.nn as nn class FcNet(nn.Module): def __init__(self, config, input_features, nr_labels): super(FcNet, self).__init__() self.config = config # create the blocks self.layers = self._make_block(self.config["num_layers"], input_features) self.fc_layer = nn.Linear(...
1,918
650
VERSION_MAJOR = "15.03"
24
17
from __future__ import annotations import os import string import random import logging import vapoursynth as vs from pathlib import Path from requests import Session from functools import partial from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor from typing import Any, Mapping, Callable, Dict, F...
16,438
5,047
# see https://www.spinningbytes.com/resources/germansentiment/ and https://github.com/aritter/twitter_download for obtaining the data. import os from pathlib import Path import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from conversion import convert_examples_to_features, conv...
3,737
1,230
""" ------------------------------------------------------------------------------------------------------------------- WEB HANDLING ---------------------------------------------------------------------------------------------------------------------""" import logging f...
1,642
457
# # -*- coding: utf-8 -*- # # Copyright (c) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
3,959
1,248
from django.db import models # Create your models here. class Visitor(models.Model): MALE = 'M' FEMALE = 'F' OTHER = 'X' GENDER_OPTIONS = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other') ] dtRegistered = models.DateTimeField(auto_now_add=True) strFullName = m...
867
285
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["quadratic_2d"] import numpy as np def quadratic_2d(data): """ Compute the quadratic estimate of the centroid in a 2d-array. Args: data (2darray): two dimensional data array Returns center (tuple): c...
1,751
845
from models.multiple_solution.swarm_based.WOA import BaseWOA, BaoWOA from utils.FunctionUtil import square_function ## Setting parameters root_paras = { "problem_size": 30, "domain_range": [-1, 1], "print_train": True, "objective_func": square_function } woa_paras = { "epoch": 100, "pop_size": ...
416
176
import unittest from musket_core import projects from musket_core import parralel import os fl=__file__ fl=os.path.dirname(fl) class TestCoders(unittest.TestCase): def test_basic_network(self): pr = projects.Project(os.path.join(fl, "project")) exp = pr.byName("exp01") tasks = exp.fit() ...
600
196
#!/usr/bin/env python3 """ Based on template: https://github.com/FedericoStra/cython-package-example """ from setuptools import setup with open("requirements.txt") as fp: install_requires = fp.read().strip().split("\n") with open("requirements_dev.txt") as fp: dev_requires = fp.read().strip().split("\n") s...
470
179
#Paleo_DB_Rip.py #Python script to programmatically web-scrape from paleobiodb.org #Author: Matt Oakley #Date: 08/15/2016 # Imports # from bs4 import BeautifulSoup from time import sleep from geopy.geocoders import Nominatim import urllib2 import pycountry import wget import sys import os.path import codecs # Globals...
3,038
1,140
import sys, re if __name__=='__main__': sys.path.append(sys.path[0]+'\\..') from body.bone import NetP from body.soul import Karma from body.body_motor import Motor from body.body_pool import Pool from body.body_brain import Brain from body.body_debugger import Debugger from tools import tools_sl, tools_ba...
10,015
3,527
# -*- coding: utf-8 -*- from model.group import group def test_add_group(app): app.group.create(group(name="Name", header="Head", footer="Footer")) def test_add_empty_group(app): app.group.create(group(name="", header="", footer=""))
246
89
from django.views.generic import DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from schedule.models import Calendar from schedule.views i...
2,569
708
import dill import glob import csv import os from os.path import basename, join from joblib import Parallel, delayed domain_path = '/datasets/amazon-data/new-julian/domains' domain_subdirectory = 'only-overall-lemma-and-label-sampling-1-3-5' domain_files = glob.glob(join(domain_path, 'o...
2,055
679
from image_augmentation.preprocessing.preprocess import cifar_baseline_augmentation, cifar_standardization from image_augmentation.preprocessing.preprocess import imagenet_baseline_augmentation, imagenet_standardization from image_augmentation.preprocessing import efficientnet_preprocess
289
79
from binaryninjaui import DockHandler, DockContextHandler, UIActionHandler, getMonospaceFont from PySide2 import QtCore from PySide2.QtCore import Qt from PySide2.QtWidgets import (QApplication, QHBoxLayout, QVBoxLayout, QLabel, QWidget, QPlainTextEdit, QSizePolicy, QFormLayout, QPushButton, QLineEdit) ...
10,406
3,072
""" C 1.19 --------------------------------- Problem Statement : Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], but without having to type all 26 such characters literally. Author : Saurabh """ print([chr(x + 97) for x in range(26)])
291
96
from __future__ import annotations from ast import AST, Subscript, Name, Call READONLY_ANNOTATION: str = "Readonly" READONLY_CALL: str = "readonly" READONLY_FUNC: str = "readonly_func" def is_readonly_annotation(node: AST) -> bool: return ( isinstance(node, Subscript) and isinstance(node.value, ...
596
220
# -*- coding: utf-8 -*- import os # noqa: F401 import os.path import shutil import time import unittest from configparser import ConfigParser from os import environ from pprint import pformat from pprint import pprint # noqa: F401 from Velvet.VelvetImpl import Velvet from Velvet.VelvetServer import MethodContext fro...
11,360
3,533
"""Defines the application configuration for the product application""" from __future__ import unicode_literals from django.apps import AppConfig class ProductConfig(AppConfig): """Configuration for the product application""" name = 'product' label = 'product' verbose_name = 'Product' def ready(...
681
174
__author__ = 'yanikafarrugia' import unittest import lattly_service.converter class ConverterTests(unittest.TestCase): def test_degrees_to_radians(self): rad = lattly_service.converter.Converter.degrees_to_radians(120) self.assertEqual(rad, 2.0943951023931953) self.assertIsNotNone(rad) self.assertTrue(rad >...
1,248
612
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='vindinium-client', version='0.1.0', description='Client for Vindinium.org', long_description=readme, author='Serg...
527
197
"""This module tests Machine Translation processor.""" import unittest import os import tempfile import shutil from ddt import ddt, data, unpack from texar.torch import HParams from forte.pipeline import Pipeline from forte.data.readers import MultiPackSentenceReader from forte.processors import MicrosoftBingTranslat...
2,012
597
#!/usr/bin/env python import cv2 from picamera.array import PiRGBArray from picamera import PiCamera import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from models.ros_publisher import ROSPublisher class ImageCapture(ROSPublisher): """Captures and converts openCV image da...
1,715
526
"""lesson6/solution_simple_functions.py Contains solutions for simple functions. """ # Exercise 1: Write a function that prints your name and try calling it. # Work in this file and not in the Python shell. Defining functions in # a Python shell is difficult. Remember to name your function something # that indicat...
612
192
# ------------------------------------------------------------------------ # MIT License # # Copyright (c) [2021] [Avinash Ranganath] # # This code is part of the library PyDL <https://github.com/nash911/PyDL> # This code is licensed under MIT license (see LICENSE.txt for details) # ------------------------------------...
21,829
7,094
# -*- coding: utf-8 -*- from dateutil.parser import isoparse class ISODateTime(object): def __init__(self, initval=None): self.val = initval def __get__(self, obj, obj_type): return self.val def __set__(self, obj, string_date): if string_date is None: self.val = None ...
416
150
# Copyright 2018 Cognibit Solutions LLP. # # 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 ...
3,317
1,118
""" Creates Pelvis """ import maya.cmds as mc from ..Utils import String as String class Pelvis(): def __init__(self, characterName = '', suffix = '', name = 'Pelvis', parent = ''): """ @return: returns end joint """ ...
913
276
from multiprocessing import Pipe import requests import json import time cur_file = "../data/cur_weather.json" today_file = "../data/today_weather.json" def write2file(data, json_file): with open(json_file, 'w') as f: f.write(json.dumps(data)) f.close() # class Weather(object): # def __init__...
2,311
823
import os.path import logging logger = logging.getLogger("MSI_GUI") from PyQt5 import QtCore, QtGui class Options: def __init__(self, mainWindow): self.general_box = GeneralBox(mainWindow) self.raw_tab = RawTab(mainWindow) self.process_tab = ProcessTab(mainWindow) self.denoise_tab...
14,640
4,923
import numpy as np from models import * from datasets import * from util import parse_funct_arguments import pickle import itertools def mse(y_true, y_mdl): return np.mean((y_true - y_mdl)**2) def train(mdl, dset): # Get train u_train, y_train = dset.get_train() # Fit X_train, z_train = construc...
5,800
2,045
# Pylint doesn't play well with fixtures and dependency injection from pytest # pylint: disable=redefined-outer-name import os import pytest from buildstream import _yaml from buildstream._project import Project from buildstream._protos.build.bazel.remote.execution.v2 import remote_execution_pb2 from buildstream._te...
6,000
1,751
import logging from app.config import oapi, app_api, redis, LAST_MENTION_ID from app.fetcher import fetch from app.utils import compile_tweet_link, process_tweet_text, get_most_similar_tweets, send_tweet, \ get_action, ActionType, send_no_reference_tweet import tweepy logging.basicConfig(filename='app.log', for...
3,006
1,007
import os from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.core.files.storage import DefaultStorage from django.utils.translati...
3,649
1,073
from pymodm import MongoModel, fields from models.target import Target from models.user import User class Dive(MongoModel): diver = fields.ReferenceField(User) target = fields.ReferenceField(Target) created_at = fields.DateTimeField() location_correct = fields.BooleanField() new_x_coordinate = fie...
1,769
509
#!/usr/bin/env python from PIL import Image import sys, glob, tqdm, os import numpy as np from colour import Color def usage(): print("./evaluate.py <imgdir> <outdir> <mode>") print("") print("\timgdir = folder of OCT B scans") print("\toutdir = EMPTY folder to output segmentation masks") print("\t...
3,193
1,334
from tkinter import * import os from datetime import datetime import webbrowser from tkinter import messagebox from tkinter import ttk import tkinter.filedialog import tkinter as tk import openpyxl from REPORTE import * datos = [] #reporte precios = [] #precios preciosmq=[] #precios mq subtotales = [] def CREAR_INTER...
29,604
8,751
""" Plot data split by compartments Classes: * :py:class:`CompartmentPlot`: compartment plotting tool """ # Standard lib from typing import Tuple, Optional, Dict # 3rd party imports import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # Our own imports from .styling impo...
16,156
4,880
import torch import numpy as np def train_perm_orth(train_loader, model, optimizer, scheduler, criterion, regularizer=None, rho=1E-4, delta=0.5, nu=1E-2, eps=1E-3, tau=1E-2, lagrange_pen=1E-2, perm_flag=True, t_step=40): if perm_flag: tau_min = 1E-24 tau_max = 1E-1 c = ...
10,874
3,567
from unittest import mock import unittest import pytest from .main import some_func class TestMain(unittest.TestCase): @pytest.fixture(autouse=True) def _setup_service(self): self.mock_object = mock.MagicMock() def test_some_func(self): assert some_func() == 3 # def test_mock(self)...
374
124
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.keras.applications.densenet namespace. """ from __future__ import print_function as _print_function import sys as _sys from keras.applications.densenet import DenseNe...
566
183