text
string
size
int64
token_count
int64
from django.contrib import admin from .models import Hire, Apply # Register your models here. class HireAdmin(admin.ModelAdmin): list_display = ['id', 'kind', 'start_date', 'end_date'] list_display_links = ['id', 'kind'] class ApplyAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'hire'] list_dis...
424
141
# PyZX - Python library for quantum circuit rewriting # and optimization using the ZX-calculus # Copyright (C) 2018 - Aleks Kissinger and John van de Wetering # 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 co...
9,422
3,030
''' 그래프의 데이터를 저장할 때는 크게 두 가지 방법이 존재한다. 인접행렬과 인접리스트 방식이 존재하는데, 각각의 장단점이 있으니 이를 파악해두자. 먼저 인접행렬의 장단점을 살펴보자. [인접행렬] 장점 : 구현이 쉽다. 단점 : 엣지의 개수가 적을 때, 불필요한 검색 연산이 들어가며 불필요한 메모리 낭비도 발생한다. ex) 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0 엣지의 개수는 2개밖에 없지만 탐색을 시작하면 16번의 연산이 일어날 수 있다. 또한, 큰 의미가 없는 '0' 이라는 데이터를 잔뜩 저장해야 한다. 이러한 인접행렬은 포화트...
538
732
import imgurScraper as IS import Tkinter, Tkconstants, tkFileDialog, tkMessageBox, tkFileDialog, threading, os class Interface: def __init__(self, top): self.downloadThread = None top.resizable(0, 0) frame = Tkinter.Frame(top, borderwidth=3) self.scraper = IS.scraperObject() ...
5,533
1,782
# Provided by Liu Benyuan in https://github.com/inducer/meshpy/pull/11 from __future__ import division import meshpy.triangle as triangle import numpy as np def round_trip_connect(start, end): return [(i, i+1) for i in range(start, end)] + [(end, start)] def refinement_func(tri_points, area): max_area=0.1 ...
1,741
750
""" 1 - Reads the csv files that contain all the coordinates of apple, stem, gravity and origin 2 - Obtains the angles: Hand-to-Stem, Hand-to-Gravity and Stem-to-Gravity which are the key to replicate a pick 3 - Some references https://stackoverflow.com/questions/11140163/plotting-a-3d-cube-a-sphere-and-a-vector-i...
17,962
7,026
from django.db import models from django.utils.translation import ugettext_lazy as _ from foundation_public.models.abstract_place import AbstractPublicPlace class PublicCountry(AbstractPublicPlace): """ A country. https://schema.org/Country """ class Meta: app_label = 'foundation_public' ...
491
144
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os # noqa import unittest from typing import Callable from ..get_graphql_sources import GraphQLSourceGenerator from .test_functions import ...
1,177
365
import numpy import os import os.path as osp import json from random import shuffle import argparse def parse_submission(submission_file): with open(submission_file) as f: lines = f.readlines() submission = {} for line in lines: words = line.strip().split() if len(words) != 2: ...
1,829
639
# 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 # d...
5,061
1,485
import logging import os import cv2 import numpy as np import torch from skimage import io class Dataset(torch.utils.data.Dataset): def __init__(self, config, flist_gt=None, flist=None, test=False, device=torch.device('cpu')): super(Dataset, self).__init__() self.device = device self....
10,645
4,365
from ..prelude import * from .eval import * from .fid import * class EvalReconstructionRealism(Evaluation): table_stat: str = "FID" @torch.no_grad() def produce_images(self, experiment_name: str, dataloader: InvertedDataloader) -> str: print("Saving Reconstruction images...") path = f"...
1,128
383
#!/usr/bin/python ## # all_mounts.fact # This is a custom fact that will gather all # mounts into a fact, ansible_mounts will only # get mounts that are tied to a physical device # that will leave out many mounts ## import os import json ## # get_file_content # gets the content of a file # path - the path to the fil...
1,642
522
import sys, os import re cd = os.path.realpath(os.getcwd()) possible_ns_parent_dir = cd while(True): possible_ns_dir = os.path.join(possible_ns_parent_dir, "h2o-package") possible_ns = os.path.join(possible_ns_dir, "NAMESPACE") if os.path.exists(possible_ns): namespace_dir = possible_ns br...
2,476
881
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import argv, exit from multiprocessing import Process from PyQt4 import QtCore from PyQt4 import QtGui import tftpy class MainWindow(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self._init_ui() self.server = None...
3,182
1,051
from asgiref.sync import async_to_sync from channels.generic.websocket import AsyncWebsocketConsumer, \ WebsocketConsumer import json from blog.models import Comment class ChatConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.room_name = self.scope['url_ro...
3,171
1,221
import argparse import sys import traceback from .oruliner import oruline def main(): usage = ['oruliner --help', 'oruliner [--debug] [infile.py [outfile.py]]', ] parser = argparse.ArgumentParser(usage='\n '.join(usage), description=("if infile is given and outfile is no...
2,183
630
from graphql.language.location import SourceLocation def test_repr_source_location(): # type: () -> None loc = SourceLocation(10, 25) assert repr(loc) == "SourceLocation(line=10, column=25)"
205
69
import re import json from strings import normalize_text from project.server.main.logger import get_logger logger = get_logger(__name__) def construct_regex(a_list): return re.compile('|'.join([f'(?<![a-z]){kw}(?![a-z])' for kw in a_list])) def construct_regex_simple(a_list): return re.compile('|'.join([...
1,418
453
#!/usr/bin/env python # -*- coding: UTF-8 -*- '''================================================= @Project -> File :bytes_concept @IDE :pycharm @Author :xz98y @Date :2022/1/11 22:54 ==================================================''' """ 码位:每一个字符都有一个标识,即码位,是0-1114111之间的数字, 在Unicode中码位以4到6个十六进制数表示,而且加以U+前缀,例如...
705
537
import math from datetime import timedelta, datetime from django.core.cache import cache from django.db import models from django.db.models import F, Prefetch from django.dispatch import receiver from django.db.models.signals import post_delete, post_save from django.contrib.auth.models import User from django.utils.t...
33,003
9,739
#!/usr/bin/env python3 import sports_book_manager.model_probability as mp import unittest class TestMP(unittest.TestCase): """ Tests valid inputs for model_probability return results. """ def test_valid_tests(self): """ Tests to make sure outputs are occuring with valid inputs. ...
448
148
import datetime class QueryConstructorService(object): """Class for formatting query and download sql""" @staticmethod def format_dataset_query(dataset_name, params): agg_by = params['aggregate_by'] agg_values = params['aggregate_values'] agg_admin = params['aggregate_admin'] ...
4,558
1,243
# *************************** Desafio 092 ***************************** # # Cadastro de Trabalhador em Python # # Crie um programa que leia nome, ano de nascimento e carteira de # # trabalho e cadastre-o (com idade) em um dicionário. Se por acaso a # # CTPS for diferente de ...
1,538
547
from typing import Iterable from django.db.models import QuerySet from django.db import IntegrityError from users.models import User from events.models import ( EventCategoryTypeSubscription, SubscriptionActionType, EventCategoryType, ) from events.logic.event import get_event_category_types def get_eve...
2,227
590
import torch from torch.nn import ReLU def l2n(x, eps=1e-6): return x / (torch.norm(x, p=2, dim=1, keepdim=True) + eps).expand_as(x) def powerlaw(x, eps=1e-6): x = x + eps return x.abs().sqrt().mul(x.sign()) def alexnet(net): return list(net.features.children())[:-1] def vggnet(net): return ...
919
371
import os import pytest import shutil import subprocess import sys from .base_module_check import * def test_run_check_default(basic_build_bad_content): ctx = basic_build_bad_content.run_tools(["cppcheck", "cpplint"]) assert len(ctx.file_analysis_map) != 0 for file_name, file_analysis in ctx.file_analysi...
1,077
382
# baseline cnn model for mnist from numpy import mean from numpy import std from matplotlib import pyplot from sklearn.model_selection import KFold from keras.datasets import mnist from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPool...
3,693
1,361
# coding=utf-8 file_path = './data/letters_source.txt' with open(file_path) as f: source_data = f.read()
113
48
import pytest import responses from requests import HTTPError from config.enums import Network from src.token_utils import get_token_price @responses.activate def test_get_token_price_prod(): currency = "usd" price = 8.75 responses.add( responses.GET, f"https://api.badger.finance/v2/price...
1,859
774
from sim import TABLE_MIN def place_6_8(player, point): if not 'place-6' in player.current_bets: player.bet('place-6', 18) if not 'place-8' in player.current_bets: player.bet('place-8', 18) def place_inside(player, point): for i in [6, 8]: if not 'place-%s' % i in player.current_be...
486
189
from MergeSort import mergeSort from QuickSort import quickSort from HeapSort import heapSort from InsertionSort import insertionSort import time import sys import openpyxl import math sys.setrecursionlimit(992233720) #這裡設定大一些 sort_fun = input("please input sorting method (merge/quick/heap/insertion):") n = int(input...
1,783
660
import http import connexion_buzz class InvalidPhone(connexion_buzz.ConnexionBuzz): status_code = http.HTTPStatus.BAD_REQUEST
133
48
""" Code for writing simple summaries of analyzed data. """ from common import (write_status, write_summary, sort_data, render_exception) def summary_by_dev_and_network(data, devs, networks): if not devs: return '' ret = 'Format: ({})\n'.format(', '.join(networks)) for dev in devs: ret += '...
1,864
564
# -*- coding: utf-8 -*- # Python Repo Template # .................................. # Copyright (c) 2017-2018, Kendrick Walls # .................................. # Licensed under MIT (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # ..........
1,218
412
from django.shortcuts import render from django.http import JsonResponse from rest_framework import viewsets from rest_framework.response import Response from .models import Player, Team from .serializers import PlayerSerializer, TeamSerializer def APIWelcomeView(request): return JsonResponse({'result':'error', ...
1,026
291
""" Algorithm 3.4 of 'Numerical Optimization' by Jorge Nocedal and Stephen J. Wright This is based on the MATLAB code from Michael L. Overton <overton@cs.nyu.edu>: http://cs.nyu.edu/overton/g22_opt/codes/cholmod.m """ import numpy import scipy.sparse def gill_king(mat, eps=1e-16): """ Gill-King algorithm fo...
3,251
1,180
#index urls.py from django.urls import path from .views import * urlpatterns= [ path('',materias.as_view(), name="materias") ]
132
48
# -*- coding: utf-8 -*- #BEGIN_HEADER import os import re import sys from datetime import datetime from pprint import pformat # ,pprint from installed_clients.KBaseReportClient import KBaseReport from installed_clients.SetAPIServiceClient import SetAPI from installed_clients.WorkspaceClient import Workspace as worksp...
145,964
41,226
import pysat from pysat.pb import PBEnc from itertools import product, permutations # ============================================================================ # Utilities for problems that involve 1v1 dice comparisons # ============================================================================ def build_clause...
12,606
4,457
import socket import unittest import tests.test_helpers as h class TestBlksize(unittest.TestCase): @classmethod def setUpClass(cls): with open('LICENSE', 'rb') as f: cls.license = f.read() cls.server_addr = ('127.0.0.1', 9069,) cls.blk_rrq = (h.RRQ + ...
2,650
1,120
#!/usr/bin/env python # Takes a .xml formatted blast results file as input and prints the query and hit ids # for sequences passing the thresholds passed via the command line arguments. For sequences # with no hits below the thresholds, the program returns "no hits below threshold" rather # than the hit id. import ge...
3,551
1,409
""" PythontoHTML : use python functions to create html document ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from .__about__ import __name__, __version__, __author__, __author_email__, __license__
217
61
from datetime import datetime from sqlite3 import connect from typing import Dict, NamedTuple, Optional, Mapping import json from black import line_to_string import kfp.dsl as dsl import kfp from kfp.components import func_to_container_op, InputPath, OutputPath import kfp.compiler as compiler from kfp.dsl.types import...
15,874
5,057
#! /usr/bin/env python3 # coding: utf-8 import copy import datetime as dt import subprocess import sys import typing as t from io import BytesIO from pathlib import Path import dropbox import piexif from geopy.distance import great_circle from PIL import Image from resizeimage import resizeimage from kamera import co...
6,743
2,287
seg = int(input('digite um valor inteiro: ')) min = seg / 60 hrs = seg / 3600 print(f'{seg} segundos é equivalente a {min:.2f} minutos ou {hrs:.2f} horas')
155
71
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ Confidential ML utilities. """ from .constants import DataCategory # noqa: F401 from .logging import enable_confidential_logging # noqa: F401 from .exceptions import prefix_stack_trace # noqa: F401 import warnings __version__ = "0.9.1" ...
532
181
"""This package contains instantiation implementations.""" # from bqskitrs import CeresInstantiater from __future__ import annotations from bqskit.ir.opt.instantiaters.minimization import Minimization from bqskit.ir.opt.instantiaters.qfactor import QFactor instantiater_order = [QFactor, Minimization] __all__ = [ ...
382
128
from skatteetaten_api import main_relay import requests from pathlib import Path # Slå av sertifikat verifikasjon i test import urllib3 urllib3.disable_warnings() ALTINN_URL = "https://skd.apps.tt02.altinn.no" def hent_altinn_token(idporten_token: dict) -> dict: altinn3 = "https://platform.tt02.altinn.no/authent...
3,971
1,517
# -*- coding: utf-8 -*- """Untitled36.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1MdrNEYLEdkdvrNak3maz1C1n3o5hIz_o """ print("Hello prudhvi") x= "Garapati" y = " Prudhvi" print(x+" "+y)
264
122
from .Gallery import UserGalleryHandler, UserGalleryApiHandler
64
18
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-07-12 16:39 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations...
3,448
996
# authentication / authorization related error classes class UserUnknownError(Exception): pass class TokenVersionError(Exception): pass class AuthenticationError(Exception): pass class NotAuthorized(Exception): pass
240
60
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: return (lambda f: lambda *args: collections.deque(itertools.accumulate(chain((((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: lambda: y(y)(*args))))(f))(*args),), itertools.repeat(None)), lambda f, _: (lambda f: f() if calla...
1,074
360
from rest_framework import viewsets, permissions, response, views from .utils import RestaurantSerializer from .models import Restaurant class StatisticView(views.APIView): """ Return a list of specifics restaurants. """ def get_object(self, pk): try: restaurants = Restaurant.objec...
1,127
322
# -*- coding: utf-8 -*- __author__ = 'luckydonald' from .exceptions import NoResponse, IllegalResponseException from .encoding import to_unicode as u from time import sleep import atexit import logging logger = logging.getLogger(__name__) __all__ = ["receiver", "sender", "Telegram"] class Telegram(object): """ ...
4,975
1,818
import numpy as np import collections from robel.dkitty.orient import DKittyOrientRandom from robel.dkitty.walk import BaseDKittyWalk from robel.simulation.randomize import SimRandomizer from typing import Dict, Optional, Sequence, Tuple, Union class DKittyWalkRandom(BaseDKittyWalk): """Walk straight towards a ran...
3,963
1,303
from io import BytesIO from django.core.files import File import pytest @pytest.fixture def private_file(request): from testapp.models import File as FileModel file = FileModel() file.file.save("dummy.txt", File(BytesIO(b"dummy"))) file.image.save("dummy.png", File(BytesIO(b"dummy"))) def fin(...
463
159
from tkinter import PhotoImage class Card: def __init__(self, face_value, face_img_path, back_img_path): self.face_value = face_value self.face_img_path = face_img_path self.face_img = None # PhotoImage(file=face_img) self.back_img_path = back_img_path self.back_img = Non...
876
300
# START LAB EXERCISE 06 print('Lab Exercise 06 \n') import csv # PROBLEM 1 (4 Points) def read_csv(filepath, encoding='utf-8', newline='', delimiter=','): """ Reads a CSV file, parsing row values per the provided delimiter. Returns a list of lists, wherein each nested list represents a single row from th...
5,106
1,494
# Данный пример позволяет устанавливать угол сервопривода. # $ Строки со знаком $ являются необязательными. # from pyiArduinoI2Cexpander import * # Подключаем библиотеку для работы с расширителем выводов. from time import sleep ...
2,183
782
# FinSim # Copyright 2018 Carnegie Mellon University. All Rights Reserved. # NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, ...
1,497
532
OCTICON_CHEVRON_DOWN = """ <svg class="octicon octicon-chevron-down" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M12.78 6.22a.75.75 0 010 1.06l-4.25 4.25a.75.75 0 01-1.06 0L3.22 7.28a.75.75 0 011.06-1.06L8 9.94l3.72-3.72a.75.75 0 011.06 0z"></path></svg> "...
323
218
from ..models import User, Weapon, Location, Slack from ..app import Session from ..util.log import getLogger _log = getLogger(__name__) def session(f): ''' Creates a new database session per call wrapped functions should return a 2-tuple of 1) a list of models to be added to the session and 2) value to re...
2,601
1,038
# coding: utf-8 import sys class Logstdout(object): def __init__(self, filename='default.log', stream=sys.stdout): self.terminal = stream self.log = open(filename, 'a') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass # sys.std...
392
138
#!/usr/bin/env python # coding: utf-8 # # BCG Gamma Challenge # # Libraries # In[1]: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy import stats # In[2]: pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) # # Dataset # In...
1,400
700
#------------------------------------------------------------------------------ # Name: Real Import Wrapper for MBTA # # Purpose: This function interfaces with a csv containing ridership data # provided by Boston's Massachusetts Bay Transportation Authority. # This function only pro...
8,260
2,455
from models.unet import UNet import torch from utils.utils import get_latest_checkpoint class EventGANBase(object): def __init__(self, options): self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.generator = UNet(num_input_channels=2*options.n_image_channels, ...
1,627
447
import pandas as pd import numpy as np import os import cv2 from PredictFeatures.VisualizeBox import BoxTemplate from PredictFeatures.MakeVideo import * import csv import math class SequenceExtracter: df_all = pd.read_csv('./data/ehmt1/VideoNamesStatus.csv') def __init__(self, vidnumber,): self.df = Se...
9,481
2,988
# !/usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
11,149
3,249
import abc import argparse import dateparser import io # 3p from datetime import timedelta import pandas as pd import boto3 from botocore import UNSIGNED from botocore.config import Config # usage: filter [-h] [--input-bucket INPUT] [--output-bucket OUTPUT] [--days DAYS] # [--hour HOUR] [--hour-range HO...
9,724
3,154
""" Example: python3 get-status.py """ import requests import sys import os import json import time from datetime import timedelta, date, datetime hostname = "go-echarger" def main(argv): datestring = datetime.now().strftime("%Y_%m_%d-%H-%M-%S") url = "http://" + hostname + "/status" r = requests.get...
5,338
2,146
import string def decrypt(file): #open text file in read mode ct = [] with open(file, "rb") as f: while (byte := f.read(1)): char = int(byte,16)-18 char = 179 * char % 256 ct.append(char) return bytes(ct) ct = decrypt('./msg.enc') f = open('./msg.txt',...
353
136
import sys import os import tables import numpy as np import qtl_fdr_utilities #V0.1.1 class hdf5_writer: def __init__(self,output_filename): self.h5file = tables.open_file(output_filename,'w') def close(self): self.h5file.close() def add_result_df(self,qtl_results_df): assert(l...
4,720
1,481
import os from base import TestBase class ExceptionsTest(TestBase): snippet_dir = "exceptions" def test_raise(self): self.validate_snippet(self.get_snippet_path("raise")) def test_raise_attr(self): self.validate_snippet(self.get_snippet_path("raise_attr")) def test_raise_assigned(s...
397
139
from __future__ import ( absolute_import, unicode_literals, ) from typing import ( Any, Dict, List, Optional, Union, cast, ) from conformity import fields from conformity.settings import ( Settings, SettingsSchema, ) import six __all__ = ( 'ExpansionConverter', 'Expan...
19,221
4,567
# Importing libraries #general stuff import numpy as np import matplotlib.pyplot as plt import pandas as pd #apna time ayega from preprocessing import * from util import * #sk learn from sklearn.svm import SVR from sklearn.model_selection import train_test_split datasets=["B0005.mat","B0006.mat","B0007...
3,081
1,366
""" Writer ------------------- Writing functionalty for **TFS** files. """ import logging import pathlib from collections import OrderedDict from typing import List, Union import numpy as np import pandas as pd from pandas.api import types as pdtypes from tfs.constants import DEFAULT_COLUMN_WIDTH, INDEX_ID, MIN_COLU...
10,277
3,184
"""Generate random data for the project.""" from dataclasses import dataclass, field, asdict from typing import Optional from random import choice, seed as py_rand_seed from pathlib import Path import numpy as np from faker import Faker import pandas as pd from dateutil import parser, rrule fake = Faker() seed = 111...
7,447
2,753
import numpy as np import pandas as pd import socket from tensorflow.keras.applications.vgg16 import preprocess_input def load_classes(num_classes, df='imagenetA'): """ load in all imagenet/imagenetA or other dataframe classes, return: ------- n classes of wnids, indices and descriptions ...
1,249
431
"""Infer allelic imbalance effects from allelic read counts using Bayesian inference.""" import os import shutil import logging import tempfile import traceback from argparse import Namespace from collections import OrderedDict import arviz as az import pymc3 as pm from pysam.libctabix import asBed, asTuple from .zu...
9,321
3,147
#!/usr/bin/env python3 """ Write your code in this file. Fill out the defined functions with your solutions. You are free to write additional functions and modules as you see fit. """ import analyze_functions as analyze_functions import date_time_functions as date_time_functions def analyze_text(): """ Analy...
2,806
877
import pandas as pa import numpy as np import matplotlib.pyplot as plt datset=pa.read_csv("Salary_Data.csv") x= datset.ix[:,:-1].values #indepedent experience y= datset.ix[:,1].values #dependent salary from sklearn.cross_validation import train_test_split xtrain, xtest, ytrain, ytest = train_test_spl...
1,059
406
from boto3 import client from datetime import datetime from io import StringIO from os import getenv from pandas import concat, DataFrame, read_csv, set_option #load_dotenv() # To run this task while working on it, set the below to True, so that there appears to be an uncleaned file to work on, # and so that you are ...
17,667
5,685
from django.db import models class Color(models.Model): COLORS = ( ('black', 'Czarny'), ('light-blue', 'Jasny niebieski'), ('blue', 'Niebieski'), ('light-green', 'Jasny Zielony'), ('green', 'Zielony'), ('pink', 'Różowy'), ('purple', 'Fioletowy'), ('b...
990
334
# Databricks notebook source # MAGIC %md # MAGIC # Model Management # MAGIC # MAGIC An MLflow model is a standard format for packaging models that can be used on a variety of downstream tools. This lesson provides a generalizable way of handling machine learning models created in and deployed to a variety of environm...
12,692
4,283
""" Overtime ======== Overtime is a Python package for the creation and analysis of temporal networks. """ # check installed python version import sys if sys.version_info[:2] < (3, 7): m = "Python 3.7 or later is required for Overtime ({}.{} detected)." raise ImportError(m.format(sys.version_info...
659
218
from importd import d d( DEBUG=True, SMART_RETURN=True, ) # configure django def real_index2(request): return d.HttpResponse("real_index2") d(# configure other urlpatterns d.patterns("", ("^$", real_index2), ) ) @d # /index/ def index(request): import time return "index.html", {"msg"...
1,036
409
from distutils.core import setup setup( name = 'kkltk', # package name packages = ['kkltk'], # same as "name" version = '1.0', # first version license='MIT', # This package is licenced under MIT licence description = 'kkltk is a toolkit designed for Kinyarwanda and Kirundi language...
1,725
539
# 3) def asterisco(): num = int(input("Quantos asteriscos :")) contador = 0 while contador < num: print( end = "*") contador = contador + 1 asterisco()
188
72
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 意味解析で行う処理群を記述したクラス ''' from lark import Transformer, v_args from hiyo.vm.hiyo_vm.id import ID __author__ = 'Okayama Kodai' __version__ = '1.0.0' @v_args(inline=True) class TreeTransformer(Transformer): """ Larkで意味解析を行うためのクラス """ def __init__(self...
4,174
1,458
import pandas as pd try: from pandas.io.formats.excel import ExcelFormatter except ImportError: from pandas.formats.format import ExcelFormatter from pandas.io.common import _stringify_path from .xl_types import XLCell from .chart_wrapper import create_chart, SINGLE_CATEGORY_CHARTS, CATEGORIES_REQUIRED_CHART...
19,096
5,261
import config import GeodesignHub, shapelyHelper from shapely.geometry.base import BaseGeometry from shapely.geometry import shape, mapping, shape, asShape import os, sys, requests, geojson import json, pyproj import string, random from operator import itemgetter from rtree import Rtree from shapely.validation import e...
19,848
7,177
import pandas as pd from flask import Flask, jsonify, request, make_response from openpyxl import Workbook from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl.writer.excel import save_virtual_workbook app = Flask(__name__) @app.route("/") def index(): return jsonify({ 'message': 'Welcome...
1,638
510
import asyncio import functools as ft SQL_CREATE_TABLE = [ ''' CREATE TABLE people ( id INTEGER PRIMARY KEY, name TEXT ); ''', ] def sync(method): @ft.wraps(method) def wrapper(self, *args, **kwargs): loop = asyncio.get_event_loop() f = method(self, *args, **k...
388
132
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2015 Nippon Telegraph and Telephone 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/lic...
6,903
1,561
import multiprocessing import time from config import Config from simulation_constants import END_MESSAGE from lib.helper import get_log_func import simulation log = get_log_func("[headless]") SECONDS_TO_RUN = 120 # specify the mode in which the simulation is run # to alter cluster values open appropriate json files...
1,697
549
import gym import gym_panda #need to be imported !! import random import numpy as np import matplotlib.pyplot as plt import time import execnet from pilco.models import PILCO from pilco.controllers import RbfController, LinearController from pilco.rewards import ExponentialReward import tensorflow as tf from gpflow ...
2,420
1,001
# https://wiki.freecadweb.org/Scripting_examples # https://wiki.freecadweb.org/Mesh_to_Part import FreeCAD, Part, Drawing, time import Mesh DOC = FreeCAD.activeDocument() DOC_NAME = "Pippo" def clear_doc(): """ Clear the active document deleting all the objects """ for obj in DOC.Objects: DOC....
3,654
1,226
import json from datetime import date, datetime, timedelta import pytz from django.db.models import Avg, DateTimeField, Max, OuterRef, Subquery, Sum from django.db.models.query import QuerySet from django.utils.timezone import now from i18nfield.strings import LazyI18nString from pretix.base.models import Item, OrderP...
9,165
3,037