text
stringlengths
8
6.05M
from urlparse import urlparse from httplib import HTTPConnection import sys def getTokenFromBody(body): index_cookie = body.find('user_token')+19 substr = body[index_cookie:] index_cookie_end = substr.find("'") token = substr[:index_cookie_end] #print "token is "+token return token url = "http://10....
from django.db import models from django.db.models.fields import DecimalField, IntegerField from django.contrib.auth.models import User # Create your models here. class Dashboard(models.Model): totalnoofrides = IntegerField(null=True, blank=True) cancelledpercentage = DecimalField(max_digits=4, null=True, bl...
from utility import Global #testSampleResultFile.SPBest.nwlen=1000000.mds=1000.t=0.ns=200.r=2.k=5.nw=5.wf=0 input_path = "D:\\nowMask\\KnowledgeBase\\data\\DataSet\\DBpedia\\orginal\\" output_path = "D:\\nowMask\\KnowledgeBase\\data\\DataSet\\DBpedia\\orginalIndex\\" def sample_res_path(dir, sp='SPBest', nwlen=100000...
from onegov.form import Form from onegov.form.fields import ChosenSelectField, ChosenSelectMultipleField from onegov.form.fields import PhoneNumberField from onegov.form.validators import UniqueColumnValue from onegov.gazette import _ from onegov.user import User, UserGroupCollection from onegov.user import UserGroup f...
#!/usr/bin/python #\file baynat.py #\brief Go to an initial pose. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Dec.07, 2015 ''' NOTE: run beforehand: $ rosrun baxter_interface joint_trajectory_action_server.py ''' from bxtr import * def GoNatural(robot): q0= [robot.Q(RIGHT),robot.Q(...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-03-04 06:06 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('authentication', '0038_auto_20190302_1628'), ] operation...
from decouple import config import httpx UPSTREAM_URL = config("UPSTREAM_URL", default="https://postman-echo.com/post") """ Helper function which handles async requests to the upstream host and fetches the response """ async def upstream_post(body, token, headers): upstream_headers = { "content-type": he...
from django import forms from sensibilizacao.models import Palestra class CreatePalestraForm(forms.ModelForm): class Meta: model = Palestra fields = '__all__'
from .config import config import pandas as pd import numpy as np from datetime import datetime, timedelta import logging logger = logging.getLogger(__name__) constants = config(section="constants") processing_params = config(section="data") sensors_list = config(section="sensors") sensors_list = sensors_list["includ...
''' Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. https://leetcode.com/problems/counting-bits/#/description 铁定用位运算了,主要是要发现规律,找到这个递推公式,用...
# -*- coding: utf-8 -*- """ Created on Sun Mar 2 21:22:30 2014 @author: atproofer """ # Author: Nelle Varoquaux <nelle.varoquaux@gmail.com> # Licence: BSD # #print(__doc__) import numpy as np from matplotlib import pyplot as plt from matplotlib.collections import LineCollection from sklearn import manifold from sk...
# -*-coding:utf-8-*- # AUTHOR:tyltr # TIME :2018/11/20 import redis from flask_bcrypt import Bcrypt from flask_bootstrap import Bootstrap from flask_httpauth import HTTPBasicAuth from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy from albumy.common.redis_client import RedisClient db = SQLAlchemy() b...
# Pegando dados do usuário nome = input('Qual o seu nome?') idade = input('E a sua idade?') peso = input('E qual o seu peso?') # Imprimindo dados pegos print(nome, 'tem', idade, 'anos de idade e', peso, 'kg')
def intersection(a, b): c = [] x = y = 0 while x < len(a) and y < len(b): if b[y] < a[x]: y += 1 elif b[y] == a[x]: c.append(b[y]) y += 1 x += 1 elif b[y] > a[x]: x += 1 return c A = list(map(int, input().split())) B =...
import scipy.sparse as sparse import scipy.io as sio import numpy as np #spectral, KMeans or gmm TYPEOFCLUSTERING = "spectral" LIMIT = 100 songPosition = {} songMap = {} f= sio.loadmat('/home/dmitriy/workspace/MLFinalProject/MatlabFiles/finalSongIDs.mat') f1= f['finalSongIDs'] for songID in range(0,f1.shape[0]): so...
#!/usr/bin/python import time import numpy as np if __name__=='__main__': t_last= 10.0 dt= 0.001 t0= time.time() L= [] for t in np.arange(0.0,t_last,dt): L+= [t] print 'arange+for:', (time.time()-t0)*1.0e3 t0= time.time() L= [] t= 0.0 while t<t_last: L+= [t] t+= dt print 'while:', (...
import logging from django.db import models from django.utils.translation import ugettext_lazy as _ from sso.core.ip_filter import get_client_ip logger = logging.getLogger(__file__) class SamlApplication(models.Model): slug = models.SlugField( _('slug'), help_text=_('WARNING: changing this may ...
class TrainingOptions: """ Configuration options for the training """ def __init__(self, batch_size: int, number_of_epochs: int, train_folder: str, validation_folder: str, runs_folder: str, start_epoch: int, experiment_name: str): ...
from tkinter import * from visualization import VISUALIZATION from math import radians import cmath import numpy as np from PIL import Image from _DStarLite_ import DStarLite from _AStar_ import astar from GraphUtils import AbstractToGraph def BringToLife(obj,plt,algo,vCalcfct,costfct,heuristicfct): fro...
from django.shortcuts import render import models as fleet_models from django.http import JsonResponse def create(request): if 'char' not in request.session.keys(): return redirect('eveuser:sso') char = request.session['char'] # make sure char isnt already in a fleet fleets = fleet_models.Fle...
from unittest import TestCase import unittest from single_number import Solution class TestSolution(TestCase): def test_singleNumberCase1(self): sol = Solution() self.assertEqual(sol.singleNumber([1]),1) def test_singleNumberCase2(self): sol = Solution() self.assertEqual(sol.si...
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User as UserDjango from django.forms import ModelForm from users.models import User class UserDjangoCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = ('username', 'first_name', 'last_na...
import data_pre_processing as dpp import feature_importance_plot as fip training_data = dpp.get_training_data() data = training_data['data'] target = training_data['target'] features = training_data['features'] features_entities = training_data['features_entities'] target_names = training_data['target_names'] for fea...
import os import matplotlib.pyplot as plt import numpy as np from models.senet import SENet from neural_network import NeuralNetwork from games.tictactoe import TicTacToe from games.tictacmo import TicTacMo from players.deep_mcts_player import DeepMCTSPlayer from players.uninformed_mcts_player import UninformedMCTSPla...
import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy import os import itertools import math # TO BE CHANGED --> trial for new REAL data; select code blocks for respective runs trial = 'trial_12_05_20' #real # trial_list = ['train_12_28_20', 'train_12_29_20'] #286 load size # label_list...
#_*_coding:utf-8_*_ from django import forms from models import Spool class SpoolForm(forms.ModelForm): class Meta: model = Spool fields = ['uuid','origin_email','accept_email','origin_uuid','accept_uuid','printer_name','printer_uuid','file_name','file_path','file_client_path','page_num']
#!/usr/bin/python # -*- encoding: utf-8 -*- ########################################################################### # Module Writen to OpenERP, Open Source Management Solution # Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>). # All Rights Reserved ################################################...
baseAddress = "192.168.0." hostAddress = range(20) ipRange = [] for i in hostAddress: ipRange.append(baseAddress + str(i)) for ipAddr in ipRange: print ipAddr print "process completed"
import os def compose(netlist, filename): """To compose a file into a netlit format""" extension = os.path.splitext(filename)[1] extension_lower = extension.lower() if extension_lower in {".edf", ".edif"}: from spydrnet.composers.edif.composer import ComposeEdif composer = ComposeEdif(...
#-*- coding:utf8 -*- from django.contrib import admin from shopapp.notify.models import ItemNotify,TradeNotify,RefundNotify class ItemNotifyAdmin(admin.ModelAdmin): list_display = ('id','user_id','num_iid','title','sku_id','sku_num','increment','nick', 'num','price','changed_fields','modified...
''' Created on 28.08.2018 @author: FM ''' import unittest import unittest.mock as mock from FileSet import FileSet from test.testing_tools import mock_assert_msg, KeywordArgTuple def preserve_gaps(boolean): return KeywordArgTuple('preserve_gaps', boolean) def strip_gaps(boolean): return Keywo...
import tkinter as tk from tkinter import ttk from tkinter import scrolledtext as sk win = tk.Tk() def m_f(): checher = buttvar.get() if checher == 0: return 'male' elif checher == 1: return 'female' # def check(): # allo = curent # if allo == 0: # return 'good' # else...
from django.contrib import admin from .models import Contact # Register your models here. class ContactAdmin(admin.ModelAdmin): pass admin.site.register(Contact, ContactAdmin)
from gitmostwanted.services.celery import instance from unittest import TestCase, mock from gitmostwanted.web import app class ServicesCeleryTestCase(TestCase): def test_use_flask_context(self): context = mock.MagicMock() app.app_context = lambda: context app.config['CELERY_ALWAYS_EAGER']...
# coding=utf-8 from django.db import models from ckeditor.fields import RichTextField from likes.models import Likes from comment.models import CommentParent class PopularManager(models.Manager): def filter_by_popularity(self, *args, **kwargs): """ Раширение objects.filter() сортировкой по популярности"...
import pandas as pd import numpy as np import matplotlib.pyplot as plt mu = 10, 20 sigma = 5, 2 dist = pd.DataFrame(np.random.normal(loc = mu, scale = sigma, size = (1000, 2)), columns=["x1", "x2"]) dist dist.agg(["min", "max", "mean", "std"]) # Densidad y función de probabilidad fig, ax = plt.subplots() dist.plot.k...
from datetime import datetime import random from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect, get_object_or_404 import serial def show_graph(request,template_name='live_graph.html'): return render(request,template_name) def fetch_sensor_values_ajax(request): d...
/Users/Di/anaconda/lib/python2.7/os.py
# -*- coding: utf-8 -*- # Parameters: # - background # - color # - shape_appearance # - text_appearance # - theme # - widget_style # - window_configuration # Output image: # attr name | android_framework | app_compat | material_component # :-- | :--: | :--: | :--: # editTextBackground | ◯ | ◯ | ー __...
class BST: def __init__(self): self.root = None self.items = [] class Node: def __init__(self, key, left = None, right = None): self.key = key self.left = left self.right = right def insert(self, root, key): if not self.root: ...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems 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 # # ...
from collections import OrderedDict PARAMS = { "format": "default", "field": "complaint_what_happened", "frm": 0, "no_aggs": False, "no_highlight": False, "size": 10, "sort": "relevance_desc", } # -*- coding: utf-8 -*- DELIMITER = u'\u2022' SOURCE_FIELDS = ( "company", "company_p...
""" WEEK 7 TASKS 1 AND 2 "GRAPHS, BFS AND DFS" """ def addNode(node, graph): #NODE CREATE FUNCTION graph[node] = [] #TAKES ARGUMENTS (VALUE OF THE NODE, A DICTIONARY) #SETS THE VALUE OF THE NODE AS THE KEY AND KEEPS THE VALUE ...
from urllib.parse import urlparse from PIL import Image, ImageDraw import os, io, forecastio, config, pytz, urllib, shutil, ffmpeg, mimetypes, time, moabim.utils as utils from datetime import datetime, timezone from boto3 import session from aws_requests_auth.aws_auth import AWSRequestsAuth from concurrent.futures impo...
import sys import struct import time import os import textwrap import random from contextlib import contextmanager sys.path.append(".") import unittest import windows import windows.debug import windows.native_exec.simple_x86 as x86 import windows.native_exec.simple_x64 as x64 import windows.native_exec.nativeutils as...
# imageapi/urls.py from django.conf.urls import url from imagesapi import views urlpatterns = [ url(r'convertSomeToSomeView', views.convertSomeToSomeView.as_view()), url(r'uploadFile', views.uploadFile), ]
from os import system from random import randint from datetime import datetime def get_current_time(): return datetime.now() def is_5_minutes_done(start_time): current_time = get_current_time() return ((current_time - start_time).total_seconds()) / 60 >= 5 def get_percent_score(questions_count, score...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2018-01-24 06:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('diagnoses', '0001_initial'), ] operations = [ migrations.AddField( ...
run profile1 # 경로 확인 import os os.getcwd() # 경로변경 os.chdir('C:\\Users\\kitcoop\\.spyder-py3\\새 폴더') os.chdir('C:\\Users\\kitcoop\\.spyder-py3\\분석') # 원 핫 코딩 (dummies) - 문자 변수를 0과 1의 값을 갖는 이진 데이터로 변경 - 모델에 따라 문자값의 학습 불가한 경우 사용 - 딥러닝 모델에서의 Y값은 원 핫 인코딩이 필수 # 예제) 아래 데이터 프레임에서 col1의 컬럼 값을 이진 데이터로 표현 df...
import uuid import logging from typing import List from pydantic import BaseModel from starlette.applications import Starlette from starlette.websockets import WebSocketDisconnect, WebSocket from starlette.routing import WebSocketRoute class ConnectionManager: async def connect(self, websocket: WebSocket): ...
""" Django settings for mystore project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os...
# -*- encoding:utf-8 -*- import logging import random import string # # create logger # logger_name = "example" # logger = logging.getLogger(logger_name) # logger.setLevel(logging.DEBUG) # # # create file handler # # log_path = "./log/log.log" # fh = logging.FileHandler(log_path) # fh.setLevel(logging.WARN) # # # crea...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.8 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('bool数据类型实验') str1 = 'www.juzicode.com' print('str1:',str1) print('www in str1:','www' in str1) # www是否在str1中 print('orange in str1:','or...
# A concise python code based tutorial for (mathmatical) optimization # https://github.com/sorayng/python-in-optimization-tutorial # Python Version: 3.3.3 # Contact: Sean Yang - yng(at)outlook.com # Task 1 - Newton's method for finding a root # Date: 2014.01.10 # Description: # 1. This routine tries to find a root of ...
#!/usr/bin/env python import vtk class vtkTimerCallback(): def __init__(self, steps, actor, iren): self.timer_count = 0 self.steps = steps self.actor = actor self.iren = iren self.timerId = None def execute(self, obj, event): step = 0 while step < self....
from rest_framework import serializers class ProjectsField(serializers.RelatedField): def to_representation(self, value): return value.as_json()
# Generated by Django 3.0.4 on 2020-04-18 03:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Component', fields=[ ...
from django.urls import path from . import views urlpatterns = [ path('get/', views.get, name="get"), path('get/item/<str:pk>/', views.itemView, name="itemView"), path('get/category/<str:pk>/', views.categoryView, name="categoryView"), path('get/item/<str:pk>/buy/', views.itemBuy, name="itemBuy"), ...
# Fibonacci series # 1,1,2,3,5,8.................n # 1, 1+1 = 2, 2+1 = 3, 3+2 = 5 ............ n def fib (n): if n == 1: return 1 elif n == 2: return 2 elif n > 2: return fib (n-1) + fib (n-2) for n in range (1,11): print (n, ':', fib(n)) # if we will us...
#!/usr/bin/python # -*- coding: utf-8 -*- import click import os from multiprocessing import Pool import hashlib import json from glob import glob def md5sum(filename): ''' generator md5 for the input file :param filename: file path in file system :return: md5 in hex ''' with open(filename, "rb"...
#!/usr/bin/env python # # Copyright 2014 by Idiap Research Institute, http://www.idiap.ch # # See the file COPYING for the licence associated with this software. # # Author(s): # Phil Garner, January 2014 # import unittest import ssp import numpy as np import numpy.testing as npt class TestSSP(unittest.TestCase): ...
import numpy as np from nltk.corpus import sentiwordnet as swn from nltk.stem import * import nltk import xlrd as xlrd import sys ############################################################################################################################################### ''' <<< stripString >>> Performs stripping (...
N = int( input()) ANS = [0]*N for i in range(N): a, b = map( int, input().split()) ANS[i] = a+b print( max(ANS))
str = 'Hello world' print('str = ', str) print('str[0] = ', str[0]) print('str[-1] = ', str[-1]) print('str[1:5] = ', str[1:5]) print('str[5:-2] = ', str[5:-2])
"""Advent of Code Day 13 - Knights of the Dinner Table""" import itertools import re def calc_happiness(person, neighbour): """Returns the overall hapiness of a pair of people.""" if person == 'me' or neighbour == 'me': return 0 pair_happiness = 0 p_regex = re.compile(r'{} would (gain|lose) ...
#!/usr/bin/env python3 from codon_tools import SequenceAnalyzer, CodonOptimizer, CodonFreqScorer, StopAndCpGScorer from Bio import SeqIO def optimize_codon_freqs(seq, target_seq): scorer = CodonFreqScorer() scorer.set_codon_freqs_from_seq(target_seq) o = CodonOptimizer(scorer) sa = SequenceAnalyzer() ...
# Dependencies from bs4 import BeautifulSoup as bs from splinter import Browser import os import requests import pandas as pd import time import numpy as np # import warnings # warnings.filterwarnings('ignore') def init_browser(): import os if os.name=="nt": executable_path = {'executable_path': './ch...
from ucca4bpm.toolkit.readers.result import ReadResult class BaseReader: def __init__(self, remaining_arguments): pass def read(self, input_path: str) -> ReadResult: raise NotImplementedError() @staticmethod def format_id() -> str: raise NotImplementedError()
import ipaddress import netifaces import os import socket import subprocess import yaml from glob import glob from path import Path from urllib.parse import urlparse from charms import layer from charmhelpers import fetch from charmhelpers.core import hookenv, unitdata from charmhelpers.core.host import ( chdir, ...
''' Created on 11-Feb-2019 @author: prasannakumar ''' class QuestionsClass: def __init__(self, prompt,answer): self.question = prompt self.answer = answer
# import gamengine modules from bge import logic from bge import events from bge import render # import mvb's own module from . import bgui from .helpers import * # native python modules import math, pdb outlinerLabel = "outlinerLabel_" outlinerHelper1 = "outlinerHelper1_" outlinerHelper2 = "outlinerHelper2_" cla...
#-*- coding: utf-8 -*- """ F-Saipe - Flask SqlAlchemy In Page Editor """ __author__ = 'Gustavo Vargas <xgvargas@gmail.com>' __version_info__ = ('0', '1', '0') __version__ = '.'.join(__version_info__) from editor import Saipe, SaipeConfig # from form import FormFromPeewee
# -*- coding: utf-8 -*- # !/usr/bin/env python import sys import os import time import json import tensorflow as tf from aip import AipNlp import pandas as pd reload(sys) sys.setdefaultencoding('utf8') APP_ID = '9585999' API_KEY = 'EHjkhXXsbLXATesvGBLu7PgB' SECRET_KEY = 'tiTrCDQTqMQBbsarcn52CeP0Dc7bgmzT' class Word(...
# starter.py v2 import sys reload(sys) sys.setdefaultencoding('utf8') import json import yaml from jamf import JamfApi from device42 import Device42Api with open('config.yaml', 'r') as cfg: config = yaml.load(cfg.read()) device42 = config['device42'] jamf = config['jamf'] options = config['options'] jamf_api = Ja...
def maxArea( A): l = 0 r = len(A) -1 area = 0 while l < r: # Calculating the max area area = max(area, min(A[l], A[r]) * (r - l)) if A[l] < A[r]: l += 1 else: r -= 1 return area t = int(input()) for _ in range(t): n = int(input()) ...
""" 世界万物,皆可分类 世界万物,皆为对象 只要是对象,肯定属于个类 只要是对象,就肯定有属性 百科全书就是把世界分门别类来描述世界的,面向对象编程就是借助这种思想,将一切对象分门别类; 先总结出要描述事物的特点,按照特点定义可以描述这种事物的类(创建类),每种类都有其特有的属性和方法,有了类, 就可以用类来描述其他相同特点的事物(实例化类) """ """ 面向对象编程 OOP编程是利用“类”和“对象”来创建各种模型来实现对真实世界的描述,使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单,并且可以大大提高程序开发效率 ,另外,基于面向对象的程序可以使它人更加容易理解你的代码逻辑,从而使团队开发变得...
#!/usr/local/bin/python3 def checkout(score): for line in open("checkouts_file", "r"): check = line.split() checkout = {} checkout[int(check[0])] = check[1:] if score in checkout.keys(): print('Get these to checkout:\t', ', '.join(checkout[score])) def game_type(): ...
from django.apps import AppConfig from django.conf import settings import os.path class BotConfig(AppConfig): name = 'bot' verbose_name = "Ilya's GroupMe Bot" def ready(self): home_dir = os.path.expanduser("~") cred_dir = os.path.join(home_dir, '.groupy.key') #write groupy key to ap...
import platform import unittest from collections import defaultdict from conan.builds_generator import BuildConf from conan.packager import ConanMultiPackager from conans.model.ref import ConanFileReference from conans.util.files import load from conans.model.profile import Profile class MockRunner(object): de...
#!/usr/bin/env python # -*- coding: utf-8 -*- from smorest_sfs.extensions.flask import Flask from smorest_sfs.modules.email_templates.models import EmailTemplate def test_get_template(flask_app: Flask) -> None: name = str(EmailTemplate.create(name="test", template="111")) assert name == "test" and EmailTempla...
""" Class Distribution This class implements a distribution object that is defined by its pdf (probability density function) Interestingly, I could not find in numpy/scipy a class that could implement a distribution just from its pdf. The idea of such object is to be able to compute statistics of this distribution w...
import unittest import TTDB class DBTest(unittest.TestCase): def setUp(self): self.mysql = TTDB.TTDB() def tearDown(self): self.mysql.closeDB() def test_create_task(self): self.assertEqual(1, self.mysql.create_task('sprint planning', 'sprint 17092')) def test_show_task(self...
from game.items.item import Ore class SilverOre(Ore): type = 'Silver' name = 'Silver Ore' value = 75
from django.contrib import admin from authors.apps.article_tag.models import ArticleTag # Register your models here. admin.site.register(ArticleTag)
word = input("Enter word: ") n = input("Enter count of words: ") n = int(n) count = 1 words = [] while count <= n: new_word = input("Enter new word: ") words += [new_word] count += 1 count_of_word = 0 for w in words: if w == word: count_of_word += 1 print("Word \"{}\" is found {} times in {...
x = input().split() y = (int(i) for i in x) def even(x): return x % 2 == 0 evens = filter(even, y) for i in evens: print(i)
# =================================================================================================== # Units are checked and converted in cae of inconsistencie with data specified in Include file # So far only adapted for emission fluxes # ===============================================================================...
#!/usr/bin/env python ''' The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence (st...
# coding: utf-8 """ Lilt REST API The Lilt REST API enables programmatic access to the full-range of Lilt backend services including: * Training of and translating with interactive, adaptive machine translation * Large-scale translation memory * The Lexicon (a large-scale termbase) * Programmatic cont...
""" #------------------------------------------------------------------------------ # Input generation for Boom Crane - inputgen.py # # Create a specific vibration and a shaped command that is designed to offset that vibration. # Formatted for input to a small-scale boom crane # # Created: 4/26/17 - Daniel Newman -- da...
import threading import queue import os buffer_size = 5 lock = threading.Lock() queue = queue.Queue(buffer_size) file_count = 0 def producer(top_dir,queue_buffer): # Search sub-dir in top_dir and put them in queue files=os.listdir(top_dir) queue_buffer.put(top_dir,block=True, timeout=0.1) for i in fi...
from typing import Optional, ClassVar, List from collections import namedtuple from math import log, e, ceil from enum import Enum import logging import json import os from .utils import EntropyAlgos shannon = EntropyAlgos.shannon l = logging.getLogger("[encrypted]") EntropyOfBlock = namedtuple( "EntropyOfBlock...
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' SIZE = 101 RESIZE = 128 PAD = 14 Y0, Y1, X0, X1 = PAD,PAD+SIZE,PAD,PAD+SIZE, from common import * ### submitting ############################################################## #augment == 'flip' def test_augment_flip(image, mask, index, scale='pad'): cac...
# 1-Import modules: import os import csv # 2-Set a path to the file we are going to read and pull data from: budget_csv = os.path.join ('Resources','budget_data.csv') # 6-Create lists to store the contents (aka lists) within the column 1 & 2: dates = [] values = [] # 9-Create list to carry out my calculations: delta...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from django.core.management.base import BaseCommand from materialcleaner.settings import FILE_PHOTO_TYPES_BASIC from poster.models import FileType class Command(BaseCommand): help = 'Step 1 @ fill-in new DB. Fill-in photo file types into FileType model/DB acc. FILE_PHOTO_TYPES_BASIC' def handle(self, *...
from drunk_walk import TraditionalDrunk # From drunk_walk file imports the TraditionalDrunk class from drunk_walk import FallenDrunk from field import Field from coordinates import Coordinate # From the coordinates file imports the Coordinate class from bokeh.plotting import figure, show, output_file, save def walk(f...
"""Products models.""" from django.db import models from django.contrib.auth.models import User class Category(models.Model): """Categorie model.""" name = models.CharField(max_length=150, unique=True) def __str__(self): """Nicer str.""" return self.name class Product(models.Model): ...
#!/usr/bin/env python """ _PromptReco_t_ Unit tests for the new Tier1 PromptReconstruction workflow. """ import unittest import os from WMCore.WMBS.Fileset import Fileset from WMCore.WMBS.Subscription import Subscription from WMCore.WMBS.Workflow import Workflow from WMCore.WorkQueue.WMBSHelper import WMBSHelper fr...
# Generated by Django 3.0.5 on 2020-10-30 15:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('log', '0008_auto_20201022_1528'), ] operations = [ migrations.RenameField( model_name='log', old_name='celerytask_id', ...