content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
# -*- coding: utf-8 -*-
"""Data fetching utility for USDA datasets.
This module provides the primary support functions for downloading datasets from
a text file. Each line in the text file is expected to be a complete URL. Lines
that begin with '#' are ignored.
Example:
This module can be run directly with the following arguments:
$ python -m project01.fetch path/to/uri.txt output/dir
The URIs listed in the file path/to/uri.txt will be Files will be saved to output/dir.
If no arguments are specified, they defaults (./uri.txt, and ./dataset)
"""
import os
import sys
import requests
import tempfile
import zipfile
def cli():
"""Creates a CLI parser
Returns:
argparse.ArgumentParser: An Argument Parser configured to support the
fetcher class.
"""
import argparse
parser = argparse.ArgumentParser("Fetch datasets")
parser.add_argument("urifile", nargs="?",
default="uri.txt",
help="Path to file containing URIs to download.")
parser.add_argument("outdir", nargs="?",
default="dataset",
help="Path to a directory to output the files.")
return parser
if __name__ == "__main__":
config = cli().parse_args()
main(uri_file=config.urifile, out=config.outdir)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
6601,
21207,
278,
10361,
329,
29986,
40522,
13,
198,
198,
1212,
8265,
3769,
262,
4165,
1104,
5499,
329,
22023,
40522,
422,
198,
64,
2420,
2393,
13,
220,
5501... | 2.693227 | 502 |
from feeds.alltests.feeds_tests import * | [
6738,
21318,
13,
439,
41989,
13,
12363,
82,
62,
41989,
1330,
1635
] | 3.333333 | 12 |
import numpy as np
import pylab
from scipy import sparse
import regreg.api as rr
Y = np.random.standard_normal(500); Y[100:150] += 7; Y[250:300] += 14
loss = rr.quadratic.shift(-Y, coef=0.5)
sparsity = rr.l1norm(len(Y), 1.4)
# TODO should make a module to compute typical Ds
D = sparse.csr_matrix((np.identity(500) + np.diag([-1]*499,k=1))[:-1])
fused = rr.l1norm.linear(D, 25.5)
problem = rr.container(loss, sparsity, fused)
solver = rr.FISTA(problem)
solver.fit(max_its=100)
solution = solver.composite.coefs
delta1 = np.fabs(D * solution).sum()
delta2 = np.fabs(solution).sum()
fused_constraint = rr.l1norm.linear(D, bound=delta1)
sparsity_constraint = rr.l1norm(500, bound=delta2)
constrained_problem = rr.container(loss, fused_constraint, sparsity_constraint)
constrained_solver = rr.FISTA(constrained_problem)
constrained_solver.composite.lipschitz = 1.01
vals = constrained_solver.fit(max_its=10, tol=1e-06, backtrack=False, monotonicity_restart=False)
constrained_solution = constrained_solver.composite.coefs
fused_constraint = rr.l1norm.linear(D, bound=delta1)
smoothed_fused_constraint = rr.smoothed_atom(fused_constraint, epsilon=1e-2)
smoothed_constrained_problem = rr.container(loss, smoothed_fused_constraint, sparsity_constraint)
smoothed_constrained_solver = rr.FISTA(smoothed_constrained_problem)
vals = smoothed_constrained_solver.fit(tol=1e-06)
smoothed_constrained_solution = smoothed_constrained_solver.composite.coefs
#pylab.clf()
pylab.scatter(np.arange(Y.shape[0]), Y,c='red', label=r'$Y$')
pylab.plot(solution, c='yellow', linewidth=5, label='Lagrange')
pylab.plot(constrained_solution, c='green', linewidth=3, label='Constrained')
pylab.plot(smoothed_constrained_solution, c='black', linewidth=1, label='Smoothed')
pylab.legend()
#pylab.plot(conjugate_coefs, c='black', linewidth=3)
#pylab.plot(conjugate_coefs_gen, c='gray', linewidth=1)
| [
11748,
299,
32152,
355,
45941,
198,
11748,
279,
2645,
397,
197,
198,
6738,
629,
541,
88,
1330,
29877,
198,
198,
11748,
842,
2301,
13,
15042,
355,
374,
81,
198,
198,
56,
796,
45941,
13,
25120,
13,
20307,
62,
11265,
7,
4059,
1776,
575... | 2.318126 | 811 |
from typing import Dict
import aiohttp
from async_timeout import timeout
from openapi.testing import json_body
| [
6738,
19720,
1330,
360,
713,
198,
198,
11748,
257,
952,
4023,
198,
6738,
30351,
62,
48678,
1330,
26827,
198,
198,
6738,
1280,
15042,
13,
33407,
1330,
33918,
62,
2618,
628,
628,
628,
628,
628,
628,
628,
628
] | 3.459459 | 37 |
#!/usr/bin/env python
import os
import subprocess
TID_FILE = "src/tiddlers/system/plugins/security_tools/twsm.tid"
VERSION_FILE = "VERSION"
if __name__ == "__main__":
main() | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
28686,
198,
11748,
850,
14681,
198,
198,
51,
2389,
62,
25664,
796,
366,
10677,
14,
83,
1638,
8116,
14,
10057,
14,
37390,
14,
12961,
62,
31391,
14,
4246,
5796,
13,
83,
312,
1,
... | 2.594203 | 69 |
# coding=utf-8
"""
@author: oShine <oyjqdlp@126.com>
@link: https://github.com/ouyangjunqiu/ou.py
定时器,每隔一段时间执行一次
"""
import threading
| [
2,
19617,
28,
40477,
12,
23,
198,
37811,
198,
198,
31,
9800,
25,
267,
2484,
500,
1279,
726,
73,
80,
25404,
79,
31,
19420,
13,
785,
29,
198,
31,
8726,
25,
3740,
1378,
12567,
13,
785,
14,
280,
17859,
29741,
80,
16115,
14,
280,
13,... | 1.593023 | 86 |
for n in range(10):
print(n, factorial(n))
| [
198,
198,
1640,
299,
287,
2837,
7,
940,
2599,
198,
220,
220,
220,
3601,
7,
77,
11,
1109,
5132,
7,
77,
4008,
198
] | 2.130435 | 23 |
@set_log(1)
def test01():
"""
@super_set_func(1) 带有参数的装饰器,用来区分多个函数都被同一个装饰器装饰,用来区分函数
实现的原理是,把装饰器外边包上一层函数,带有参数
这种特殊的带有参数的装饰器,并不是直接test01 = set_log(1, test01)的,并非直接把函数名传递给set_log
1- @装饰器(参数) 会先**调用**set_log函数,把1当作实参进行传递,此时跟函数名没有关系,先调用带有参数的set_log函数
2- 把set_log函数的返回值,当作装饰器进行装饰,此时才是test01 = super_set_func(test01)
"""
print("----test01----没有参数,没有返回值")
@set_log(2)
class Log(object):
"""
类装饰器,装饰器加载在类上,不在是传统上的加载在方法上面
作用就是:不同于方法装饰器,类装饰器可以在被装饰的方法的前后添加多个自己类的实力方法进行装饰,self.xxx(),self.yyy()
1- @Log 等价于 Log(test03) 初始化Log的init方法,test03函数名作为参数传递
2- 此时test03就指向一个类对象,等test03()调用的时候,相当于调用了类中的call方法
"""
@Log
if __name__ == '__main__':
main()
| [
198,
198,
31,
2617,
62,
6404,
7,
16,
8,
198,
4299,
1332,
486,
33529,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
220,
220,
220,
220,
2488,
16668,
62,
2617,
62,
20786,
7,
16,
8,
10263,
116,
99,
17312,
231,
20998,
224,
46763,
1... | 0.86014 | 858 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of fionautil.
# http://github.com/fitnr/fionautil
# Licensed under the GPLv3 license:
# http://http://opensource.org/licenses/GPL-3.0
# Copyright (c) 2015, Neil Freeman <contact@fakeisthenewreal.org>
import collections
from unittest import TestCase as PythonTestCase
import unittest.main
import os.path
import fionautil.layer
shp = os.path.join(os.path.dirname(__file__), 'fixtures/testing.shp')
geojson = os.path.join(os.path.dirname(__file__), 'fixtures/testing.geojson')
if __name__ == '__main__':
unittest.main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
770,
2393,
318,
636,
286,
277,
295,
2306,
346,
13,
198,
2,
2638,
1378,
12567,
13,
785,
14,
11147,
48624,
14... | 2.64 | 225 |
#!/usr/bin/env python
# ScraperWiki Limited
# Ian Hopkinson, 2013-06-20
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
"""
Analysis and visualisation library for pdftables
"""
import pdftables as pt
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from tree import Leaf, LeafList
FilterOptions = ['LTPage','LTTextBoxHorizontal','LTFigure','LTLine','LTRect','LTImage','LTTextLineHorizontal','LTCurve', 'LTChar', 'LTAnon']
Colours = ['black' ,'green' ,'black' ,'red' ,'red' ,'black' ,'blue' ,'red' , 'red' , 'White']
ColourTable = dict(zip(FilterOptions, Colours))
LEFT = 0
TOP = 3
RIGHT = 2
BOTTOM = 1
def plotpage(d):
#def plotpage(BoxList,xhistleft,xhistright,yhisttop,yhistbottom,xComb,yComb):
# global ColourTable
"""This is from pdftables"""
#columnProjectionThreshold = threshold_above(columnProjection,columnThreshold)
#colDispHeight = max(columnProjection.values())*0.8
#columnProj = dict(zip(columnProjectionThreshold, [colDispHeight]*len(columnProjectionThreshold)))
"""End display only code"""
"""This is from pdftables"""
#rowProjectionThreshold = threshold_above(rowProjection,rowThreshold)
# rowDispHeight = max(rowProjection.values())*0.8
# rowProj = dict(zip(rowProjectionThreshold, [rowDispHeight]*len(rowProjectionThreshold)))
"""End display only code"""
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.axis('equal')
for boxstruct in d.box_list:
box = boxstruct.bbox
thiscolour = ColourTable[boxstruct.classname]
ax1.plot([box[0],box[2],box[2],box[0],box[0]],[box[1],box[1],box[3],box[3],box[1]],color = thiscolour )
# fig.suptitle(title, fontsize=15)
divider = make_axes_locatable(ax1)
#plt.setp(ax1.get_yticklabels(),visible=False)
ax1.yaxis.set_label_position("right")
if d.top_plot:
axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=ax1)
axHistx.plot(map(float,d.top_plot.keys()),map(float,d.top_plot.values()), color = 'red')
if d.left_plot:
axHisty = divider.append_axes("left", 1.2, pad=0.1, sharey=ax1)
axHisty.plot(map(float,d.left_plot.values()),map(float,d.left_plot.keys()), color = 'red')
if d.y_comb:
miny = min(d.y_comb)
maxy = max(d.y_comb)
for x in d.x_comb:
ax1.plot([x,x],[miny,maxy],color = "black")
axHistx.scatter(x,0,color = "black")
if d.x_comb:
minx = min(d.x_comb)
maxx = max(d.x_comb)
for y in d.y_comb:
ax1.plot([minx,maxx],[y,y],color = "black")
axHisty.scatter(1,y,color = "black")
plt.draw()
plt.show(block = False)
return fig, ax1
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
1446,
38545,
32603,
15302,
198,
2,
12930,
21183,
261,
11,
2211,
12,
3312,
12,
1238,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
6738,
11593,
37443,
... | 2.221617 | 1,286 |
import rhinoscriptsyntax as rs
| [
11748,
9529,
11996,
6519,
1837,
41641,
355,
44608,
201,
198,
220,
220,
220,
220,
201,
198,
220,
220,
220,
220
] | 2.1 | 20 |
# !/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020/6/22 上午9:58
# @Author: Jtyoui@qq.com
# @Notes : 身份证检查
from .idcard import IdCard
__version__ = '2020.6.22'
__author__ = 'Jtyoui'
__description__ = '身份证实体抽取,身份证补全,身份证检测等功能。'
__email__ = 'jtyoui@qq.com'
__names__ = 'pyUnit_idCard'
__url__ = 'https://github.com/PyUnit/pyunit-idCard'
| [
2,
5145,
14,
14629,
14,
8800,
14,
29412,
18,
13,
22,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2488,
7575,
220,
1058,
12131,
14,
21,
14,
1828,
220,
41468,
39355,
230,
24,
25,
3365,
198,
2,
2488,
13... | 1.6 | 215 |
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2018 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pickle
from decimal import Decimal
import numpy as np
from petastorm.reader_impl.pyarrow_serializer import PyArrowSerializer
def test_serializer_is_pickable():
"""Pickle/depickle the serializer to make sure it can be passed
as a parameter cross process boundaries when using futures"""
s = PyArrowSerializer()
deserialized_s = pickle.loads(pickle.dumps(s))
expected = [{'a': np.asarray([1, 2], dtype=np.uint64)}]
actual = deserialized_s.deserialize(deserialized_s.serialize(expected))
np.testing.assert_array_equal(actual[0]['a'], expected[0]['a'])
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
220,
15069,
357,
66,
8,
2177,
12,
7908,
12024,
21852,
11,
3457,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
... | 3.186352 | 381 |
# Copyright 2017 Arie Bregman
#
# 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 the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
def setup_db_create_subparser(subparsers, parent_parser):
"""Adds db create sub-parser"""
db_create_parser = subparsers.add_parser(
"create", parents=[parent_parser])
db_create_parser.add_argument(
'--all', '-a', action='store_true')
def setup_db_drop_subparser(subparsers, parent_parser):
"""Adds db drop sub-parser"""
db_drop_parser = subparsers.add_parser(
"drop", parents=[parent_parser])
db_drop_parser.add_argument(
'--all', '-a', action='store_true')
def create():
"""Returns argparse parser."""
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--debug', required=False, action='store_true',
dest="debug", help='Turn DEBUG on')
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="parser")
setup_db_create_subparser(subparsers, parent_parser)
setup_db_drop_subparser(subparsers, parent_parser)
return parser
| [
2,
15069,
2177,
317,
5034,
347,
2301,
805,
198,
2,
198,
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
198,
2,
220,
220,
220,
407,
779,
428,
2393,
2845,
287,
11846,... | 2.813149 | 578 |
import pytest
from nerwhal.integrated_recognizers.phone_number_recognizer import PhoneNumberRecognizer
@pytest.fixture(scope="module")
# DIN 5008
# Microsoft's canonical format
# E.123
# Others
# Non-standard
# US style
# Not phone numbers
| [
11748,
12972,
9288,
198,
198,
6738,
17156,
1929,
282,
13,
18908,
4111,
62,
26243,
11341,
13,
4862,
62,
17618,
62,
26243,
7509,
1330,
14484,
15057,
6690,
2360,
7509,
628,
198,
31,
9078,
9288,
13,
69,
9602,
7,
29982,
2625,
21412,
4943,
... | 2.917526 | 97 |
# OBSS SAHI Tool
# Code written by Kadir Nar, 2022.
import unittest
from sahi.utils.cv import read_image
from sahi.utils.torchvision import TorchVisionTestConstants
MODEL_DEVICE = "cpu"
CONFIDENCE_THRESHOLD = 0.5
IMAGE_SIZE = 320
if __name__ == "__main__":
unittest.main()
| [
2,
440,
4462,
50,
14719,
25374,
16984,
198,
2,
6127,
3194,
416,
31996,
343,
13596,
11,
33160,
13,
628,
198,
11748,
555,
715,
395,
198,
198,
6738,
473,
5303,
13,
26791,
13,
33967,
1330,
1100,
62,
9060,
198,
6738,
473,
5303,
13,
26791... | 2.605505 | 109 |
from django.urls import path, include
from tool import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('candidates', views.CandidatesViewSet)
router.register('jobs', views.JobViewSet)
urlpatterns = [
path('', include(router.urls)),
path('recruiters/', views.RecruiterView.as_view(), name="recruiters"),
path('skills/<int:pk>/', views.SkillsView.as_view(), name="skills"),
path('skills/active/', views.ActiveSkills.as_view(), name="active skills"),
path('interviews/', views.InterviewView.as_view(), name="interviews"),
] | [
6738,
42625,
14208,
13,
6371,
82,
1330,
3108,
11,
2291,
198,
6738,
2891,
1330,
5009,
198,
198,
6738,
1334,
62,
30604,
13,
472,
1010,
1330,
15161,
49,
39605,
198,
198,
472,
353,
796,
15161,
49,
39605,
3419,
198,
472,
353,
13,
30238,
... | 2.911765 | 204 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); 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 the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import mxnet as mx
import numpy as _np
from mxnet.test_utils import same, rand_shape_nd
from mxnet.runtime import Features
from common import with_seed
_features = Features()
@with_seed()
if __name__ == '__main__':
import nose
nose.runmodule()
| [
2,
49962,
284,
262,
24843,
10442,
5693,
357,
1921,
37,
8,
739,
530,
198,
2,
393,
517,
18920,
5964,
11704,
13,
220,
4091,
262,
28536,
2393,
198,
2,
9387,
351,
428,
670,
329,
3224,
1321,
198,
2,
5115,
6634,
9238,
13,
220,
383,
7054,... | 3.695035 | 282 |
import pexpect
import timeout_decorator
#csk = CreateSSLKey()
#csk.start()
| [
11748,
613,
87,
806,
198,
11748,
26827,
62,
12501,
273,
1352,
628,
628,
628,
198,
2,
6359,
74,
796,
13610,
31127,
9218,
3419,
198,
2,
6359,
74,
13,
9688,
3419,
628,
220,
220,
220,
220,
220,
220,
220,
220,
628
] | 2.3 | 40 |
import argparse
import torch
import torch.utils.data.distributed
import pprint
from utils.MyDataset import MyDataLoader, MyDataset
from config import args as default_args, project_root_path
import numpy as np
import pandas as pd
import os
from models import (
SOTA_goal_model,
AlbertForMultipleChoice,
RobertaForMultipleChoiceWithLM,
RobertaForMultipleChoice
)
from model_modify import (
get_features,
create_datasets_with_kbert,
train_and_finetune, test
)
from utils.semevalUtils import (
get_all_features_from_task_1,
get_all_features_from_task_2,
)
from transformers import (
RobertaTokenizer,
RobertaConfig,
)
if __name__ == '__main__':
build_parse()
# print all config
print(project_root_path)
pprint.pprint(default_args)
# prepare for tokenizer and model
tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
config = RobertaConfig.from_pretrained('roberta-large')
config.hidden_dropout_prob = 0.2
config.attention_probs_dropout_prob = 0.2
if default_args['with_kegat']:
# create a model with kegat (or and lm)
model = SOTA_goal_model(default_args)
elif default_args['with_lm']:
model = RobertaForMultipleChoiceWithLM.from_pretrained(
'pre_weights/roberta-large_model.bin', config=config)
else:
model = RobertaForMultipleChoice.from_pretrained(
'pre_weights/roberta-large_model.bin', config=config)
train_data = test_data = optimizer = None
print('with_LM: ', 'Yes' if default_args['with_lm'] else 'No')
print('with_KEGAT: ', 'Yes' if default_args['with_kegat'] else 'No')
print('with_KEmb: ', 'Yes' if default_args['with_kemb'] else 'No')
train_features, dev_features, test_features = [], [], []
if default_args['subtask_id'] == 'A':
train_features = get_all_features_from_task_1(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Training Data/subtaskA_data_all.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Training Data/subtaskA_answers_all.csv',
tokenizer, default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
dev_features = get_all_features_from_task_1(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Dev Data/subtaskA_dev_data.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Dev Data/subtaskA_gold_answers.csv',
tokenizer, default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
test_features = get_all_features_from_task_1(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Testing Data/subtaskA_test_data.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Testing Data/subtaskA_gold_answers.csv',
tokenizer, default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
elif default_args['subtask_id'] == 'B':
train_features = get_all_features_from_task_2(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Training Data/subtaskB_data_all.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Training Data/subtaskB_answers_all.csv',
tokenizer,
default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
dev_features = get_all_features_from_task_2(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Dev Data/subtaskB_dev_data.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Dev Data/subtaskB_gold_answers.csv',
tokenizer, default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
test_features = get_all_features_from_task_2(
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Testing Data/subtaskB_test_data.csv',
'SemEval2020-Task4-Commonsense-Validation-and-Explanation-master/Testing Data/subtaskB_gold_answers.csv',
tokenizer, default_args['max_seq_length'],
with_gnn=default_args['with_kegat'],
with_k_bert=default_args['with_kemb'])
train_dataset = create_datasets_with_kbert(train_features, shuffle=True)
dev_dataset = create_datasets_with_kbert(dev_features, shuffle=False)
test_dataset = create_datasets_with_kbert(test_features, shuffle=False)
if default_args['use_multi_gpu']:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
train_data = torch.utils.data.DataLoader(train_dataset, batch_size=default_args['batch_size'],
sampler=train_sampler)
dev_sampler = torch.utils.data.distributed.DistributedSampler(dev_dataset)
dev_data = torch.utils.data.DataLoader(dev_dataset, batch_size=default_args['test_batch_size'],
sampler=dev_sampler)
test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset)
test_data = torch.utils.data.DataLoader(test_dataset, batch_size=default_args['test_batch_size'],
sampler=test_sampler)
else:
train_data = MyDataLoader(train_dataset, batch_size=default_args['batch_size'])
dev_data = MyDataLoader(dev_dataset, batch_size=default_args['test_batch_size'])
test_data = MyDataLoader(test_dataset, batch_size=default_args['test_batch_size'])
train_data = list(train_data)
dev_data = list(dev_data)
test_data = list(test_data)
print('train_data len: ', len(train_data))
print('dev_data len: ', len(dev_data))
print('test_data len: ', len(test_data))
dev_acc, (train_pred_opt, dev_pred_opt) = train_and_finetune(model, train_data, dev_data, default_args)
_, test_acc, _ = test(model, test_data, default_args)
print('Dev acc: ', dev_acc)
print('Test acc: ', test_acc)
| [
11748,
1822,
29572,
198,
11748,
28034,
198,
11748,
28034,
13,
26791,
13,
7890,
13,
17080,
6169,
198,
11748,
279,
4798,
198,
6738,
3384,
4487,
13,
3666,
27354,
292,
316,
1330,
2011,
6601,
17401,
11,
2011,
27354,
292,
316,
198,
6738,
4566... | 2.286232 | 2,760 |
# python 3.6
import logging
import os
import random
import time
from threading import Thread
from paho.mqtt import client as mqtt_client
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
mqtt_broker = os.environ['MQTT_BROKER']
mqtt_topic = os.environ['MQTT_TOPIC']
value_type = os.environ['VALUE_TYPE']
invalid_value_occurrence = int(os.environ['INVALID_VALUE_OCCURRENCE'])
mqtt_port = int(os.environ['MQTT_BROKER_PORT'])
pod_name = os.environ['POD_NAME']
input_file = os.environ['INPUT_FILE']
# topic = "mqtt/temperature"
# username = 'emqx'
# password = 'public'
# Cast values from string to integer
if value_type == 'integer':
start_value = int(os.environ['START_VALUE'])
end_value = int(os.environ['END_VALUE'])
invalid_value = int(os.environ['INVALID_VALUE'])
# Cast values from string to flaot
if value_type == 'float':
start_value = float(os.environ['START_VALUE'])
end_value = float(os.environ['END_VALUE'])
invalid_value = float(os.environ['INVALID_VALUE'])
# Connect to MQTT broker
# Generate integer values based on given range of values
# Generate float values based on given range of values
# Publish message to MQTT topic
# using readlines()
# while(True):
# get_generated_data()
if __name__ == '__main__':
run()
| [
2,
21015,
513,
13,
21,
198,
11748,
18931,
198,
11748,
28686,
198,
11748,
4738,
198,
11748,
640,
198,
6738,
4704,
278,
1330,
14122,
198,
198,
6738,
279,
17108,
13,
76,
80,
926,
1330,
5456,
355,
285,
80,
926,
62,
16366,
198,
198,
6404... | 2.654618 | 498 |
import pytest
from .app import oso, Organization, Repository, User
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
@pytest.fixture
| [
11748,
12972,
9288,
198,
198,
6738,
764,
1324,
1330,
267,
568,
11,
12275,
11,
1432,
13264,
11,
11787,
628,
198,
31,
9078,
9288,
13,
69,
9602,
628,
198,
31,
9078,
9288,
13,
69,
9602,
628,
198,
31,
9078,
9288,
13,
69,
9602,
628,
198... | 2.527473 | 91 |
import csv
buffer = []
for i in range(0,100):
buffer.append(i)
print("Writing buffer to buffer.csv now...")
data_logger_csv(buffer,"buffer.csv") | [
11748,
269,
21370,
198,
197,
197,
198,
22252,
796,
17635,
198,
1640,
1312,
287,
2837,
7,
15,
11,
3064,
2599,
198,
197,
22252,
13,
33295,
7,
72,
8,
198,
197,
198,
4798,
7203,
33874,
11876,
284,
11876,
13,
40664,
783,
9313,
8,
198,
... | 2.678571 | 56 |
# -*- coding: utf-8
"""Unit tests for the mstranslate event plugin."""
# pylint: disable=missing-docstring,too-few-public-methods
from twisted.internet.defer import inlineCallbacks
from twisted.trial.unittest import TestCase
from ...test.helpers import CommandTestMixin
from . import Default
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
198,
37811,
26453,
5254,
329,
262,
285,
2536,
504,
17660,
1785,
13877,
526,
15931,
198,
2,
279,
2645,
600,
25,
15560,
28,
45688,
12,
15390,
8841,
11,
18820,
12,
32146,
12,
11377,
12,
243... | 3.3 | 90 |
from abc import ABCMeta, abstractmethod
class DefaultExperimentProvider(object):
"""
Abstract base class for objects that provide the ID of an MLflow Experiment based on the
current client context. For example, when the MLflow client is running in a Databricks Job,
a provider is used to obtain the ID of the MLflow Experiment associated with the Job.
Usually the experiment_id is set explicitly by the user, but if the experiment is not set,
MLflow computes a default experiment id based on different contexts.
When an experiment is created via the fluent ``mlflow.start_run`` method, MLflow iterates
through the registered ``DefaultExperimentProvider``s until it finds one whose
``in_context()`` method returns ``True``; MLflow then calls the provider's
``get_experiment_id()`` method and uses the resulting experiment ID for Tracking operations.
"""
__metaclass__ = ABCMeta
@abstractmethod
def in_context(self):
"""
Determine if the MLflow client is running in a context where this provider can
identify an associated MLflow Experiment ID.
:return: ``True`` if the MLflow client is running in a context where the provider
can identify an associated MLflow Experiment ID. ``False`` otherwise.
"""
pass
@abstractmethod
def get_experiment_id(self):
"""
Provide the MLflow Experiment ID for the current MLflow client context.
Assumes that ``in_context()`` is ``True``.
:return: The ID of the MLflow Experiment associated with the current context.
"""
pass
| [
6738,
450,
66,
1330,
9738,
48526,
11,
12531,
24396,
628,
198,
4871,
15161,
20468,
3681,
29495,
7,
15252,
2599,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
27741,
2779,
1398,
329,
5563,
326,
2148,
262,
4522,
286,
281,
10373,
11125,
... | 3.251984 | 504 |
# -*- coding: utf-8 -*-
"""Provide a traversal root that looks up registered resources."""
__all__ = [
'EngineRoot',
]
import logging
logger = logging.getLogger(__name__)
import zope.interface as zi
import pyramid_basemodel as bm
from pyramid_basemodel import container
from pyramid_basemodel import tree
from . import auth
from . import util
QUERY_SPEC = {
'property_name': 'id',
'validator': util.id_validator,
}
class EngineRoot(tree.BaseContentRoot):
"""Lookup registered resources by tablename and id, wrapping the result
in an ACL wrapper that restricts access by api key.
"""
@property
def add_engine_resource(config, resource_cls, container_iface, query_spec=None):
"""Populate the ``registry.engine_resource_mapping``."""
# Compose.
if not query_spec:
query_spec = QUERY_SPEC
# Unpack.
registry = config.registry
tablename = resource_cls.class_slug
# Create the container class.
class_name = '{0}Container'.format(resource_cls.__name__)
container_cls = type(class_name, (ResourceContainer,), {})
zi.classImplements(container_cls, container_iface)
# Make sure we have a mapping.
if not hasattr(registry, 'engine_resource_mapping'):
registry.engine_resource_mapping = {}
# Prepare a function to actually populate the mapping.
# Register the configuration action with a discriminator so that we
# don't register the same class twice.
discriminator = ('engine.traverse', tablename,)
# Make it introspectable.
intr = config.introspectable(category_name='engine resources',
discriminator=discriminator,
title='An engine resource',
type_name=None)
intr['value'] = resource_cls, container_iface
config.action(discriminator, register, introspectables=(intr,))
def includeme(config, add_resource=None):
"""Provide the ``config.add_engine_resource`` directive."""
config.add_directive('add_engine_resource', add_engine_resource)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
15946,
485,
257,
33038,
282,
6808,
326,
3073,
510,
6823,
4133,
526,
15931,
198,
198,
834,
439,
834,
796,
685,
198,
220,
220,
220,
705,
13798,
30016,
3256,
... | 2.713168 | 767 |
#!/usr/bin/env python
import urllib2
httpCode = http_code()
uri = ["https://www.digitalocean.com/community/tutorials/how-to-import-and-export-databases-in-mysql-or-mariadb/lkajsklas/90/laksjkjas/alsjhkahskjas/asjhakjshkjas/aslkjakslj"]
for i in uri:
httpCode.error(i)
print '\n'
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
628,
198,
11748,
2956,
297,
571,
17,
628,
198,
220,
220,
220,
220,
220,
198,
198,
4023,
10669,
796,
2638,
62,
8189,
3419,
198,
198,
9900,
796,
14631,
5450,
1378,
2503,
13,
34725,
78,
5829... | 2.097222 | 144 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
response = urllib2.urlopen("https://www.python.org/")
html = response.read()
# print out the HTML response
print(html)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
2956,
297,
571,
17,
198,
198,
26209,
796,
2956,
297,
571,
17,
13,
6371,
9654,
7203,
5450,
1378,
2503,
13,... | 2.577465 | 71 |
# LOCAL IMPORTS
from Connection.connection import Connection # connecting to SQL database
"""
It's meant to be run only before using the project for the first time (or at least for the first time in
a certain database (make sure you changed parameters in Connection/'con_parameters.py' file.
"""
with Connection() as con:
cursor=con.cursor()
cursor.execute('DROP TABLE IF EXISTS decks CASCADE')
"""
Deck table: created for storing names and options of existing decks (for example to know if called deck has to be created)
and managing daily new cards limits.
"""
cursor.execute("""CREATE TABLE decks(
name TEXT,
new_limit INT,
limit_left INT,
last_date DATE,
EASE_FACTOR FLOAT,
EASY_BONUS FLOAT,
REVIEW_INTERVAL INT,
EASY_REVIEW_INTERVAL INT,
EARLY_LEARNING INT,
NEW_STEPS FLOAT[],
LAPSE_STEPS FLOAT[],
PRIMARY KEY (name))
""")
| [
2,
37347,
1847,
30023,
33002,
201,
198,
6738,
26923,
13,
38659,
1330,
26923,
1303,
14320,
284,
16363,
6831,
201,
198,
37811,
201,
198,
220,
220,
220,
632,
338,
4001,
284,
307,
1057,
691,
878,
1262,
262,
1628,
329,
262,
717,
640,
357,
... | 2.618529 | 367 |
import sys
sys.path.insert(0, "/home/puneeth/Projects/GAN/GenerativeAdversarialNetworks/utilities")
import mini_batch_gradient_descent as gd
import plotting_functions as pf
import numpy as np
X = np.transpose(np.random.random_sample(10) * 2.0)
obj = [X]
mle = gd.GradientDescentOptimizer(X, 10**-4, 1)
theta = mle.optimize()
# print(np.random.normal(theta[0], theta[1], 5))
# print("gaussian", gaussian(X, [5, 5]))
pred = np.transpose(gaussian(X, theta))
obj.append(pred)
print(theta)
print("theta")
pf.plot_graphs(1, 5, 10, obj) | [
11748,
25064,
198,
17597,
13,
6978,
13,
28463,
7,
15,
11,
12813,
11195,
14,
79,
1726,
2788,
14,
16775,
82,
14,
45028,
14,
8645,
876,
2782,
690,
36098,
7934,
5225,
14,
315,
2410,
4943,
198,
11748,
9927,
62,
43501,
62,
49607,
62,
8906... | 2.437788 | 217 |
# Import Setup and Dependancies
import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
########## Database Setup ###########
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# Reflect an existing database and tables
Base = automap_base()
# Reflect the tables
Base.prepare(engine, reflect=True)
# Save reference to the tables
Measurement = Base.classes.measurement
Station = Base.classes.station
# Create an app
app = Flask(__name__)
########## Flask Routes ##########
@app.route("/")
def welcome():
"""List all available api routes."""
return (
f"Welcome to Hawaii Climate Home Page<br/> "
f"Available Routes:<br/>"
f"<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/min_max_avg/<start><br/>"
f"/api/v1.0/min_max_avg/<start>/<end><br/>"
f"<br/>"
)
@app.route("/api/v1.0/precipitation")
@app.route("/api/v1.0/stations")
@app.route("/api/v1.0/tobs")
@app.route("/api/v1.0/min_max_avg/<start>")
def temp_range_start(start):
"""TMIN, TAVG, and TMAX per date starting from a starting date.
Args:
start (string): A date string in the format %Y-%m-%d
Returns:
TMIN, TAVE, and TMAX
"""
start_date = dt.datetime.strptime(start, '%Y-%m-%d')
# Create our session (link) from Python to the Database
session = Session(engine)
results = session.query(Measurement.date,\
func.min(Measurement.tobs), \
func.avg(Measurement.tobs), \
func.max(Measurement.tobs)).\
filter(Measurement.date>=start).\
group_by(Measurement.date).all()
# Create a list to hold results
start_list = []
for start_date, min, avg, max in results:
dict_a = {}
dict_a["Date"] = start_date
dict_a["TMIN"] = min
dict_a["TAVG"] = avg
dict_a["TMAX"] = max
start_list.append(dict_a)
session.close()
# jsonify the result
return jsonify(start_list)
@app.route("/api/v1.0/min_max_avg/<start>/<end>")
#run the app
if __name__ == "__main__":
app.run(debug=True)
## EOF ## | [
2,
17267,
31122,
290,
37947,
16183,
198,
11748,
299,
32152,
355,
45941,
220,
198,
11748,
4818,
8079,
355,
288,
83,
198,
11748,
44161,
282,
26599,
220,
198,
6738,
44161,
282,
26599,
13,
2302,
13,
2306,
296,
499,
1330,
3557,
499,
62,
86... | 2.18552 | 1,105 |
from lib.database import db_connect | [
6738,
9195,
13,
48806,
1330,
20613,
62,
8443
] | 4.375 | 8 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from werkzeug.wrappers import Response
import frappe
import json
__version__ = '0.0.1'
@frappe.whitelist(allow_guest=True)
# api url: http://<site_name>/api/method/vsf_erpnext.cart.update?token=&cartId=
@frappe.whitelist(allow_guest=True)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
6738,
266,
9587,
2736,
1018,
13,
29988,
11799,
1330,
18261,
198,
11748,
5306,
27768,
198,
11748,
33918,
19... | 2.456 | 125 |
import pytest
from gaea.config import CONFIG
from hermes.constants import SENDER, TO
from hermes.email_engine import EmailEngine
@pytest.fixture(scope="module", autouse=True)
| [
11748,
12972,
9288,
198,
198,
6738,
308,
44705,
13,
11250,
1330,
25626,
198,
198,
6738,
607,
6880,
13,
9979,
1187,
1330,
311,
10619,
1137,
11,
5390,
198,
6738,
607,
6880,
13,
12888,
62,
18392,
1330,
9570,
13798,
628,
198,
31,
9078,
92... | 3.155172 | 58 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pprint
import math
import urllib.request, urllib.error, urllib.parse
import sys
import traceback
import re
import time
import urllib.parse
import types
import json
import string
import copy
import threading
import localconstants
import util
import random
import datetime
import http.cookies
"""
Handles incoming queries for the search UI.
"""
TRACE = False
if not localconstants.isDev:
TRACE = False
allProjects = ('Tika', 'Solr', 'Lucene', 'Infrastructure')
DO_PROX_HIGHLIGHT = False
MAX_INT = (1 << 31) - 1
jiraSpec = JIRASpec()
jiraSpec.doAutoComplete = True
jiraSpec.showGridOrList = False
jiraSpec.indexName = 'jira'
jiraSpec.itemLabel = 'issues'
if False:
# (field, userLabel, facetField)
jiraSpec.groups = (
('assignee', 'assignee', 'assignee'),
('facetPriority', 'priority', 'facetPriority'),
)
# (id, userLabel, field, reverse):
jiraSpec.sorts = (
('relevanceRecency', 'relevance + recency', 'blendRecencyRelevance', True),
('relevance', 'pure relevance', None, False),
('oldest', 'oldest', 'created', False),
('commentCount', 'most comments', 'commentCount', True),
('voteCount', 'most votes', 'voteCount', True),
('watchCount', 'most watches', 'watchCount', True),
('newest', 'newest', 'created', True),
('priority', 'priority', 'priority', False),
#('notRecentlyUpdated', 'not recently updated', 'updated', False),
('recentlyUpdated', 'recently updated', 'updated', True),
#('keyNum', 'issue number', 'keyNum', False),
)
jiraSpec.retrieveFields = (
'key',
'updated',
'created',
{'field': 'allUsers', 'highlight': 'whole'},
'status',
'author',
'commentID',
'commentCount',
'voteCount',
'watchCount',
'commitURL',
{'field': 'summary', 'highlight': 'whole'},
{'field': 'description', 'highlight': 'snippets'},
{'field': 'body', 'highlight': 'snippets'},
)
jiraSpec.highlighter = {
'class': 'PostingsHighlighter',
'passageScorer.b': 0.75,
'maxPassages': 3,
'maxLength': 1000000}
# (userLabel, fieldName, isHierarchy, sort, doMorePopup)
jiraSpec.facetFields = (
('Status', 'status', False, None, False),
('Project', 'project', False, None, False),
('Updated', 'updated', False, None, False),
('Updated ago', 'updatedAgo', False, None, False),
('User', 'allUsers', False, None, True),
('Committed by', 'committedBy', False, None, True),
('Last comment user', 'lastContributor', False, None, True),
('Fix version', 'fixVersions', True, '-int', True),
('Committed paths', 'committedPaths', True, None, False),
('Component', 'facetComponents', True, None, True),
('Type', 'issueType', False, None, True),
('Priority', 'facetPriority', False, None, False),
('Labels', 'labels', False, None, True),
('Attachment?', 'attachments', False, None, False),
('Commits?', 'hasCommits', False, None, False),
('Has votes?', 'hasVotes', True, None, False),
('Reporter', 'reporter', False, None, True),
('Assignee', 'assignee', False, None, True),
('Resolution', 'resolution', False, None, False),
#('Created', 'facetCreated', True, None, False),
)
jiraSpec.textQueryFields = ['summary', 'description']
# nocommit can we do key descending as number...?
jiraSpec.browseOnlyDefaultSort = 'recentlyUpdated'
jiraSpec.finish()
escape = util.escape
chars = string.ascii_lowercase + string.digits
reIssue = re.compile('([A-Z]+-\d+)')
CHECKMARK = '✓'
reNumber = re.compile(r'^[\-0-9]+\.[0-9]+')
opticalZoomSortOrder = [
'1x',
'1x-3x',
'3x-6x',
'6x-10x',
'10x-20x',
'Over 20x',
]
weightSortOrder = [
'0 - .25',
'.25 - .50',
'.50 - .75',
'.75 - 1.0',
'Over 1.0',
]
| [
2,
49962,
284,
262,
24843,
10442,
5693,
357,
1921,
37,
8,
739,
530,
393,
517,
198,
2,
18920,
5964,
11704,
13,
220,
4091,
262,
28536,
2393,
9387,
351,
198,
2,
428,
670,
329,
3224,
1321,
5115,
6634,
9238,
13,
198,
2,
383,
7054,
37,
... | 2.911493 | 1,514 |
import networkx as nx
from models.case import Case
from models.legal_knowledge_graph import LegalKnowledgeGraph
from helpers import *
from custom import *
G = init_graph("{}/all_citations.txt".format(DATADIR)).fetch_subgraph(
query_type='case')
print(len(G.nodes()))
print(len(G.edges()))
print(G.in_degree_distribution())
print(G.out_degree_distribution())
print('Average clustering coeff', nx.average_clustering(G))
print('Average in_degree', G.average_in_degree())
print('Average out_degree', G.average_out_degree())
# print_landmark_cases(nx.in_degree_centrality, G, 'In-Degree centrality')
# print_landmark_cases(nx.eigenvector_centrality, G, 'Eigen-vector centrality')
# print_landmark_cases(nx.katz_centrality, G, 'Katz centrality')
# print_landmark_cases(nx.closeness_centrality, G, 'Closeness centrality')
# print_landmark_cases(nx.pagerank, G, 'Pagerank')
# print_landmark_cases(custom_centrality, G, 'Custom centrality')
# print_common_cases()
# plot_distribution(fetch_log_scale(G.in_degree_distribution()), 'In-Degree', 'graph_plots/power_law_distribution/in_degree.png', fontSize=2, dpi=500, plot_type="scatter")
# plot_distribution(fetch_log_scale(G.out_degree_distribution()), 'Out-Degree', 'graph_plots/power_law_distribution/out_degree.png', fontSize=2, dpi=500, plot_type="scatter")
# unfrozen_graph = nx.Graph(G)
# unfrozen_graph.remove_edges_from(unfrozen_graph.selfloop_edges())
# core_number = nx.core_number(unfrozen_graph)
# core_number_sorted = sorted(core_number.items(), key=lambda kv: kv[1], reverse=True)[:50]
# for case_id, value in core_number_sorted:
# print(case_id, "\t", CASE_ID_TO_NAME_MAPPING[case_id], "\t", value)
# print("k_core")
# k_core = nx.k_core(unfrozen_graph)
# # k_core_sorted = sorted(k_core.items(), key=lambda kv: kv[1], reverse=True)[:50]
# for _ in k_core.nodes():
# print(_, "\t", CASE_ID_TO_NAME_MAPPING[_])
# print("k_shell")
# k_shell = nx.k_shell(unfrozen_graph)
# for _ in k_shell.nodes():
# print(_, "\t", CASE_ID_TO_NAME_MAPPING[_])
# print("k_crust")
# k_crust = nx.k_crust(unfrozen_graph)
# for _ in k_crust.nodes():
# print(_, "\t", CASE_ID_TO_NAME_MAPPING[_])
# print("k_corona")
# k_corona = nx.k_corona(unfrozen_graph, k=10)
# for _ in k_corona.nodes():
# print(_, "\t", CASE_ID_TO_NAME_MAPPING[_])
# rich_club_coefficient = nx.rich_club_coefficient(unfrozen_graph, normalized=False)
# rich_club_sorted = sorted(rich_club_coefficient.items(), key=lambda kv: kv[1], reverse=True)
# min_degree = 116
# rich_club = list()
# for case_id in unfrozen_graph:
# if len(unfrozen_graph[case_id]) > min_degree:
# rich_club.append(case_id)
# print([CASE_ID_TO_NAME_MAPPING[case_id] for case_id in rich_club])
# k_clique_communities = list(nx.algorithms.community.k_clique_communities(unfrozen_graph, k=8))
# # print(k_clique_communities)
# for k_clique in k_clique_communities:
# print("\n")
# for case_id in k_clique:
# if case_id in CASE_ID_TO_FILE_MAPPING:
# path = CASE_ID_TO_FILE_MAPPING[case_id]
# subjects = find_subjects_for_case(path)
# print(case_id,"\t", CASE_ID_TO_NAME_MAPPING[case_id],"\t", ", ".join(subjects))
| [
11748,
3127,
87,
355,
299,
87,
198,
198,
6738,
4981,
13,
7442,
1330,
8913,
198,
6738,
4981,
13,
18011,
62,
45066,
62,
34960,
1330,
16027,
23812,
2965,
37065,
198,
6738,
49385,
1330,
1635,
198,
6738,
2183,
1330,
1635,
198,
198,
38,
796... | 2.421296 | 1,296 |
import torch
import torch.nn as nn
import nlpblock as nb
"""
Example to run
model = RNN_Attention(emb_dim=50,
n_class=2, n_hidden=128, n_layers=1, bidirectional=False, linearTransform=True)
output, attention = model(
torch.rand([3, 5, 50]) # [batch, seq_len, emb_dim]
)
print(output.shape, attention.shape)
"""
| [
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
299,
34431,
9967,
355,
299,
65,
198,
198,
37811,
198,
16281,
284,
1057,
198,
19849,
796,
371,
6144,
62,
8086,
1463,
7,
24419,
62,
27740,
28,
1120,
11,
198,
220,
2... | 2.358621 | 145 |
import os
from celery.result import AsyncResult
from fastapi import APIRouter, Depends, Request
from fastapi.responses import FileResponse, JSONResponse
from services.calculators import TophatterCalculator
from services.database.user_database import UserDatabase
from services.mapper import TophatterMapper
from services.pandi import Pandi
from services.schemas import User
from tasks import fetch_tophatter_orders
services = UserDatabase()
tophatter = APIRouter(prefix="/tophatter")
@tophatter.get("/create_task")
@tophatter.get("/tasks")
@tophatter.get("/tasks/clean")
@tophatter.get("/revenue")
@tophatter.get("/download")
| [
11748,
28686,
198,
198,
6738,
18725,
1924,
13,
20274,
1330,
1081,
13361,
23004,
198,
6738,
3049,
15042,
1330,
3486,
4663,
39605,
11,
2129,
2412,
11,
19390,
198,
6738,
3049,
15042,
13,
16733,
274,
1330,
9220,
31077,
11,
19449,
31077,
198,
... | 3.255102 | 196 |
nome = input('Digite o nome completo da pessoa: ').strip() # usa-se o método strip para retirar os espaços vazios antes e depois da frase
print('O nome completo da pessoa em maiúsculo é: ', nome.upper()) # usa o método 'upper' para transformar toda a frase em maiúscula
print('O nome completo da pessoa em minúsculo é: ', nome.lower()) # usa o método 'lower' para transformar toda a frase em minúscula
print('O nome possui {} letras'.format(len(nome) - nome.count(' '))) # usa o método 'len' para contar todas as letras e, utilizando
# o ' - nome.count(' '), o programa vai retirar todos os espaços
# vazios no meio da frase.
divide = nome.split() # pega a frase e usa o método 'split' para separar a frase em listas
print('Seu primeiro nome é {} e ele tem {} letras'.format(divide[0], len(divide[0]))) # ao utilizar 'divide[0], estou pegando a primeira
# posição da lista feita no split e mostrando a palvra
# que está contida nesta posição. Já o comando
# 'len(divide[0], vai mostrar quantas letras tem na
# palavra contida na posição 0. | [
77,
462,
796,
5128,
10786,
19511,
578,
267,
299,
462,
1224,
1462,
12379,
279,
408,
12162,
25,
705,
737,
36311,
3419,
1303,
514,
64,
12,
325,
267,
285,
25125,
24313,
10283,
31215,
1005,
343,
283,
28686,
1658,
8957,
16175,
418,
410,
103... | 1.751163 | 860 |
import abc
import os
import zipfile
from typing import List
from justmltools.config.abstract_data_path_config import AbstractDataPathConfig
from justmltools.config.local_data_path_config import LocalDataPathConfig
| [
11748,
450,
66,
198,
11748,
28686,
198,
11748,
19974,
7753,
198,
6738,
19720,
1330,
7343,
198,
198,
6738,
655,
76,
2528,
10141,
13,
11250,
13,
397,
8709,
62,
7890,
62,
6978,
62,
11250,
1330,
27741,
6601,
15235,
16934,
198,
6738,
655,
... | 3.6 | 60 |
# -*- coding: utf-8 -*-
'''Command line interface module for intro_py-intro.
'''
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os, sys, argparse, json
import logging, inspect
from future.builtins import (ascii, filter, hex, map, oct, zip, str, open, dict)
from intro_py import util, intro
from intro_py.intro import person
from intro_py.practice import classic, sequenceops as seqops
__all__ = ['main']
# -- run w/out compile --
# python script.py [arg1 argN]
#
# -- run REPL, import script, & run --
# python
# >>> from . import script.py
# >>> script.main([arg1, argN])
#
# -- help/info tools in REPL --
# help(), quit(), help(<object>), help([modules|keywords|symbols|topics])
#
# -- show module/type info --
# ex: pydoc list OR python> help(list)
logging.basicConfig(level = logging.DEBUG)
MODULE_LOGGER = logging.getLogger(__name__)
def main(argv=None):
'''Main entry.
Args:
argv (list): list of arguments
Returns:
int: A return code
Demonstrates Python syntax
'''
rsrc_path = os.environ.get('RSRC_PATH')
logjson_str = util.read_resource('logging.json', rsrc_path=rsrc_path)
log_cfg = deserialize_str(logjson_str, fmt='json')
util.config_logging('info', 'cfg', log_cfg)
opts_hash = parse_cmdopts(argv)
util.config_logging(opts_hash.log_lvl, opts_hash.log_opt, log_cfg)
MODULE_LOGGER.info('main()')
cfg_blank = {'hostname':'???', 'domain':'???', 'file1':{'path':'???',
'ext':'txt'}, 'user1':{'name':'???', 'age': -1}}
cfg_ini = dict(cfg_blank.items())
cfg_ini.update(util.ini_to_dict(util.read_resource('prac.conf',
rsrc_path=rsrc_path)).items())
#cfg_json = dict(cfg_blank.items())
#cfg_json.update(deserialize_str(util.read_resource('prac.json',
# rsrc_path=rsrc_path)).items())
#cfg_yaml = dict(cfg_blank.items())
#cfg_yaml.update(deserialize_str(util.read_resource('prac.yaml',
# rsrc_path=rsrc_path), fmt='yaml').items())
#cfg_toml = dict(cfg_blank.items())
#cfg_toml.update(deserialize_str(util.read_resource('prac.toml',
# rsrc_path=rsrc_path), fmt='toml').items())
tup_arr = [
(cfg_ini, cfg_ini['domain'], cfg_ini['user1']['name'])
#, (cfg_json, cfg_json['domain'], cfg_json['user1']['name'])
#, (cfg_yaml, cfg_yaml['domain'], cfg_yaml['user1']['name'])
#, (cfg_toml, cfg_toml['domain'], cfg_toml['user1']['name'])
]
for (cfg, domain, user1Name) in tup_arr:
print('\nconfig: {0}'.format(cfg))
print('domain: {0}'.format(domain))
print('user1Name: {0}'.format(user1Name))
print('')
run_intro(vars(opts_hash), rsrc_path=rsrc_path)
logging.shutdown()
return 0
if '__main__' == __name__:
sys.exit(main(sys.argv[1:]))
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
7061,
6,
21575,
1627,
7071,
8265,
329,
18951,
62,
9078,
12,
600,
305,
13,
198,
198,
7061,
6,
198,
198,
6738,
11593,
37443,
834,
1330,
357,
48546,
62,
11748,
11,
7297,
... | 2.31379 | 1,211 |
from sklearn.model_selection import BaseCrossValidator
import numpy as np
import pandas as pd
# We dont implement this one
if __name__ == "__main__":
versions = np.reshape(np.array( [1,1,1,2,2,2,2,3,3,3] ), (10,1))
data = np.reshape(np.zeros(100), (10, 10))
X = pd.DataFrame( np.append( versions, data, axis = 1 ), columns = ["version"] + [i for i in range(10)] )
y = pd.DataFrame(np.zeros(10))
for i, (train_index, test_index) in enumerate(VersionDropout(10, 0.2).split(X, y)):
print( "iter: %d\ntraining: %s\ntesting: %s\n" % (i, train_index, test_index) ) | [
6738,
1341,
35720,
13,
19849,
62,
49283,
1330,
7308,
21544,
47139,
1352,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
19798,
292,
355,
279,
67,
198,
220,
220,
220,
220,
198,
220,
220,
220,
1303,
775,
17666,
3494,
428,
530,
628,
198... | 2.301527 | 262 |
# format, name, destination register, source 1, data of source 1, IB in which data expected, source 2, data of source 2, IB in which data expected, immediate data, T_NT,stall
#A=[format,name,rd,rs1,rs2,imm]
#A=[format,name,rd,rs1,rs2,imm]
# format, name, destination register, source 1, data of source 1, IB in which data expected, source 2, data of source 2, IB in which data expected, immediate data, T_NT,stall
RZ=0
RM=0
RF_write=0
R=[RZ,RM,RF_write]
#A=["R","srl","101","1101010101","4","imm"]
#A=raw_input()
#A=A.split(" ")
#get_alu_opt(A)
'''
if A[0]=="R":
B=[A[1],A[2],A[3],A[4]]
R=R_format(B)
print(R)
if A[0]=="I":
B=[A[1],A[2],A[3],A[5]]
I=I_format(B)
print(I)
if A[0]=="S":
B=[A[1],A[3],A[4],A[5]]
S=S_format(B)
print(S)
if A[0]=="SB":
B=[A[1],A[3],A[4],A[5]]
SB=SB_format(B)
print(SB)
if A[0]=="U":
B=[A[1],A[2],A[5]]
U=U_format(B)
print(U)
if A[0]=="UJ":
B=[A[1],A[2],A[5]]
UJ=UJ_format(B)
print(UJ)
'''
| [
198,
2,
5794,
11,
1438,
11,
10965,
7881,
11,
2723,
352,
11,
1366,
286,
2723,
352,
11,
34782,
287,
543,
1366,
2938,
11,
2723,
362,
11,
1366,
286,
2723,
362,
11,
34782,
287,
543,
1366,
2938,
11,
7103,
1366,
11,
309,
62,
11251,
11,
... | 1.923077 | 494 |
from datetime import datetime
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.generic import ListView, View
from django.views.generic.edit import CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from backend.forum.models import Category, Section, Topic, Message
from backend.forum.forms import MessageForm, CreateTopicForm
class Sections(ListView):
"""Вывод разделов форума"""
model = Category
template_name = "forum/section.html"
class TopicsList(ListView):
"""Вывод топиков раздела"""
template_name = "forum/topics-list.html"
class TopicDetail(ListView):
"""Вывод темы"""
context_object_name = 'messages'
template_name = 'forum/topic-detail.html'
paginate_by = 10
class EditTopic(LoginRequiredMixin, UpdateView):
"""Редактирование темы"""
model = Topic
form_class = MessageForm
template_name = 'forum/update_message.html'
class EditMessages(LoginRequiredMixin, UpdateView):
"""Редактирование коментариев"""
model = Message
form_class = MessageForm
template_name = 'forum/update_message.html'
class MessageCreate(LoginRequiredMixin, View):
"""Отправка комментария на форуме"""
# class MessageCreate(LoginRequiredMixin, CreateView):
# """Создание темы на форуме"""
# model = Message
# form_class = MessageForm
# template_name = 'forum/topic-detail.html'
#
# def form_valid(self, form):
# form.instance.user = self.request.user
# form.instance.topic_id = self.kwargs.get("pk")
# form.save()
# return super().form_valid(form)
class CreateTopic(LoginRequiredMixin, CreateView):
"""Создание темы на форуме"""
model = Topic
form_class = CreateTopicForm
template_name = 'forum/create-topic.html'
| [
6738,
4818,
8079,
1330,
4818,
8079,
198,
198,
6738,
42625,
14208,
13,
19509,
23779,
1330,
18941,
198,
6738,
42625,
14208,
13,
6371,
82,
1330,
9575,
62,
75,
12582,
198,
198,
6738,
42625,
14208,
13,
33571,
13,
41357,
1330,
7343,
7680,
11,... | 2.384314 | 765 |
import urllib
import urllib.request
try:
site = urllib.request.urlopen('http://pudim.com.br/')
except urllib.error.URLError:
print('O site ardeu')
else:
print('Pode ir tá tudo nice')
| [
11748,
2956,
297,
571,
198,
11748,
2956,
297,
571,
13,
25927,
198,
28311,
25,
198,
220,
220,
220,
2524,
796,
2956,
297,
571,
13,
25927,
13,
6371,
9654,
10786,
4023,
1378,
79,
463,
320,
13,
785,
13,
1671,
14,
11537,
198,
16341,
2956,... | 2.321429 | 84 |
import six
DefinitionsHost = {'discriminator': 'name',
'required': ['name',
'region_id',
'ip_address',
'device_type'],
'type': 'object',
'properties': {
'active': {'type': 'boolean'},
'note': {'type': 'string'},
'ip_address': {'type': 'string'},
'name': {'type': 'string'},
'id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'parent_id': {'type': 'integer',
'description': 'Parent Id of this host'},
'device_type': {'type': 'string',
'description': 'Type of host'},
'labels': {'type': 'array',
'items': 'string',
'description': 'User defined labels'},
'data': {'type': 'allOf',
'description': 'User defined information'},
'region_id': {'type': 'integer'}}}
DefinitionsHostId = {'discriminator': 'name',
'type': 'object',
'properties': {
'active': {'type': 'boolean'},
'note': {'type': 'string'},
'ip_address': {'type': 'string'},
'name': {'type': 'string'},
'id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'project_id': {'type': 'string'},
'labels': {'type': 'array',
'items': 'string',
'description': 'User defined labels'},
'data': {'type': 'allOf',
'description': 'User defined information'},
'region_id': {'type': 'integer'}}}
DefinitionsCell = {'discriminator': 'name',
'required': ['name',
'region_id',
],
'type': 'object',
'properties': {
'note': {'type': 'string'},
'name': {'type': 'string'},
'region_id': {'type': 'integer'},
'data': {'type': 'allOf',
'description': 'User defined information'},
'id': {'type': 'integer',
'description': 'Unique ID of the cell'}}}
DefinitionsCellId = {'discriminator': 'name',
'type': 'object',
'properties': {
'note': {'type': 'string'},
'project_id': {'type': 'string',
'description': 'UUID of the project'},
'name': {'type': 'string'},
'region_id': {'type': 'integer'},
'data': {'type': 'allOf',
'description': 'User defined information'},
'id': {'type': 'integer',
'description': 'Unique ID of the cell'}}}
DefinitionsData = {'type': 'object',
'properties': {'key': {'type': 'string'},
'value': {'type': 'object'}}}
DefinitionsLabel = {'type': 'object',
'properties': {'labels': {
'type': 'array',
'items': {'type': 'string'}}}}
DefinitionsError = {'type': 'object',
'properties': {'fields': {'type': 'string'},
'message': {'type': 'string'},
'code': {'type': 'integer',
'format': 'int32'}
}}
DefinitionsRegion = {'discriminator': 'name',
'required': ['name'],
'type': 'object',
'properties': {
'note': {
'type': 'string',
'description': 'Region Note'},
'name': {
'type': 'string',
'description': 'Region Name.'},
'cells': {
'items': DefinitionsCell,
'type': 'array',
'description': 'List of cells in this region'},
'data': {
'type': 'allOf',
'description': 'User defined information'},
'id': {
'type': 'integer',
'description': 'Unique ID for the region.'}}}
DefinitionsRegionId = {'discriminator': 'name',
'type': 'object',
'properties': {
'note': {
'type': 'string',
'description': 'Region Note'},
'name': {
'type': 'string',
'description': 'Region Name.'},
'project_id': {
'type': 'string',
'description': 'UUID of the project'},
'cells': {
'items': DefinitionsCell,
'type': 'array',
'description': 'List of cells in this region'},
'data': {
'type': 'allOf',
'description': 'User defined information'},
'id': {
'type': 'integer',
'description': 'Unique ID for the region.'}}}
DefinitionUser = {'discriminator': 'name',
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'api_key': {'type': 'string'},
'username': {'type': 'string'},
'is_admin': {'type': 'boolean'},
'project_id': {'type': 'string'},
'roles': {'type': 'allOf'}}}
DefinitionProject = {'discriminator': 'name',
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'name': {'type': 'string'}}}
DefinitionNetwork = {'discriminator': 'name',
'required': ['name',
'cidr',
'gateway',
'netmask'],
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'region_id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'name': {'type': 'string'},
'cidr': {'type': 'string'},
'gateway': {'type': 'string'},
'netmask': {'type': 'string'},
'data': {'type': 'allOf'},
"ip_block_type": {'type': 'string'},
"nss": {'type': 'string'}}}
DefinitionNetworkId = {'discriminator': 'name',
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'project_id': {'type': 'string'},
'region_id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'name': {'type': 'string'},
'cidr': {'type': 'string'},
'gateway': {'type': 'string'},
'netmask': {'type': 'string'},
'data': {'type': 'allOf'},
"ip_block_type": {'type': 'string'},
"nss": {'type': 'string'}}}
DefinitionNetInterface = {'discriminator': 'name',
'required': ['name',
'device_id',
'interface_type'],
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'name': {'type': 'string'},
'device_id': {'type': 'integer',
'default': None},
'network_id': {'type': 'integer',
'default': None},
'interface_type': {'type': 'string'},
'project_id': {'type': 'string'},
'vlan_id': {'type': 'integer'},
'vlan': {'type': 'string'},
'port': {'type': 'integer'},
'duplex': {'type': 'string'},
'speed': {'type': 'integer'},
'link': {'type': 'string'},
'cdp': {'type': 'string'},
'data': {'type': 'allOf'},
'security': {'type': 'string'}}}
DefinitionNetInterfaceId = {'discriminator': 'name',
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'name': {'type': 'string'},
'device_id': {'type': 'integer'},
'project_id': {'type': 'string'},
'network_id': {'type': 'integer'},
'interface_type': {'type': 'string'},
'vlan_id': {'type': 'integer'},
'vlan': {'type': 'string'},
'port': {'type': 'string'},
'duplex': {'type': 'string'},
'speed': {'type': 'integer'},
'link': {'type': 'string'},
'cdp': {'type': 'string'},
'data': {'type': 'allOf'},
'security': {'type': 'string'}}}
DefinitionNetDevice = {'discriminator': 'hostname',
'required': ['hostname',
'region_id',
'device_type',
'ip_address'],
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'region_id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'parent_id': {'type': 'integer'},
'ip_address': {'type': 'string'},
'device_type': {'type': 'string'},
'hostname': {'type': 'string'},
'access_secret_id': {'type': 'integer'},
'model_name': {'type': 'string'},
'os_version': {'type': 'string'},
'vlans': {'type': 'string'},
'data': {'type': 'allOf',
'description': 'User defined variables'},
'interface_id': {'type': 'integer'},
'network_id': {'type': 'integer'}}}
DefinitionNetDeviceId = {'discriminator': 'hostname',
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'project_id': {'type': 'string'},
'region_id': {'type': 'integer'},
'cell_id': {'type': 'integer'},
'parent_id': {'type': 'integer'},
'ip_address': {'type': 'string'},
'device_type': {'type': 'string'},
'hostname': {'type': 'string'},
'access_secret_id': {'type': 'integer'},
'model_name': {'type': 'string'},
'os_version': {'type': 'string'},
'vlans': {'type': 'string'},
'interface_id': {'type': 'integer'},
'data': {'type': 'allOf',
'description': 'User defined variables'},
'network_id': {'type': 'integer'}}}
validators = {
('ansible_inventory', 'GET'): {
'args': {'required': ['region_id'],
'properties': {
'region_id': {
'default': None,
'type': 'string',
'description': 'Region to generate inventory for'},
'cell_id': {
'default': None,
'type': 'string',
'description': 'Cell id to generate inventory for'}}}
},
('hosts_id_data', 'PUT'): {'json': DefinitionsData},
('hosts_labels', 'PUT'): {'json': DefinitionsLabel},
('hosts_id', 'GET'): {
'args': {'required': [],
'properties': {
'resolved-values': {
'default': True,
'type': 'boolean'}}}
},
('hosts_id', 'PUT'): {'json': DefinitionsHost},
('regions', 'GET'): {
'args': {'required': [],
'properties': {
'name': {
'default': None,
'type': 'string',
'description': 'name of the region to get'},
'id': {
'default': None,
'type': 'integer',
'description': 'ID of the region to get'}}}
},
('regions', 'POST'): {'json': DefinitionsRegion},
('regions_id_data', 'PUT'): {'json': DefinitionsData},
('hosts', 'POST'): {'json': DefinitionsHost},
('hosts', 'GET'): {
'args': {'required': ['region_id'],
'properties': {
'name': {
'default': None,
'type': 'string',
'description': 'name of the hosts to get'},
'region_id': {
'default': None,
'type': 'integer',
'description': 'ID of the region to get hosts'},
'cell_id': {
'default': None,
'type': 'integer',
'description': 'ID of the cell to get hosts'},
'device_type': {
'default': None,
'type': 'string',
'description': 'Type of host to get'},
'limit': {
'minimum': 1,
'description': 'number of hosts to return',
'default': 1000,
'type': 'integer',
'maximum': 10000},
'ip': {
'default': None,
'type': 'string',
'description': 'ip_address of the hosts to get'},
'id': {
'default': None,
'type': 'integer',
'description': 'ID of host to get'}}
}},
('cells_id', 'PUT'): {'json': DefinitionsCell},
('cells', 'POST'): {'json': DefinitionsCell},
('cells', 'GET'): {
'args': {'required': ['region_id'],
'properties': {
'region_id': {
'default': None,
'type': 'string',
'description': 'name of the region to get cells for'},
'id': {
'default': None,
'type': 'integer',
'description': 'id of the cell to get'
},
'name': {
'default': None,
'type': 'string',
'description': 'name of the cell to get'}}
}},
('regions_id', 'PUT'): {'json': DefinitionsRegion},
('cells_id_data', 'PUT'): {'json': DefinitionsData},
('projects', 'GET'): {
'args': {'required': [],
'properties': {
'id': {
'default': None,
'type': 'integer',
'description': 'id of the project to get'
},
'name': {
'default': None,
'type': 'string',
'description': 'name of the project to get'}}
}},
('projects', 'POST'): {'json': DefinitionProject},
('users', 'GET'): {
'args': {'required': [],
'properties': {
'id': {
'default': None,
'type': 'integer',
'description': 'id of the user to get'
},
'name': {
'default': None,
'type': 'string',
'description': 'name of the user to get'}}
}},
('users', 'POST'): {'json': DefinitionUser},
('netdevices', 'GET'): {
'args': {'required': [],
'properties': {
'id': {
'default': None,
'type': 'integer',
'description': 'id of the net device to get'
},
'ip': {
'default': None,
'type': 'string',
'description': 'IP of the device to get'},
'region_id': {
'default': None,
'type': 'string',
'description': 'region id of the device to get'},
'name': {
'default': None,
'type': 'string',
'description': 'name of the device to get'},
'device_type': {
'default': None,
'type': 'string',
'description': 'type of the device to get'},
'cell_id': {
'default': None,
'type': 'string',
'description': 'cell id of the device to get'}}
}},
('netdevices_id', 'GET'): {
'args': {'required': [],
'properties': {
'resolved-values': {
'default': True,
'type': 'boolean'}}}},
('netdevices', 'POST'): {'json': DefinitionNetDevice},
('netdevices_labels', 'PUT'): {'json': DefinitionsLabel},
('net_interfaces', 'GET'): {
'args': {'required': ['device_id'],
'properties': {
'id': {
'default': None,
'type': 'integer',
'description': 'id of the net interface to get'
},
'device_id': {
'default': None,
'type': 'integer',
'description': 'device id of the interface to get'},
'ip': {
'default': None,
'type': 'string',
'description': 'IP of the interface to get'},
'interface_type': {
'default': None,
'type': 'string',
'description': 'Type of the interface to get'}}
}},
('net_interfaces', 'POST'): {'json': DefinitionNetInterface},
('networks', 'GET'): {
'args': {'required': [],
'properties': {
'id': {
'default': None,
'type': 'integer',
'description': 'id of the network to get'
},
'network_type': {
'default': None,
'type': 'string',
'description': 'type of the network to get'},
'name': {
'default': None,
'type': 'string',
'description': 'name of the network to get'},
'region_id': {
'default': None,
'type': 'string',
'description': 'region id of the network to get'},
'cell_id': {
'default': None,
'type': 'string',
'description': 'cell idof the network to get'}}
}},
('networks', 'POST'): {'json': DefinitionNetwork},
}
filters = {
('hosts_id_data', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_id_data', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionsHostId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_id', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_id', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_labels', 'GET'):
{200: {'headers': None, 'schema': DefinitionsLabel},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts_labels', 'PUT'):
{200: {'headers': None, 'schema': DefinitionsLabel},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts', 'POST'):
{200: {'headers': None, 'schema': DefinitionsHost},
400: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('hosts', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionsHost, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionsCellId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells_id', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells_id', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells_id_data', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells_id_data', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells', 'POST'):
{200: {'headers': None, 'schema': DefinitionsCell},
400: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('cells', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionsCell, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions', 'POST'):
{200: {'headers': None, 'schema': DefinitionsRegion},
400: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionsRegion, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions_id_data', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions_id_data', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionsRegionId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions_id', 'PUT'):
{200: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('regions_id', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('projects', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionProject, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('projects', 'POST'):
{200: {'headers': None, 'schema': DefinitionProject},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('users', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionUser, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('users', 'POST'):
{200: {'headers': None, 'schema': DefinitionUser},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('users_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionUser},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('users_id', 'DELETE'):
{204: {'headers': None, 'schema': None},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('netdevices', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionNetDeviceId, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('netdevices_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionNetDeviceId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('netdevices_labels', 'GET'):
{200: {'headers': None, 'schema': DefinitionsLabel},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('netdevices_labels', 'PUT'):
{200: {'headers': None, 'schema': DefinitionsLabel},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('networks', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionNetwork, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('networks_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionNetworkId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('net_interfaces', 'GET'):
{200: {'headers': None,
'schema': {'items': DefinitionNetInterface, 'type': 'array'}},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
('net_interfaces_id', 'GET'):
{200: {'headers': None, 'schema': DefinitionNetInterfaceId},
400: {'headers': None, 'schema': None},
404: {'headers': None, 'schema': None},
405: {'headers': None, 'schema': None}},
}
scopes = {
('hosts_id_data', 'PUT'): [],
('hosts_id_data', 'DELETE'): [],
('hosts_id', 'PUT'): [],
('hosts_id', 'DELETE'): [],
('regions', 'GET'): [],
('regions_id_data', 'PUT'): [],
('regions_id_data', 'DELETE'): [],
('hosts', 'POST'): [],
('hosts', 'GET'): [],
('cells_id', 'PUT'): [],
('cells_id', 'DELETE'): [],
('cells', 'POST'): [],
('cells', 'GET'): [],
('regions_id', 'PUT'): [],
('cells_id_data', 'PUT'): [],
('cells_id_data', 'DELETE'): [],
('projects', 'GET'): [],
('projects_id', 'GET'): [],
('projects_id', 'DELETE'): [],
('projects', 'POST'): [],
('users', 'GET'): [],
('users', 'POST'): [],
('users_id', 'GET'): [],
}
security = Security()
| [
11748,
2237,
628,
198,
7469,
50101,
17932,
796,
1391,
6,
15410,
3036,
20900,
10354,
705,
3672,
3256,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
705,
35827,
10354,
37250,
3672,
3256,
... | 1.687093 | 18,881 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './modules/dialogPassword.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
try:
_encoding = QtGui.QApplication.UnicodeUTF8
except AttributeError:
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
5178,
7822,
7560,
422,
3555,
334,
72,
2393,
705,
19571,
18170,
14,
38969,
519,
35215,
13,
9019,
6,
198,
2,
198,
2,
15622,
416,
25,
9485,
48,
83,
19,
12454,
... | 2.715278 | 144 |
#!/bin/python
import listify_circuits
listify_circuits.optimize_circuits(16, 'forward') | [
2,
48443,
8800,
14,
29412,
198,
198,
11748,
1351,
1958,
62,
21170,
15379,
198,
4868,
1958,
62,
21170,
15379,
13,
40085,
1096,
62,
21170,
15379,
7,
1433,
11,
705,
11813,
11537
] | 2.83871 | 31 |
'''
Quick setup script.
'''
import os
os.system('brew install ffmpeg')
os.system('brew install youtube-dl')
modules=['ffmpy','pandas','soundfile','pafy', 'tqdm']
pip_install(modules)
| [
7061,
6,
198,
21063,
9058,
4226,
13,
198,
7061,
6,
198,
11748,
28686,
220,
198,
198,
418,
13,
10057,
10786,
11269,
2721,
31246,
43913,
11537,
198,
418,
13,
10057,
10786,
11269,
2721,
35116,
12,
25404,
11537,
198,
18170,
28,
17816,
487,
... | 2.681159 | 69 |
import os
import sys
import torch
import logging
import pickle
import datetime
from tqdm import tqdm
sys.path.append('datapreprocess')
sys.path.append('module')
from datafunc import make_dataloader, test_data_for_predict, build_processed_data, make_validloader
from model import LinearNet, RnnNet, RnnAttentionNet
| [
11748,
28686,
198,
11748,
25064,
198,
198,
11748,
28034,
198,
11748,
18931,
198,
11748,
2298,
293,
198,
11748,
4818,
8079,
198,
6738,
256,
80,
36020,
1330,
256,
80,
36020,
198,
198,
17597,
13,
6978,
13,
33295,
10786,
19608,
499,
260,
14... | 3.148515 | 101 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-04-23 11:10
from __future__ import unicode_literals
from django.db import migrations, models
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2980,
515,
416,
37770,
352,
13,
24,
319,
1584,
12,
3023,
12,
1954,
1367,
25,
940,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
198,
6738,
... | 2.781818 | 55 |
from setuptools import find_packages, setup
setup(
name='pbase',
version='0.0.1',
author='Peng Shi',
author_email='peng_shi@outlook.com',
description='framework for deep learning applications',
url='https://github.com/Impavidity/pbase',
license='MIT',
install_requires=[
],
packages=find_packages(),
)
| [
6738,
900,
37623,
10141,
1330,
1064,
62,
43789,
11,
9058,
628,
198,
40406,
7,
198,
220,
220,
220,
1438,
11639,
79,
8692,
3256,
198,
220,
220,
220,
2196,
11639,
15,
13,
15,
13,
16,
3256,
198,
220,
220,
220,
1772,
11639,
47,
1516,
1... | 2.695313 | 128 |
"""Add Action table.
Revision ID: 4cbe8e432c6b
Revises: 7b08cf35abd9
Create Date: 2018-07-27 20:05:30.976453
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4cbe8e432c6b'
down_revision = '7b08cf35abd9'
branch_labels = None
depends_on = None
| [
37811,
4550,
7561,
3084,
13,
198,
198,
18009,
1166,
4522,
25,
604,
66,
1350,
23,
68,
45331,
66,
21,
65,
198,
18009,
2696,
25,
767,
65,
2919,
12993,
2327,
397,
67,
24,
198,
16447,
7536,
25,
2864,
12,
2998,
12,
1983,
1160,
25,
2713,... | 2.385827 | 127 |
"""
MIT License
Copyright (c) 2021 Jedy Matt Tabasco
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 limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import abc
from typing import NamedTuple
import sqlalchemy
from sqlalchemy.orm import ColumnProperty
from sqlalchemy.orm import object_mapper
from sqlalchemy.orm.relationships import RelationshipProperty
from sqlalchemy.sql import schema
from . import class_registry, validator, errors, util
class AbstractSeeder(abc.ABC):
"""
AbstractSeeder class
"""
@property
@abc.abstractmethod
def instances(self):
"""
Seeded instances
"""
@abc.abstractmethod
def seed(self, entities):
"""
Seed data
"""
@abc.abstractmethod
def _pre_seed(self, *args, **kwargs):
"""
Pre-seeding phase
"""
@abc.abstractmethod
def _seed(self, *args, **kwargs):
"""
Seeding phase
"""
@abc.abstractmethod
def _seed_children(self, *args, **kwargs):
"""
Seed children
"""
@abc.abstractmethod
def _setup_instance(self, *args, **kwargs):
"""
Setup instance
"""
class Seeder(AbstractSeeder):
"""
Basic Seeder class
"""
__model_key = validator.Key.model()
__data_key = validator.Key.data()
@property
# def instantiate_class(self, class_, kwargs: dict, key: validator.Key):
# filtered_kwargs = {
# k: v
# for k, v in kwargs.items()
# if not k.startswith("!")
# and not isinstance(getattr(class_, k), RelationshipProperty)
# }
#
# if key is validator.Key.data():
# return class_(**filtered_kwargs)
#
# if key is validator.Key.filter() and self.session is not None:
# return self.session.query(class_).filter_by(**filtered_kwargs).one()
class HybridSeeder(AbstractSeeder):
"""
HybridSeeder class. Accepts 'filter' key for referencing children.
"""
__model_key = validator.Key.model()
__source_keys = [validator.Key.data(), validator.Key.filter()]
@property
| [
37811,
198,
36393,
13789,
198,
198,
15269,
357,
66,
8,
33448,
449,
4716,
4705,
16904,
292,
1073,
198,
198,
5990,
3411,
318,
29376,
7520,
11,
1479,
286,
3877,
11,
284,
597,
1048,
16727,
257,
4866,
198,
1659,
428,
3788,
290,
3917,
10314... | 2.698344 | 1,147 |
import dependency_injector.containers as containers
import dependency_injector.providers as providers
import strongr.core
from strongr.schedulerdomain.model.scalingdrivers.nullscaler import NullScaler
from strongr.schedulerdomain.model.scalingdrivers.simplescaler import SimpleScaler
from strongr.schedulerdomain.model.scalingdrivers.surfhpccloudscaler import SurfHpcScaler
class ScalingDriver(containers.DeclarativeContainer):
"""IoC container of service providers."""
_scalingdrivers = providers.Object({
'simplescaler': SimpleScaler,
'nullscaler': NullScaler,
'surfsarahpccloud': SurfHpcScaler
})
scaling_driver = providers.Singleton(_scalingdrivers()[strongr.core.Core.config().schedulerdomain.scalingdriver.lower()], config=dict(strongr.core.Core.config().schedulerdomain.as_dict()[strongr.core.Core.config().schedulerdomain.scalingdriver]) if strongr.core.Core.config().schedulerdomain.scalingdriver in strongr.core.Core.config().schedulerdomain.as_dict().keys() else {})
| [
11748,
20203,
62,
259,
752,
273,
13,
3642,
50221,
355,
16472,
198,
11748,
20203,
62,
259,
752,
273,
13,
15234,
4157,
355,
9549,
198,
198,
11748,
1913,
81,
13,
7295,
198,
198,
6738,
1913,
81,
13,
1416,
704,
18173,
27830,
13,
19849,
1... | 3.047619 | 336 |
from rest_framework import serializers
from .models import Post, Location, Tag,Photo
# class PostSerializer(serializers.Serializer):
# id = serializers.IntegerField(read_only = True)
# title = serializers.CharField(max_length = 255)
# detail = serializers.CharField(max_length = 2047)
# def create(self,validated_data):
# """create a Post from json"""
# return Post.objects.create(**validated_data)
# def update(self, instance, validated_data):
# """Update the data by json"""
# instance
# class CategorySerializer(serializers.ModelSerializer):
# class Meta:
# model = Category
# fields = ('id','name')
| [
6738,
1334,
62,
30604,
1330,
11389,
11341,
198,
6738,
764,
27530,
1330,
2947,
11,
13397,
11,
17467,
11,
6191,
628,
198,
198,
2,
1398,
2947,
32634,
7509,
7,
46911,
11341,
13,
32634,
7509,
2599,
198,
2,
220,
220,
220,
220,
4686,
796,
... | 2.637405 | 262 |
import copy
import logging
import math
from datetime import datetime
import numpy as np
import quaternion
import cv2
from TelemetryParsing import readTelemetryCsv
from visnav.algo import tools
from visnav.algo.tools import Pose
from visnav.algo.model import Camera
from visnav.algo.odo.base import Measure
from visnav.algo.odo.visgps_odo import VisualGPSNav
from visnav.algo.odometry import VisualOdometry
from visnav.missions.base import Mission
| [
11748,
4866,
201,
198,
11748,
18931,
201,
198,
11748,
10688,
201,
198,
6738,
4818,
8079,
1330,
4818,
8079,
201,
198,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
11748,
627,
9205,
295,
201,
198,
11748,
269,
85,
17,
201,
198,
201... | 2.968553 | 159 |
from typing import List
from collections import Counter
| [
6738,
19720,
1330,
7343,
198,
6738,
17268,
1330,
15034,
628
] | 5.7 | 10 |
import io
from setuptools import setup, find_packages
setup(
name='smart-crawler',
version='0.2',
url='https://github.com/limdongjin/smart-crawler',
license='MIT',
author='limdongjin',
author_email='geniuslim27@gmail.com',
description='Smart Crawler',
packages=find_packages(),
long_description=long_description(),
zip_safe=False,
install_requires=['Click',
'beautifulsoup4',
'requests',
'selenium',
'lxml',
'pyfunctional',
'boto3',
'awscli'],
entry_points={
'console_scripts': ['smart-crawler = cli.main:main']
}
)
| [
11748,
33245,
198,
6738,
900,
37623,
10141,
1330,
9058,
11,
1064,
62,
43789,
628,
198,
198,
40406,
7,
198,
220,
220,
220,
1438,
11639,
27004,
12,
66,
39464,
3256,
198,
220,
220,
220,
2196,
11639,
15,
13,
17,
3256,
198,
220,
220,
220... | 1.934037 | 379 |
import matplotlib.pyplot as plt
import numpy as np
tray = np.genfromtxt("solar.dat",delimiter=",")
a = tray[:,0]
b = tray[:,1]
c = tray[:,2]
d = tray[:,3]
fig = plt.figure(figsize = (20,20))
plt.subplot(2,3,1)
plt.scatter(a,b)
plt.title('Grafica a vs b ')
plt.xlabel('a' )
plt.ylabel('b' )
plt.subplot(2,3,2)
plt.scatter(a,c)
plt.title('Grafica a vs c ')
plt.xlabel('a' )
plt.ylabel('c' )
plt.subplot(2,3,3)
plt.scatter(a,d)
plt.title('Grafica a vs d ' )
plt.xlabel('a' )
plt.ylabel('d' )
plt.subplot(2,3,4)
plt.scatter(b,c)
plt.title('Grafica b vs c ' )
plt.xlabel('b' )
plt.ylabel('c' )
plt.subplot(2,3,5)
plt.scatter(b,d)
plt.title('Grafica b vs d ' )
plt.xlabel('b' )
plt.ylabel('d' )
plt.subplot(2,3,6)
plt.scatter(c,d)
plt.title('Grafica c vs d ' )
plt.xlabel('c' )
plt.ylabel('d' )
plt.savefig("solar.pdf",dpi = 400)
| [
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
299,
32152,
355,
45941,
198,
198,
2213,
323,
796,
45941,
13,
5235,
6738,
14116,
7203,
82,
6192,
13,
19608,
1600,
12381,
320,
2676,
28,
2430,
8,
628,
198,
64,
796,
... | 1.809935 | 463 |
import json
import pycountry
import requests
import sys
import os
from bs4 import BeautifulSoup
from collections import namedtuple
directory = os.path.dirname(os.path.abspath(__file__))
def create_players(table):
"""
Loop through given table and create Player objects with the following
attributes:
- Nationality
- Name
- Kills
- Assists
- Deaths
- KAST
- K/D Diff
- ADR
- FK Diff
- Rating
"""
team_data = []
Player = namedtuple("Player", ["name", "k", "a", "d", "kast", "kddiff",
"adr", "fkdiff", "rating", "nationality"])
for i, row in enumerate(table.select("tr")):
if i > 0:
player_row = row.find_all("td")
nationality = player_row[0].find("img").get("alt", "")
player = [player.text for player in player_row]
player.append(nationality)
team_data.append(Player(*player))
return team_data
def team_logo(team, white=True):
"""
Takes a team's name and (hopefully) converts it to a team's logo on Reddit.
"""
if white and teams[team.name]["white"]:
return "[](#{}w-logo)".format(team.logo.lower())
else:
return "[](#{}-logo)".format(team.logo.lower())
def print_scoreboard(team):
"""
Prints the scoreboard of the given team.
"""
for player in team.players:
try:
nat = pycountry.countries.get(name=player.nationality).alpha_2
except Exception as error:
nat = country_converter(player.nationality)
print("|[](#lang-{}) {}|{}|{}|{}|{}|".format(nat.lower(),
player.name, player.k.split()[0], player.a.split()[0],
player.d.split()[0], player.rating))
def print_overview(team_1, team_2):
"""
Prints the overview of the match.
"""
print("|Team|T|CT|Total|\n|:--|:--:|:--:|:--:|")
print("|{}|{}|{}|{}|".format(team_logo(team_1, False),
team_1.match.first, team_1.match.second,
team_1.match.first + team_1.match.second))
print("|{}|{}|{}|{}|".format(team_logo(team_2, False),
team_2.match.first, team_2.match.second,
team_2.match.first + team_2.match.second))
print("\n \n")
def create_post(team_1, team_2):
"""
Prints the entire scoreboard for both teams.
"""
print("\n \n\n###MAP: \n\n \n")
print_overview(team_1, team_2)
print("|{} **{}**|**K**|**A**|**D**|**Rating**|".format(
team_logo(team_1), team_1.initials))
print("|:--|:--:|:--:|:--:|:--:|")
print_scoreboard(team_1)
print("|{} **{}**|".format(team_logo(team_2, False), team_2.initials))
print_scoreboard(team_2)
def count_rounds(half):
"""
Counts how many rounds were won in the half.
"""
rounds = 0
for img in half.find_all("img"):
if not "emptyHistory.svg" in img["src"]:
rounds += 1
return rounds
def team_match(team=1):
"""
Creates a Match object with how many matches the team won in each half.
"""
Match = namedtuple("Match", ["first", "second"])
halves = soup.find_all("div", {"class" : "round-history-half"})
if team == 1:
first_half = halves[0]
second_half = halves[1]
else:
first_half = halves[2]
second_half = halves[3]
Match.first = count_rounds(first_half)
Match.second = count_rounds(second_half)
return Match
def get_response(url):
"""
Gets the response from the given URL with some error checking.
"""
if not "www.hltv.org" in url:
sys.exit("Please enter a URL from www.hltv.org.")
try:
response = requests.get(url)
return response
except Exception as error:
sys.exit("{}: Please enter a valid URL.".format(repr(error)))
if __name__ == '__main__':
url = str(sys.argv[1])
response = get_response(url)
with open("{}/csgo.json".format(directory), "r") as json_data:
teams = json.load(json_data)
soup = BeautifulSoup(response.text, "lxml")
Team = namedtuple("Team", ["name", "players", "match", "logo", "initials"])
stats_tables = soup.find_all("table", {"class" : "stats-table"})
table_1 = stats_tables[0]
table_2 = stats_tables[1]
name_1 = table_1.find_all("th")[0].text
name_2 = table_2.find_all("th")[0].text
team_1 = Team(name_1, create_players(table_1), team_match(1),
teams[name_1]["logo"], teams[name_1]["name"])
team_2 = Team(name_2, create_players(table_2), team_match(2),
teams[name_2]["logo"], teams[name_2]["name"])
create_post(team_1, team_2) | [
11748,
33918,
198,
11748,
12972,
19315,
198,
11748,
7007,
198,
11748,
25064,
198,
11748,
28686,
198,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
198,
6738,
17268,
1330,
3706,
83,
29291,
198,
198,
34945,
796,
28686,
13,
6978,
13,
159... | 2.22607 | 2,079 |
#!/usr/bin/python
"""
Release script for botan (http://botan.randombit.net/)
(C) 2011, 2012 Jack Lloyd
Distributed under the terms of the Botan license
"""
import errno
import logging
import optparse
import os
import shlex
import StringIO
import shutil
import subprocess
import sys
import tarfile
if __name__ == '__main__':
try:
sys.exit(main())
except Exception as e:
logging.error(e)
import traceback
logging.info(traceback.format_exc())
sys.exit(1)
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
37811,
198,
26362,
4226,
329,
10214,
272,
357,
4023,
1378,
13645,
272,
13,
25192,
2381,
270,
13,
3262,
34729,
198,
198,
7,
34,
8,
2813,
11,
2321,
3619,
22361,
198,
198,
20344,
6169,
73... | 2.657895 | 190 |
# Copyright 2014 Roberto Brian Sarrionandia
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import webapp2
import jinja2
import os
from google.appengine.ext import ndb
import tusers
from models import PreRegRecord
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
app = webapp2.WSGIApplication([
('/tab', TabHandler)
], debug=True)
| [
2,
15069,
1946,
32076,
8403,
311,
3258,
295,
392,
544,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
... | 3.256849 | 292 |
import torch
import sys; sys.path.append("/workspace/once-for-all")
from ofa.model_zoo import MobileInvertedResidualBlock
from ofa.layers import ConvLayer, PoolingLayer, LinearLayer,
block_config = {
"name": "MobileInvertedResidualBlock",
"mobile_inverted_conv": {
"name": "MBInvertedConvLayer",
"in_channels": 3,
"out_channels": 3,
"kernel_size": 3,
"stride": 1,
"expand_ratio": 6,
"mid_channels": 288,
"act_func": "h_swish",
"use_se": True
},
"shortcut": {
"name": "IdentityLayer",
"in_channels": [
3
],
"out_channels": [
3
],
"use_bn": False,
"act_func": None,
"dropout_rate": 0,
"ops_order": "weight_bn_act"
}
}
block = MobileInvertedResidualBlock.build_from_config(block_config)
_ = block(torch.Tensor(1, 3, 224, 224))
trace_model = torch.jit.trace(block, (torch.Tensor(1, 3, 224, 224), ))
trace_model.save('./assets/MobileInvertedResidualBlock.jit') | [
11748,
28034,
198,
198,
11748,
25064,
26,
25064,
13,
6978,
13,
33295,
7203,
14,
5225,
10223,
14,
27078,
12,
1640,
12,
439,
4943,
198,
6738,
286,
64,
13,
19849,
62,
89,
2238,
1330,
12173,
818,
13658,
4965,
312,
723,
12235,
198,
6738,
... | 1.753846 | 715 |
from ...abc import Expression
from ..value.valueexpr import VALUE
class CONTEXT(Expression):
"""
The current context.
Usage:
```
!CONTEXT
``
"""
Attributes = {
}
| [
6738,
2644,
39305,
1330,
41986,
198,
6738,
11485,
8367,
13,
8367,
31937,
1330,
26173,
8924,
628,
198,
4871,
22904,
13918,
7,
16870,
2234,
2599,
198,
197,
37811,
198,
464,
1459,
4732,
13,
198,
198,
28350,
25,
198,
15506,
63,
198,
0,
10... | 3 | 57 |
from .controllers.pid import PID_ctrl
PID = PID_ctrl
from .filters.sma import simple_moving_average
SMA = simple_moving_average
from .filters.ewma import exponentially_weighted_moving_average
EWMA = exponentially_weighted_moving_average
from .sensors.camera import camera
camera = camera
| [
6738,
764,
3642,
36667,
13,
35317,
1330,
37022,
62,
44755,
198,
47,
2389,
796,
37022,
62,
44755,
198,
198,
6738,
764,
10379,
1010,
13,
82,
2611,
1330,
2829,
62,
31462,
62,
23913,
198,
50,
5673,
796,
2829,
62,
31462,
62,
23913,
198,
... | 3.344828 | 87 |
from clef_extractors import *
CLEF_BASE_DIR = "/work/ogalolu/data/clef/"
CLEF_LOWRES_DIR = ""
if not CLEF_BASE_DIR:
raise FileNotFoundError(f"Download CLEF and set CLEF_BASE_DIR in {__file__}")
#
# CLEF paths
#
PATH_BASE_QUERIES = CLEF_BASE_DIR + "Topics/"
PATH_BASE_DOCUMENTS = CLEF_BASE_DIR + "DocumentData/"
PATH_BASE_EVAL = CLEF_BASE_DIR + "RelAssess/"
# Prepare dutch CLEF data paths
nl_all = (PATH_BASE_DOCUMENTS + "dutch/all/", extract_dutch)
dutch = {"2001": [nl_all], "2002": [nl_all], "2003": [nl_all]}
# Prepare italian CLEF data paths
it_lastampa = (PATH_BASE_DOCUMENTS + "italian/la_stampa/", extract_italian_lastampa)
it_sda94 = (PATH_BASE_DOCUMENTS + "italian/sda_italian/", extract_italian_sda9495)
it_sda95 = (PATH_BASE_DOCUMENTS + "italian/agz95/", extract_italian_sda9495)
italian = {"2001": [it_lastampa, it_sda94],
"2002": [it_lastampa, it_sda94],
"2003": [it_lastampa, it_sda94, it_sda95]}
# Prepare finnish CLEF data paths
aamu9495 = PATH_BASE_DOCUMENTS + "finnish/aamu/"
fi_ammulethi9495 = (aamu9495, extract_finish_aamuleth9495)
finnish = {"2001": None, "2002": [fi_ammulethi9495], "2003": [fi_ammulethi9495]}
# Prepare english CLEF data paths
gh95 = (PATH_BASE_DOCUMENTS + "english/GH95/", extract_english_gh)
latimes = (PATH_BASE_DOCUMENTS + "english/latimes/", extract_english_latimes)
english = {"2001": [gh95, latimes],
"2002": [gh95, latimes],
"2003": [gh95, latimes]}
# Prepare german CLEF data paths
der_spiegel = (PATH_BASE_DOCUMENTS + "german/der_spiegel/", extract_german_derspiegel)
fr_rundschau = (PATH_BASE_DOCUMENTS + "german/fr_rundschau/", extract_german_frrundschau)
de_sda94 = (PATH_BASE_DOCUMENTS + "german/sda94/", extract_german_sda)
de_sda95 = (PATH_BASE_DOCUMENTS + "german/sda95/", extract_german_sda)
german = {"2003": [der_spiegel, fr_rundschau, de_sda94, de_sda95]}
# Prepare russian CLEF data paths
xml = (PATH_BASE_DOCUMENTS + "russian/xml/", extract_russian)
russian = {"2003": [xml]}
all_paths = {"nl": dutch, "it": italian, "fi": finnish, "en": english, "de": german, "ru": russian}
# Utility function
languages = [("de", "german"), ("en", "english"), ("ru", "russian"), ("fi", "finnish"), ("it", "italian"),
("fr", "french"), ("tr", "turkish")]
short2pair = {elem[0]: elem for elem in languages}
long2pair = {elem[1]: elem for elem in languages}
| [
6738,
1190,
69,
62,
2302,
974,
669,
1330,
1635,
198,
198,
29931,
37,
62,
33,
11159,
62,
34720,
796,
12813,
1818,
14,
519,
282,
349,
84,
14,
7890,
14,
2375,
69,
30487,
198,
29931,
37,
62,
43,
3913,
19535,
62,
34720,
796,
13538,
198... | 2.316098 | 1,025 |
DESTINATION = "dest"
ROUTE = "route"
TIMESTAMP = "time"
INCOMPLETE = "incomplete" | [
35,
6465,
1268,
6234,
796,
366,
16520,
1,
198,
49,
2606,
9328,
796,
366,
38629,
1,
198,
51,
3955,
6465,
23518,
796,
366,
2435,
1,
198,
1268,
41335,
9328,
796,
366,
259,
20751,
1
] | 2.382353 | 34 |
# Copyright 2014 Josh Pieper, jjp@pobox.com.
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''An implementation of a python3/trollius event loop for integration
with QT/PySide.'''
import errno
import thread
import trollius as asyncio
from trollius import From, Return, Task
import logging
import socket
import sys
import types
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui
logger = logging.getLogger(__name__)
| [
2,
15069,
1946,
8518,
21690,
525,
11,
474,
34523,
31,
79,
672,
1140,
13,
785,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
... | 3.481343 | 268 |
import unittest
from troposphere.route53 import AliasTarget
if __name__ == "__main__":
unittest.main()
| [
11748,
555,
715,
395,
198,
198,
6738,
14673,
22829,
13,
38629,
4310,
1330,
978,
4448,
21745,
628,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
555,
715,
395,
13,
12417,
3419,
198
] | 2.775 | 40 |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Dict, Iterable, Optional, Union
import onnx
import onnx.helper
import onnx.utils
from mmdeploy.apis.core import PIPELINE_MANAGER
from mmdeploy.core.optimizers import (attribute_to_dict, create_extractor,
get_new_name, parse_extractor_io_string,
remove_identity, rename_value)
from mmdeploy.utils import get_root_logger
@PIPELINE_MANAGER.register_pipeline()
def extract_partition(model: Union[str, onnx.ModelProto],
start_marker: Union[str, Iterable[str]],
end_marker: Union[str, Iterable[str]],
start_name_map: Optional[Dict[str, str]] = None,
end_name_map: Optional[Dict[str, str]] = None,
dynamic_axes: Optional[Dict[str, Dict[int, str]]] = None,
save_file: Optional[str] = None) -> onnx.ModelProto:
"""Extract partition-model from an ONNX model.
The partition-model is defined by the names of the input and output tensors
exactly.
Examples:
>>> from mmdeploy.apis import extract_model
>>> model = 'work_dir/fastrcnn.onnx'
>>> start_marker = 'detector:input'
>>> end_marker = ['extract_feat:output', 'multiclass_nms[0]:input']
>>> dynamic_axes = {
'input': {
0: 'batch',
2: 'height',
3: 'width'
},
'scores': {
0: 'batch',
1: 'num_boxes',
},
'boxes': {
0: 'batch',
1: 'num_boxes',
}
}
>>> save_file = 'partition_model.onnx'
>>> extract_partition(model, start_marker, end_marker, \
dynamic_axes=dynamic_axes, \
save_file=save_file)
Args:
model (str | onnx.ModelProto): Input ONNX model to be extracted.
start_marker (str | Sequence[str]): Start marker(s) to extract.
end_marker (str | Sequence[str]): End marker(s) to extract.
start_name_map (Dict[str, str]): A mapping of start names, defaults to
`None`.
end_name_map (Dict[str, str]): A mapping of end names, defaults to
`None`.
dynamic_axes (Dict[str, Dict[int, str]]): A dictionary to specify
dynamic axes of input/output, defaults to `None`.
save_file (str): A file to save the extracted model, defaults to
`None`.
Returns:
onnx.ModelProto: The extracted model.
"""
if isinstance(model, str):
model = onnx.load(model)
num_value_info = len(model.graph.value_info)
inputs = []
outputs = []
logger = get_root_logger()
if not isinstance(start_marker, (list, tuple)):
start_marker = [start_marker]
for s in start_marker:
start_name, func_id, start_type = parse_extractor_io_string(s)
for node in model.graph.node:
if node.op_type == 'Mark':
attr = attribute_to_dict(node.attribute)
if attr['func'] == start_name and attr[
'type'] == start_type and attr['func_id'] == func_id:
name = node.input[0]
if name not in inputs:
new_name = get_new_name(
attr, mark_name=s, name_map=start_name_map)
rename_value(model, name, new_name)
if not any([
v_info.name == new_name
for v_info in model.graph.value_info
]):
new_val_info = onnx.helper.make_tensor_value_info(
new_name, attr['dtype'], attr['shape'])
model.graph.value_info.append(new_val_info)
inputs.append(new_name)
logger.info(f'inputs: {", ".join(inputs)}')
# collect outputs
if not isinstance(end_marker, (list, tuple)):
end_marker = [end_marker]
for e in end_marker:
end_name, func_id, end_type = parse_extractor_io_string(e)
for node in model.graph.node:
if node.op_type == 'Mark':
attr = attribute_to_dict(node.attribute)
if attr['func'] == end_name and attr[
'type'] == end_type and attr['func_id'] == func_id:
name = node.output[0]
if name not in outputs:
new_name = get_new_name(
attr, mark_name=e, name_map=end_name_map)
rename_value(model, name, new_name)
if not any([
v_info.name == new_name
for v_info in model.graph.value_info
]):
new_val_info = onnx.helper.make_tensor_value_info(
new_name, attr['dtype'], attr['shape'])
model.graph.value_info.append(new_val_info)
outputs.append(new_name)
logger.info(f'outputs: {", ".join(outputs)}')
# replace Mark with Identity
for node in model.graph.node:
if node.op_type == 'Mark':
del node.attribute[:]
node.domain = ''
node.op_type = 'Identity'
extractor = create_extractor(model)
extracted_model = extractor.extract_model(inputs, outputs)
# remove all Identity, this may be done by onnx simplifier
remove_identity(extracted_model)
# collect all used inputs
used = set()
for node in extracted_model.graph.node:
for input in node.input:
used.add(input)
for output in extracted_model.graph.output:
used.add(output.name)
# delete unused inputs
success = True
while success:
success = False
for i, input in enumerate(extracted_model.graph.input):
if input.name not in used:
del extracted_model.graph.input[i]
success = True
break
# eliminate output without shape
for xs in [extracted_model.graph.output]:
for x in xs:
if not x.type.tensor_type.shape.dim:
logger.info(f'fixing output shape: {x.name}')
x.CopyFrom(
onnx.helper.make_tensor_value_info(
x.name, x.type.tensor_type.elem_type, []))
# eliminate 0-batch dimension, dirty workaround for two-stage detectors
for input in extracted_model.graph.input:
if input.name in inputs:
if input.type.tensor_type.shape.dim[0].dim_value == 0:
input.type.tensor_type.shape.dim[0].dim_value = 1
# eliminate duplicated value_info for inputs
success = True
# num_value_info == 0 if dynamic shape
if num_value_info == 0:
while len(extracted_model.graph.value_info) > 0:
extracted_model.graph.value_info.pop()
while success:
success = False
for i, x in enumerate(extracted_model.graph.value_info):
if x.name in inputs:
del extracted_model.graph.value_info[i]
success = True
break
# dynamic shape support
if dynamic_axes is not None:
for input_node in extracted_model.graph.input:
if input_node.name in dynamic_axes:
axes = dynamic_axes[input_node.name]
for k, v in axes.items():
input_node.type.tensor_type.shape.dim[k].dim_value = 0
input_node.type.tensor_type.shape.dim[k].dim_param = v
for output_node in extracted_model.graph.output:
for idx, dim in enumerate(output_node.type.tensor_type.shape.dim):
dim.dim_value = 0
dim.dim_param = f'dim_{idx}'
# save extract_model if save_file is given
if save_file is not None:
onnx.save(extracted_model, save_file)
return extracted_model
| [
2,
15069,
357,
66,
8,
4946,
44,
5805,
397,
13,
1439,
2489,
10395,
13,
198,
6738,
19720,
1330,
360,
713,
11,
40806,
540,
11,
32233,
11,
4479,
198,
198,
11748,
319,
77,
87,
198,
11748,
319,
77,
87,
13,
2978,
525,
198,
11748,
319,
... | 1.952758 | 4,170 |
import multiprocessing
import os
from joblib import delayed, Parallel
from Utilities.OSMnx_Utility import *
from Utilities.GTFS_Utility import *
from Utilities.General_Function import *
from Utilities.Data_Manipulation import *
import copy
import time
import tqdm
class InstanceNetwork:
"""
The 'InstanceNetwork' class contains all information regarding the used intermodal transportation network, e.g.
the network of Berlin. The functions of this class will combine the various mode networks and prepare the combined
for the solution procedure.
"""
# General attributes of this class
place = ''
connection_layer = 'connectionLayer'
networks = []
networksPath = 'data/networks/'
baseMode = 'walk'
start_time = time.time()
# complete model of network in DiGraph format found in networkx
G = nx.DiGraph()
Graph_for_Preprocessing = nx.DiGraph()
Graph_for_Preprocessing_Reverse = nx.DiGraph()
# individual graph for each mode stored
networkDict = {}
setOfModes = []
listOf_OSMNX_Modes = []
# attributes of multimodal graph
setOfNodes = [] # format [(id, lat, lon),...]
set_of_nodes_walk = set()
setOfEdges = {} # format ( (from_node, to_node, mode) : [time, headway, distance]
modifiedEdgesList_ArcFormulation = {} # format {(node, node, mode) : [time, headway, distance, fixCost], ...}
arcs_of_connectionLayer = [] # [(i,j,m)]
modes_of_public_transport = []
nodeSetID = []
publicTransport = {}
public_transport_modes = {}
matchOfRouteIDandPublicTransportMode = {} # format {routeID: public_transport_mode, ...} eg. {22453: 700, ...}
networksAreInitialized = False
# preprocessing
graph_file_path = ""
list_of_stored_punishes = []
arcs_for_refined_search = []
def initializeNetworks(self):
"""
This function loads individual networks available from OpenStreetMap, except for the Public Transport Networks.
:return: is safed directly to class attributes
"""
# load all desired networks, specified in the attributes of this class
for networkModes in self.networks:
# update class attributes of contained networks
self.setOfModes.append(networkModes)
self.listOf_OSMNX_Modes.append(str(networkModes))
# load network from memory if possible
filepath = self.networksPath + self.place + ', ' + networkModes +'.graphML'
if networkIsAccessibleAtDisk(filepath):
self.networkDict[networkModes] = ox.load_graphml(filepath)
# if network was not saved to memory before, load network from OpenStreetMap by the use of OSMnx
else:
self.networkDict[networkModes] = downloadNetwork(self.place, networkModes, self.networksPath)
# add travel time for each edge, according to mode
# for walk, a average speed of 1.4 meters / second is assumed
if networkModes == 'walk':
G_temp = [] # ebunch
for fromNode, toNode, attr in self.networkDict[networkModes].edges(data='length'):
G_temp.append((fromNode, toNode, {'travel_time': attr/(1.4*60), 'length': attr }))
self.networkDict[networkModes].add_edges_from(G_temp)
# for bike, an average speed of 4.2 meters / seconds is assumed
elif networkModes =='bike':
G_temp=[]
for fromNode, toNode, attr in self.networkDict[networkModes].edges(data='length'):
G_temp.append((fromNode, toNode, {'travel_time': attr/(4.2*60), 'length': attr}))
self.networkDict[networkModes].add_edges_from(G_temp)
# the remaining mode is drive. As OSMnx also retrieves the speedlimits,
# the inbuilt functions for calculating the travel time can be used
else:
self.networkDict[networkModes]= ox.add_edge_speeds(self.networkDict[networkModes], fallback=50, precision = 2)
self.networkDict[networkModes] = ox.add_edge_travel_times(self.networkDict[networkModes], precision=2)
# To fasten later steps, it is indicated that memory are already in memory
self.networksAreInitialized = True
print("--- %s seconds ---" % round((time.time() - self.start_time), 2) + ' to initialize networks')
def mergePublicTransport(self):
"""
This function adds the public transport networks (distinguished by modes, eg. Bus 52, Bus 53, ...) to the
network instance.
:return: return networks are directly assigned to class attributes
"""
# get the networks of all modes of public transport
publicTemporary = getPublicTransportation()
# iterate through all mode categories (e.g. Bus, Tram, Subway, ...)
for keys, mode_category in publicTemporary.items():
self.publicTransport[str(keys)] = mode_category
# get all edges and nodes of respective route network and add it to combined network
# iterate through all mode cateogries: Tram, Subway, Bus, ...
for mode_category, mode in self.publicTransport.items():
# iterate through all modes: Bus 52, Bus 53
for routeID, route in mode.items():
# add attributes to class
self.setOfModes.append(str(routeID))
self.public_transport_modes [str(routeID)] = route
# add nodes, which are stored in in the first element of the route list (format: ID, Lat, Lon)
for node in route[0]:
self.setOfNodes.append([node[0], node[1], node[2]])
# add edges, which are stored in the second element of the route list
for edge, edge_attr in route[1].items():
edge_splitted = edge.split(":")
self.setOfEdges[(edge_splitted[0], edge_splitted[1], routeID)] = [
edge_attr['travelTime'], edge_attr['headway'], 0.0]
def generateMultiModalGraph(self, parameters: {}):
"""
This function takes the prepared input (the added networks retrieved from Public Transport and OpenStreetMap)
and combines them into a Graph (as networkx DiGraph) and individual formats for edges and nodes for
faster processing.
:param parameters: Contains all features and attributes of the considered case, e.g. Berlin networks
:return: nothing, as networks are directly assigned to class attributes
"""
# if possible load complete generated Graph from memory
edges_arc_formulation_file_path = self.networksPath +'setOfEdgesModified.json'
if networkIsAccessibleAtDisk(edges_arc_formulation_file_path):
self.modifiedEdgesList_ArcFormulation = self.get_dict_with_edgeKey(edges_arc_formulation_file_path)
# if not in memory, create MulitModal Graph based on Class Attributes
else:
# if possible, load set of edges from memory
filePathOfEdges = 'data/networks/setOfEdges.json'
if networkIsAccessibleAtDisk(filePathOfEdges):
self.getSavedSets()
# generate set of all edges in multi modal network
else:
# retrieve all individual networks of OpenStreetMap
self.initializeNetworks()
# retrieve all individual networks of Public Transport network
self.mergePublicTransport()
# add each mode and the corresponding network to the mulitmodal graph
for mode in self.setOfModes:
# special treatment for all osmnx data, as drive, walk and bike network share nodes already
if mode in self.listOf_OSMNX_Modes:
# get all nodes and edges of the viewed mode in desired format
setOfNodesByMode, setOfEdgesByMode = getListOfNodesOfGraph(self.networkDict[mode])
# add all nodes to MultiModal Graph
for nodes in setOfNodesByMode:
self.setOfNodes.append(nodes)
# add all edges to MultiModal Graph
if mode == 'drive':
for edge in setOfEdgesByMode:
travel_time = edge[2]['travel_time'] / 60 # convert into minutes
self.setOfEdges[(edge[0], edge[1], mode)] = [travel_time, 0.0, edge[2]['length']]
else:
self.setOfEdges[(edge[0], edge[1], mode)] = [edge[2]['travel_time'], 0.0, edge[2]['length']]
else:
connectingEdges = connectLayersPublicTransport(self.public_transport_modes[mode], mode,
self.networkDict[self.baseMode], self.baseMode)
print("Connection of mode " + mode + "-" + self.baseMode + " initialized")
for edge in connectingEdges.keys():
self.setOfEdges[(edge[0], edge[1], self.connection_layer)] = [connectingEdges[edge]['travel_time'],
0.0, connectingEdges[edge]['length']]
self.setOfModes.append(self.connection_layer)
self.saveMultiModalGraph()
self.getModifiedNetwork(parameters)
print("--- %s seconds ---" % round((time.time() - self.start_time), 2) + ' to get all json ready')
self.initialize_base_network()
self.initialize_graph_for_preprocessing(parameters)
print("--- %s seconds ---" % round((time.time() - self.start_time), 2) + ' to get preprocessing graph ready')
# get all modes of Public transport
tempSet = set()
for i, j, m in self.modifiedEdgesList_ArcFormulation.keys():
if m not in self.listOf_OSMNX_Modes:
tempSet.add(m)
if m == self.connection_layer:
self.arcs_of_connectionLayer.append((i, j, m))
self.modes_of_public_transport=list(tempSet)
print("--- %s seconds ---" % round((time.time() - self.start_time), 2) + ' to get input data in desired format')
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
return [lst[x:x+n] for x in range(0, len(lst), n)]
| [
11748,
18540,
305,
919,
278,
198,
11748,
28686,
198,
198,
6738,
1693,
8019,
1330,
11038,
11,
42945,
198,
198,
6738,
41086,
13,
2640,
44,
77,
87,
62,
18274,
879,
1330,
1635,
198,
6738,
41086,
13,
38,
10234,
50,
62,
18274,
879,
1330,
... | 2.353743 | 4,475 |
# coding=utf-8
import sqlite3
conn = sqlite3.connect('TempTest.db') # 如果db文件不存在将自动创建
curs = conn.cursor() # 从连接获得游标
curs.execute('''
CREATE TABLE messages (
id integer primary key autoincrement,
subject text not null,
sender text not null,
reply_to int,
text text not null
)
''') # 执行SQL语句:建表
curs.execute("""insert into messages (subject, sender, text) values ('111', '111', 'Test111' )""")
curs.execute("""insert into messages (subject, sender, text) values ('222', '222', 'Test222' )""")
curs.execute("""
insert into messages (subject, sender, reply_to, text) values ('333', '333', 1, 'Test333' )
""")
curs.execute("""
insert into messages (subject, sender, reply_to, text) values ('444', '444', 3, 'Test444' )
""")
conn.commit() # 如果修改数据,必须提交修改,才能保存到文件
conn.close() # 关闭连接
| [
2,
19617,
28,
40477,
12,
23,
198,
11748,
44161,
578,
18,
198,
198,
37043,
796,
44161,
578,
18,
13,
8443,
10786,
30782,
14402,
13,
9945,
11537,
220,
1303,
10263,
99,
224,
162,
252,
250,
9945,
23877,
229,
20015,
114,
38834,
27764,
246,
... | 2 | 417 |
# Interface
from abc import ABC, abstractmethod
a = Army()
af = AirForce()
n = Navy()
a.area()
a.gun()
print()
af.area()
af.gun()
print()
n.area()
n.gun() | [
2,
26491,
198,
198,
6738,
450,
66,
1330,
9738,
11,
12531,
24396,
198,
198,
64,
796,
5407,
3419,
198,
1878,
796,
3701,
10292,
3419,
198,
77,
796,
8565,
3419,
198,
198,
64,
13,
20337,
3419,
198,
64,
13,
7145,
3419,
198,
4798,
3419,
... | 2.338235 | 68 |
import pandas as pd
import os
if __name__ == '__main__':
update_validation_data(force=True)
print('Done') | [
11748,
19798,
292,
355,
279,
67,
198,
11748,
28686,
628,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
4296,
62,
12102,
341,
62,
7890,
7,
3174,
28,
17821,
8,
198,
220,
220,
220,
3601,
10786,
4567... | 2.613636 | 44 |
# Auto-luokka yliluokka erilaisille autotyypeille
# Ominaisuudet (Field, Property) merkki, malli, vuosimalli, kilometrit, käyttövoima, vaihteistotyyppi, väri ja
# Henkiloauto
if __name__ == '__main__':
henkiloauto1 = Henkiloauto('ABC-12', 'Ferrary', 'Land', 2020, 354322, 'diesel', 'automaatti', 'punainen', 270, 2.8, 4000, 7, 5, 'tila-auto', 300, ['vakionopeuden säädin', 'peruutuskamera'])
print('Rekisterinumero: ', henkiloauto1.rek, 'istumapaikkoja', henkiloauto1.istuimet)
# Lasketaan jäljelläolevien kilometrien hinta
print('Jäljellä olevien kilometrien hinta on', henkiloauto1.km_jaljella())
print('Jäljellä olevien kilometrien hinta on', henkiloauto1.km_jaljella_hinta())
print('Korjatut kilometrit on:', henkiloauto1.korjatut_kilometrit(2))
kilometreja_jaljella = Auto.arvio_kilometrit(2.8, 364800, 2)
print('Laskettu staattisella metodilla:', kilometreja_jaljella) | [
198,
2,
11160,
12,
2290,
482,
4914,
331,
75,
346,
84,
482,
4914,
1931,
10102,
271,
8270,
1960,
313,
88,
2981,
8270,
198,
198,
2,
440,
1084,
15152,
84,
463,
316,
357,
15878,
11,
14161,
8,
4017,
74,
4106,
11,
17374,
72,
11,
410,
8... | 2.238806 | 402 |
import os
import sqlite3
def cursore_maker(method):
"""Декоратор, создающий курсор, для работы с бд"""
return wrapper
class SQLWorker:
"""Это API для работы с SQLite таблицами, заточенный под основную программу"""
@cursore_maker
def make_table(self, cur):
"""Метод, создающий таблицу (если она не существует)"""
# формат бд описан здесь
cur.execute("""CREATE TABLE IF NOT EXISTS dump(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
name text NOT NULL,
path text NOT NULL,
create_date text NOT NULL,
last_edit_date NOT NULL,
weight INTEGER NOT NULL
);""")
@cursore_maker
def add_to_the_table(self, cur, data):
"""Метод позволяет заполнить таблицу данными, на вход принимает список кортежей"""
cur.executemany("""INSERT INTO dump(name, path, create_date, last_edit_date, weight) VALUES (?,?,?,?,?)""",
data)
@cursore_maker
def search_by_sql_request(self, cur, request):
"""Метод необходим для самостоятельных пользователей, которые сами пишут SQL запрос"""
# можешь использовать его, для расширения функционала или тестов
return cur.execute(request).fetchall()
def replace_data(self, data):
"""Замена данных таблицы на новые"""
os.remove(self.name)
self.make_table()
self.fill_the_table(data)
@cursore_maker
def get_all_values(self, cur):
"""Возвращает все значения"""
data = cur.execute("select * from dump").fetchall()
return data
@cursore_maker
def except_sort_and_search(self, cur, request, search_in='name', order_by='name', direction='DESC'):
"""Метод, возвращающий все элементы таблицы содержащие в себе запрос, отсортированные
по заданному критерию, но исключая запрос"""
# direction можно передать "ASC", тогда будет от меньшего к большему
return cur.execute(f"""select * from dump where not({search_in} like '%{request}%')
ORDER BY {order_by} {direction}""").fetchall()
@cursore_maker
def sort_and_search(self, cur, request, search_in='name', order_by='name', direction='DESC'):
"""Метод, возвращающий все элементы таблицы содержащие в себе запрос, отсортированные по заданному критерию"""
# direction можно передать "ASC", тогда будет от меньшего к большему
return cur.execute(f"""select * from dump where {search_in} like '%{request}%'
ORDER BY {order_by} {direction}""").fetchall()
if __name__ == '__main__':
from Searcher import FileWorker
base = SQLWorker() # скобочки обязательно, там можно передавать имя файла с бд
file = FileWorker('./test')
base.make_table()
base.fill_the_table(file.list_of_files)
print(base.search_except_parameter('flag')) # старый код, до рефакторинга, сейчас уже не работает
| [
11748,
28686,
198,
11748,
44161,
578,
18,
628,
198,
4299,
13882,
382,
62,
10297,
7,
24396,
2599,
198,
220,
220,
220,
37227,
140,
242,
16843,
31583,
15166,
21169,
16142,
20375,
15166,
21169,
11,
220,
21727,
25443,
115,
43666,
16142,
141,
... | 1.526505 | 1,943 |
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD 3-Clause License for more details.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
| [
2,
15269,
357,
34,
8,
12131,
13,
43208,
21852,
1766,
1539,
12052,
13,
1439,
2489,
10395,
13,
201,
198,
201,
198,
2,
1212,
1430,
318,
1479,
3788,
26,
345,
460,
17678,
4163,
340,
290,
14,
273,
13096,
340,
739,
262,
2846,
286,
262,
3... | 3.632653 | 147 |
import numpy as np
import tensorflow as tf
from baselines.a2c.utils import conv, fc, conv_to_fc
from baselines.common.distributions import make_pdtype
from baselines.common.input import observation_input
def impala_cnn(images, depths=[16, 32, 32], use_batch_norm=True, dropout=0):
"""
Model used in the paper "IMPALA: Scalable Distributed Deep-RL with
Importance Weighted Actor-Learner Architectures" https://arxiv.org/abs/1802.01561
"""
dropout_layer_num = [0]
dropout_assign_ops = []
out = images
for depth in depths:
out = conv_sequence(out, depth)
out = tf.layers.flatten(out)
out = tf.nn.relu(out)
out = tf.layers.dense(out, 256, activation=tf.nn.relu)
return out, dropout_assign_ops
def nature_cnn(scaled_images, **conv_kwargs):
"""
Model used in the paper "Human-level control through deep reinforcement learning"
https://www.nature.com/articles/nature14236
"""
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),
**conv_kwargs))
h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs))
h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs))
h3 = conv_to_fc(h3)
return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))
def random_impala_cnn(images, depths=[16, 32, 32], use_batch_norm=True, dropout=0):
"""
Model used in the paper "IMPALA: Scalable Distributed Deep-RL with
Importance Weighted Actor-Learner Architectures" https://arxiv.org/abs/1802.01561
"""
dropout_layer_num = [0]
dropout_assign_ops = []
out = images
# add random filter
randcnn_depth = 3
mask_vbox = tf.Variable(tf.zeros_like(images, dtype=bool), trainable=False)
mask_shape = tf.shape(images)
rh = .2 # hard-coded velocity box size
mh = tf.cast(tf.cast(mask_shape[1], dtype=tf.float32)*rh, dtype=tf.int32)
mw = mh*2
mask_vbox = mask_vbox[:,:mh,:mw].assign(tf.ones([mask_shape[0], mh, mw, mask_shape[3]], dtype=bool))
img = tf.where(mask_vbox, x=tf.zeros_like(images), y=images)
rand_img = tf.layers.conv2d(img, randcnn_depth, 3, padding='same', \
kernel_initializer=tf.initializers.glorot_normal(), trainable=False, name='randcnn')
out = tf.where(mask_vbox, x=images, y=rand_img, name='randout')
for depth in depths:
out = conv_sequence(out, depth)
out = tf.layers.flatten(out)
out = tf.nn.relu(out)
out = tf.layers.dense(out, 256, activation=tf.nn.relu)
return out, dropout_assign_ops | [
11748,
299,
32152,
355,
45941,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
6738,
1615,
20655,
13,
64,
17,
66,
13,
26791,
1330,
3063,
11,
277,
66,
11,
3063,
62,
1462,
62,
16072,
198,
6738,
1615,
20655,
13,
11321,
13,
17080,
2455,
... | 2.313274 | 1,130 |
import os
from fusedwake import fusedwake
import numpy as np
from topfarm.cost_models.fuga import py_fuga
from topfarm.cost_models.fuga.py_fuga import PyFuga
from topfarm.cost_models.fused_wake_wrappers import FusedWakeGCLWakeModel
from topfarm.cost_models.utils.aep_calculator import AEPCalculator
from topfarm.cost_models.utils.wind_resource import WindResource
from topfarm.cost_models.fuga.lib_reader import read_lib
fuga_path = os.path.abspath(os.path.dirname(py_fuga.__file__)) + '/Colonel/'
if __name__ == '__main__':
print(HornsrevAEP_Fuga())
print(HornsrevAEP_FUSEDWake_GCL())
| [
11748,
28686,
198,
6738,
43954,
48530,
1330,
43954,
48530,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
1353,
43323,
13,
15805,
62,
27530,
13,
69,
30302,
1330,
12972,
62,
69,
30302,
198,
6738,
1353,
43323,
13,
15805,
62,
27530,
13,
69... | 2.686099 | 223 |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import IndexLocator, FormatStrFormatter
'''
Meredith Rawls, Dec 2015
Plotting routine for initial 'test' runs of ELC.
It will make a plot that has both light curve data w/fit and RV data w/fit.
There are also residuals in the plots!
(Strongly based on ELCplotter_unfold.py)
***IMPORTANT***
This version assumes the files above are NOT yet folded in phase, and are in time.
This would happen if you are using ELCgap.inp, or anytime when ELC.inp has itime = 2.
So we need to fold them.
(If you want to plot already-folded data, use ELCplotter_new.py)
***ALSO IMPORTANT***
This version assumes you haven't run demcmcELC yet, but just ELC, to get an initial
clue whether or not your input parameters are half decent.
In other words, it doesn't need .fold files or fitparm.all, but it does need ELC.out.
'''
# Colors for plots. Selected with help from colorbrewer.
red = '#e34a33' # red, star 1
yel = '#fdbb84' # yellow, star 2
# Columns in fitparm file that correspond to T0 and Period
#tconj_col = 0
#porb_col = 15
# Read in everything
f1 = 'modelU.mag'
#f2 = 'ELCdataU.fold'
f3 = 'star1.RV'
f4 = 'star2.RV'
ELCoutfile = 'ELC.out'
gridloop = 'gridloop.opt'
#f5 = 'ELCdataRV1.fold'
#f6 = 'ELCdataRV2.fold'
#fitparm = 'fitparm.all'
# OPTIONAL ADJUSTMENT B/C FINAL ELC RV MODEL OUTPUT IS SHIFTED BY GAMMA
#gamma = 0
gamma = input("Enter gamma adjustment (0 for none): ")
phase_mod,mag_mod = np.loadtxt(f1, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
#phase_dat,mag_dat = np.loadtxt(f2, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv1,rv1 = np.loadtxt(f3, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv2,rv2 = np.loadtxt(f4, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
#phase_rv1dat,rv1dat,rv1err = np.loadtxt(f5, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
#phase_rv2dat,rv2dat,rv2err = np.loadtxt(f6, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
# FUNCTION TO FOLD STUFF so phases are actually phases ... and then sort all the arrays.
# GET PERIOD AND T0 from ELC.out file
with open(ELCoutfile) as f:
for i, row in enumerate(f):
if i == 27: # 28th row
columns = row.split()
period = float(columns[0]) # 1st column
#if i == 38: # 39th row, i.e. T0 # this one has a funny zeropoint (ok if circular)
if i == 133: # 134th row, i.e. Tconj # this one puts primary eclipse at phase 0
columns = row.split()
Tconj = float(columns[0]) #1st column
#periods, tconjs = np.loadtxt(fitparm, usecols=(porb_col, tconj_col), unpack=True)
#period = np.median(periods)
#Tconj = np.median(tconjs)
print(period, Tconj)
Tconj = Tconj + 0.5*period
with open(gridloop) as f:
for i, row in enumerate(f):
if i == 0:
LCinfile = row.split()[0]
if i == 8:
RV1infile = row.split()[0]
if i == 9:
RV2infile = row.split()[0]
# Read in observed times, magnitudes, and RVs (calling time 'phase' but that's a lie)
phase_dat,mag_dat = np.loadtxt(LCinfile, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv1dat,rv1dat,rv1err = np.loadtxt(RV1infile, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
phase_rv2dat,rv2dat,rv2err = np.loadtxt(RV2infile, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
# Fold everything (observations and model)
phase_mod = phasecalc(phase_mod, period=period, BJD0=Tconj)
phase_dat = phasecalc(phase_dat, period=period, BJD0=Tconj)
phase_rv1 = phasecalc(phase_rv1, period=period, BJD0=Tconj)
phase_rv2 = phasecalc(phase_rv2, period=period, BJD0=Tconj)
phase_rv1dat = phasecalc(phase_rv1dat, period=period, BJD0=Tconj)
phase_rv2dat = phasecalc(phase_rv2dat, period=period, BJD0=Tconj)
p1 = phase_mod.argsort()
p2 = phase_dat.argsort()
p3 = phase_rv1.argsort()
p4 = phase_rv2.argsort()
p5 = phase_rv1dat.argsort()
p6 = phase_rv2dat.argsort()
phase_mod = phase_mod[p1]
phase_dat = phase_dat[p2]
phase_rv1 = phase_rv1[p3]
phase_rv2 = phase_rv2[p4]
phase_rv1dat = phase_rv1dat[p5]
phase_rv2dat = phase_rv2dat[p6]
mag_mod = mag_mod[p1]
mag_dat = mag_dat[p2]
rv1 = rv1[p3]
rv2 = rv2[p4]
rv1dat = rv1dat[p5]
rv2dat = rv2dat[p6]
# OPTIONAL ADJUSTMENT B/C FINAL ELC RV MODEL OUTPUT IS SHIFTED BY GAMMA
#gamma = input("Enter gamma adjustment (0 for none): ")
rv1 = rv1 + gamma
rv2 = rv2 + gamma
print ("Done reading (and folding) data!")
if np.abs(np.median(mag_mod) - np.median(mag_dat)) > 1:
print('Adjusting magnitude of model light curve...')
mag_mod = mag_mod + (np.median(mag_dat) - np.median(mag_mod))
# Interpolate model onto data phase grid, for residuals
newmag_model = np.interp(phase_dat, phase_mod, mag_mod)
newrv1 = np.interp(phase_rv1dat, phase_rv1, rv1)
newrv2 = np.interp(phase_rv2dat, phase_rv2, rv2)
lcresid = mag_dat - newmag_model
rv1resid = rv1dat - newrv1
rv2resid = rv2dat - newrv2
print ("Done interpolating!")
# Make plots
# First, define some handy global parameters for the plots
phasemin = 0
phasemax = 1
magdim = np.max(mag_dat) + 0.02 #11.97 # remember magnitudes are backwards, dangit
magbright = np.min(mag_dat) - 0.02 #11.861
rvmin = np.min([np.min(rv1dat), np.min(rv2dat)]) - 5 #-79
rvmax = np.max([np.max(rv1dat), np.max(rv2dat)]) + 5 #-1
primary_phasemin = 0.48 #0.09 #0.48
primary_phasemax = 0.52 #0.14 #0.52
secondary_phasemin = 0.98 #0.881
secondary_phasemax = 1.01 #0.921
magresid_min = 0.006 # remember magnitudes are backwards, dangit
magresid_max = -0.006
rvresid_min = -5
rvresid_max = 5
# Light curve
ax1 = plt.subplot2grid((12,1),(4,0), rowspan=3)
plt.axis([phasemin, phasemax, magdim, magbright])
plt.tick_params(axis='both', which='major')
plt.plot(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, 'k', lw=1.5, label='ELC Model') #lc model
ax1.set_ylabel('Magnitude', size=18)
ax1.set_xticklabels([])
# Radial velocities
ax2 = plt.subplot2grid((12,1),(1,0), rowspan=3)
plt.subplots_adjust(wspace = 0.0001, hspace=0.0001)
plt.axis([phasemin, phasemax, rvmin, rvmax])
plt.errorbar(phase_rv1dat, rv1dat, yerr=rv1err, marker='o', color=yel, ms=9, mec='None', ls='None') #rv1 data
plt.errorbar(phase_rv2dat, rv2dat, yerr=rv2err, marker='o', color=red, ms=9, mec='None', ls='None') #rv2 data
plt.plot(phase_rv1, rv1, color='k', lw=1.5) #rv1 model
plt.plot(phase_rv2, rv2, color='k', lw=1.5) #rv2 model
ax2.set_ylabel('Radial Velocity (km s$^{-1}$)', size=18)
ax2.set_xticklabels([])
# Light curve residuals
axr1 = plt.subplot2grid((12,1),(7,0))
axr1.axis([phasemin, phasemax, magresid_min, magresid_max])
axr1.set_yticks([-0.004, 0, 0.004])
plt.axhline(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
# Radial velocity residuals
axr2 = plt.subplot2grid((12,1),(0,0))
axr2.axis([phasemin, phasemax, rvresid_min, rvresid_max])
#axr2.set_yticks([-2,0,2])
plt.axhline(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')
plt.errorbar(phase_rv1dat, rv1resid, yerr=rv1err, marker='o', color=yel, ms=9, mec='None', ls='None') #rv1 residual
plt.errorbar(phase_rv2dat, rv2resid, yerr=rv2err, marker='o', color=red, ms=9, mec='None', ls='None') #rv2 residual
#plt.xlabel('Orbital Phase (conjunction at $\phi = 0.5$)', size=20) # EXTRA LABEL
axr2.set_xticklabels([])
# Zoom-in of shallower (secondary) eclipse
ax3 = plt.subplot2grid((12,2),(9,1), rowspan=2)
plt.axis([secondary_phasemin, secondary_phasemax, magdim, magbright])
ax3.set_xticks([0.89, 0.90, 0.91, 0.92])
plt.plot(phase_dat, mag_dat, color=yel, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, color='k', lw=1.5) #lc model
ax3.set_ylabel('Magnitude')
ax3.set_xticklabels([])
ax3.set_yticklabels([])
# Zoom-in of deeper (primary) eclipse
ax4 = plt.subplot2grid((12,2),(9,0), rowspan=2)
plt.axis([primary_phasemin, primary_phasemax, magdim, magbright])
ax4.set_xticks([0.49, 0.50, 0.51, 0.52])
plt.plot(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, color='k', lw=1.5) #lc model
ax4.set_xticklabels([])
#ax4.set_yticklabels([])
# Zoom plot residuals, shallower (secondary) eclipse
axr3 = plt.subplot2grid((12,2),(11,1))
plt.axis([secondary_phasemin, secondary_phasemax, magresid_min, magresid_max])
axr3.set_yticks([-0.004, 0, 0.004])
axr3.set_xticks([0.89, 0.90, 0.91, 0.92])
plt.axhline(y=0, xmin=0, xmax=2, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
axr3.set_yticklabels([])
# Zoom plot residuals, deeper (primary) eclipse
axr4 = plt.subplot2grid((12,2),(11,0))
plt.axis([primary_phasemin, primary_phasemax, magresid_min, magresid_max])
axr4.set_yticks([-0.004, 0, 0.004])
axr4.set_xticks([0.49, 0.50, 0.51, 0.52])
plt.axhline(y=0, xmin=0, xmax=2, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
#axr4.set_yticklabels([])
# Labels using overall figure as a reference
plt.figtext(0.5, 0.04, 'Orbital Phase (conjunction at $\phi = 0.5$)', ha='center', va='center', size=25)
#plt.figtext(0.135, 0.18, 'Secondary')
#plt.figtext(0.535, 0.18, 'Primary')
plt.figtext(0.06, 0.86, '$\Delta$')
plt.figtext(0.04, 0.395, '$\Delta$')
plt.figtext(0.04, 0.125, '$\Delta$')
ax1.legend(loc='lower right', frameon=False, prop={'size':20})
print ("Done preparing plot!")
plt.show()
#outfile = 'testplot1.png'
#plt.savefig(outfile)
#print ("Plot saved to %s!" % outfile)
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
6738,
2603,
29487,
8019,
13,
83,
15799,
1330,
12901,
33711,
1352,
11,
18980,
13290,
84... | 2.229345 | 4,321 |
"""
Copyright (c) 2020 WEI.ZHOU. All rights reserved.
The following code snippets are only used for circulation and cannot be used for business.
If the code is used, no consent is required, but the author has nothing to do with any problems
and consequences.
In case of code problems, feedback can be made through the following email address.
<xiaoandx@gmail.com>
@author: WEI.ZHOU
@data:2020-10-29
"""
# 根据公式计算值
import math
C = 50
H = 30
value = []
values= input("请输入一组数字:")
values = values.split(',')
for D in values:
s = str(int(round(math.sqrt(2 * C * float(D) / H))))
value.append(s)
print(','.join(value)) | [
37811,
198,
15269,
357,
66,
8,
12131,
12887,
40,
13,
57,
46685,
13,
1439,
2489,
10395,
13,
198,
464,
1708,
2438,
45114,
389,
691,
973,
329,
19133,
290,
2314,
307,
973,
329,
1597,
13,
198,
1532,
262,
2438,
318,
973,
11,
645,
8281,
... | 2.471698 | 265 |
import string
import re
from nlpaug.util import Method
from nlpaug.util.text.tokenizer import Tokenizer
from nlpaug import Augmenter
from nlpaug.util import WarningException, WarningName, WarningCode, WarningMessage
| [
11748,
4731,
198,
11748,
302,
198,
198,
6738,
299,
34431,
7493,
13,
22602,
1330,
11789,
198,
6738,
299,
34431,
7493,
13,
22602,
13,
5239,
13,
30001,
7509,
1330,
29130,
7509,
198,
6738,
299,
34431,
7493,
1330,
2447,
434,
263,
198,
6738,
... | 3.694915 | 59 |
from ._frontend import (
BackendFailed,
CmdStatus,
Frontend,
MetadataForBuildWheelResult,
RequiresBuildSdistResult,
RequiresBuildWheelResult,
SdistResult,
WheelResult,
)
from ._version import version
from ._via_fresh_subprocess import SubprocessFrontend
#: semantic version of the project
__version__ = version
__all__ = [
"__version__",
"Frontend",
"BackendFailed",
"CmdStatus",
"RequiresBuildSdistResult",
"RequiresBuildWheelResult",
"MetadataForBuildWheelResult",
"SdistResult",
"WheelResult",
"SubprocessFrontend",
]
| [
6738,
47540,
8534,
437,
1330,
357,
198,
220,
220,
220,
5157,
437,
37,
6255,
11,
198,
220,
220,
220,
327,
9132,
19580,
11,
198,
220,
220,
220,
8880,
437,
11,
198,
220,
220,
220,
3395,
14706,
1890,
15580,
45307,
23004,
11,
198,
220,
... | 2.741935 | 217 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 18:29:10 2019
@author: itamar
"""
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_images)
test_labels
print(train_images.ndim)
train_images.shape
print(train_images.dtype)
digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()
from keras import models , layers
network = models.Sequential(name = 'hello Keras')
network.add(layers.Dense(512, activation = 'relu' , input_shape = (28*28,)))
network.add(layers.Dense(10, activation='softmax'))
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images, train_labels, epochs=20, batch_size=32)
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
import numpy as np
x = np.array([[[1,2,3],
[1,7,3],
[1,2,3]],
[[1,2,3],
[1,4,3],
[1,2,3]]])
x.ndim
x.shape
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
3300,
5267,
2681,
1248,
25,
1959,
25,
940,
13130,
198,
198,
31,
9800,
25,
340,
39236,
198... | 2.350238 | 631 |
from api import db
| [
6738,
40391,
1330,
20613,
220,
198,
220,
220,
220,
220
] | 2.4 | 10 |
from datetime import date
import numpy as np
import pandas as pd
from scipy.stats import zscore
def normalize(df):
"""
特徴量を標準化する。
Parameters
----------
df: pandas.dataframe
標準化前の特徴量データフレーム
Returns
-------
norm_df: pandas.dataframe
標準化された特徴量データフレーム
"""
def calc_age(born):
"""
生年月日から年齢を計算する。
Parameters
----------
born: datetime.datetime
利用者の生年月日
Returns
-------
age: int
利用者の年齢
"""
today = date.today()
age = today.year-born.year-((today.month, today.day)<(born.month, born.day))
return age
# 年齢を算出する。
df['age'] = df['birth_date'].map(calc_age)
# 標準化する。
norm_df = pd.DataFrame()
# norm_df['id'] = df['id']
f_cols = ['desitination_latitude', 'desitination_longitude', 'age', 'sex']
norm_df[f_cols] = df[f_cols].apply(zscore)
return norm_df
def calc_dist_array(norm_df, f_w=[1, 1, 1]):
"""
特徴量からデータ間距離を求める。
Parameters
----------
norm_df: pandas.dataframe
標準化された特徴量のデータフレーム
f_w: list
各特徴量の重み
Returns
-------
dist_array: numpy.ndarray
利用者間のデータ間距離2次元配列(上三角行列)
"""
d_lat = norm_df['desitination_latitude'].values
d_long = norm_df['desitination_longitude'].values
age = norm_df['age'].values
sex = norm_df['sex'].values
def square_diff_matrix(f_array):
"""
1次元配列の各要素の差分の二乗を計算する。
Parameters
----------
f_array: numpy.ndarray
利用者毎の特徴量を示す1次元配列
Returns
-------
diff_array: numpy.ndarray
差分の二乗が入った2次元配列
"""
length_fa = len(f_array)
diff_array = np.array([(i-j)**2 for i in f_array for j in f_array])
diff_array = diff_array.reshape(length_fa, length_fa)
return diff_array
# 各特徴量の差分の二乗和の行列を求める。
direct_dist = np.sqrt(square_diff_matrix(d_lat)+square_diff_matrix(d_long))
age_dist = square_diff_matrix(age)
sex_dist = square_diff_matrix(sex)
# 各特徴量への重みづける
dist_array = f_w[0]*direct_dist+f_w[1]*age_dist+f_w[2]*sex_dist
dist_array = dist_array/sum(f_w)
dist_array = np.triu(dist_array)
return dist_array
| [
6738,
4818,
8079,
1330,
3128,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
19798,
292,
355,
279,
67,
198,
6738,
629,
541,
88,
13,
34242,
1330,
1976,
26675,
628,
198,
4299,
3487,
1096,
7,
7568,
2599,
198,
220,
220,
220,
37227,
198,
... | 1.597742 | 1,417 |
__version__ = "1.0.3"
from spotify_uri.parse import parse as _parse
from spotify_uri.spotify import SpotifyUri
| [
834,
9641,
834,
796,
366,
16,
13,
15,
13,
18,
1,
198,
198,
6738,
4136,
1958,
62,
9900,
13,
29572,
1330,
21136,
355,
4808,
29572,
198,
6738,
4136,
1958,
62,
9900,
13,
20485,
1958,
1330,
26778,
52,
380,
628,
628,
628
] | 2.853659 | 41 |
import argparse
import pandas as pd
import numpy as np
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
from cloudwine.utils import logger
# Loads TF-IDF model and inferences input string
# Loads TF-IDF model and inferences input string
# Loads BERT embeddings and inferences input string
| [
11748,
1822,
29572,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
2298,
293,
198,
6738,
1341,
35720,
13,
30053,
62,
2302,
7861,
13,
5239,
1330,
309,
69,
312,
69,
38469,
7509,
198,
6738,
1341,
35... | 3.152047 | 171 |
from __future__ import absolute_import
from collections import OrderedDict, deque
from urlparse import urlparse
| [
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
198,
198,
6738,
17268,
1330,
14230,
1068,
35,
713,
11,
390,
4188,
198,
6738,
19016,
29572,
1330,
19016,
29572,
628,
198
] | 3.965517 | 29 |
import json
from tweepy import OAuthHandler, Stream, StreamListener #faz requisicao de tweets ao Twitter
from datetime import datetime
# CADASTRAR AS CHAVES DE ACESSO
consumer_key = "YGSFrzszgES6SFMtZTUghUhlw"
consumer_secret = "TITEr8yC97JPTaiG9flVZrGc8INvFkObHpznB6NnupabE3OKx2"
access_token = "1342352348497272833-J2FXw9MGDeiOQFSRLzsyJog94VOiRH"
access_token_secret = "x5pdI1Fos0MMxidVxMYkfq5GrJ2u8GNounFan74SzuRZE"
# DEFININDO UM ARQUIVO DE SAÍDA PARA ARMAZENAR OS TWEETS COLETADOS
data_hoje = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
out = open(f"collected_tweets_{data_hoje}.txt", "w")
# IMPLEMENTAR UM CLASSE PARA CONEXÃO COM TWITTER
## My Listener está recebendo uma herança da classe StreamListener!
# IMPLEMENTAR A FUNÇÃO MAIN
if __name__ == "__main__":
l = MyListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(track=["DisneyPlus"])
| [
11748,
33918,
220,
198,
6738,
4184,
538,
88,
1330,
440,
30515,
25060,
11,
13860,
11,
13860,
33252,
220,
1303,
69,
1031,
1038,
271,
3970,
78,
390,
12665,
257,
78,
3009,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
198,
2,
37292,
1921,... | 2.262557 | 438 |
#!/usr/env/bin python
from setuptools import setup
setup(
name='pygitea',
version='0.0.1',
description='Gitea API wrapper for python',
url='http://github.com/jo-nas/pygitea',
author='Jonas',
author_email='jonas@steinka.mp',
install_requires=[
'parse',
'requests'
],
setup_requires=["pytest-runner"],
tests_require=["pytest"],
license='WTFPL',
packages=['pygitea']
)
| [
2,
48443,
14629,
14,
24330,
14,
8800,
21015,
198,
198,
6738,
900,
37623,
10141,
1330,
9058,
198,
198,
40406,
7,
198,
220,
220,
220,
1438,
11639,
9078,
70,
578,
64,
3256,
198,
220,
220,
220,
2196,
11639,
15,
13,
15,
13,
16,
3256,
1... | 2.273684 | 190 |
from .poly import polyrecur
from scipy import integrate
from .tools import printer
from copy import deepcopy
import numpy as np
# %% Polynomial Chaos
class Expansion:
"""Class of polynomial chaos expansion"""
# Evaluates the expansion at the points
# %% Univariate Expansion
def transfo(invcdf,order,dist):
"""Maps an arbitrary random variable to another distribution"""
nbrPoly = order+1
coef = np.zeros(nbrPoly)
poly = polyrecur(order,dist)
# Computes polynomial chaos coefficients and model
for i in range(nbrPoly):
fun = lambda x: invcdf(x)*poly.eval(dist.invcdf(x))[:,i]
coef[i] = integrate.quad(fun,0,1)[0]
expan = Expansion(coef,poly)
transfo = lambda x: expan.eval(x)
return transfo
# %% Analysis of Variance
def anova(coef,poly):
"""Computes the first and total order Sobol sensitivity indices"""
S,ST = [[],[]]
expo = poly.expo
dim = expo.shape[0]
coef = np.array(coef)
nbrPoly = poly[:].shape[0]
var = np.sum(coef[1:]**2,axis=0)
# Computes the first and total Sobol indices
for i in range(dim):
order = np.sum(expo,axis=0)
pIdx = np.array([poly[j].nonzero()[-1][-1] for j in range(nbrPoly)])
sIdx = np.where(expo[i]-order==0)[0].flatten()[1:]
index = np.where(np.in1d(pIdx,sIdx))[0]
S.append(np.sum(coef[index]**2,axis=0)/var)
sIdx = np.where(expo[i])[0].flatten()
index = np.where(np.in1d(pIdx,sIdx))[0]
ST.append(np.sum(coef[index]**2,axis=0)/var)
S = np.array(S)
ST = np.array(ST)
sobol = dict(zip(['S','ST'],[S,ST]))
return sobol
# %% Analysis of Covariance
def ancova(model,point,weight=0):
"""Computes the sensitivity indices by analysis of covariance"""
printer(0,'Computing ancova ...')
nbrPts = np.array(point)[...].shape[0]
if not np.any(weight): weight = np.ones(nbrPts)/nbrPts
expo = model.expo
coef = model.coef
nbrIdx = expo.shape[1]
index,ST,SS = [[],[],[]]
model = deepcopy(model)
resp = model.eval(point)
difMod = resp-np.dot(resp.T,weight).T
varMod = np.dot(difMod.T**2,weight).T
# Computes the total and structural indices
for i in range(1,nbrIdx):
model.expo = expo[:,i,None]
model.coef = coef[...,i,None]
resp = model.eval(point)
dif = resp-np.dot(resp.T,weight).T
cov = np.dot((dif*difMod).T,weight).T
var = np.dot(dif.T**2,weight).T
S = cov/varMod
if not np.allclose(S,0):
index.append(expo[:,i])
SS.append(var/varMod)
ST.append(S)
# Combines the different powers of a same monomial
index,SS,ST = combine(index,SS,ST)
ancova = dict(zip(['SS','SC','ST'],[SS,ST-SS,ST]))
printer(1,'Computing ancova 100 %')
return index,ancova
# %% Combine Power
def combine(index,SS,ST):
"""Combines the indices from different powers of the same monomial"""
index = np.transpose(index)
index = (index/np.max(index,axis=0)).T
# Normalizes and eliminates the duplicates
minIdx = np.min(index,axis=1)
idx = np.argwhere(minIdx).flatten()
index[idx] = (index[idx].T/minIdx[idx]).T
index = np.rint(index).astype(int)
index,old = np.unique(index,return_inverse=1,axis=0)
shape = (index.shape[0],)+np.array(SS).shape[1:]
SS2 = np.zeros(shape)
ST2 = np.zeros(shape)
# Combines duplicates ancova indices
for i in range(old.shape[0]): SS2[old[i]] += SS[i]
for i in range(old.shape[0]): ST2[old[i]] += ST[i]
return index,SS2,ST2 | [
6738,
764,
35428,
1330,
7514,
8344,
333,
198,
6738,
629,
541,
88,
1330,
19386,
198,
6738,
764,
31391,
1330,
20632,
198,
6738,
4866,
1330,
2769,
30073,
198,
11748,
299,
32152,
355,
45941,
198,
198,
2,
43313,
12280,
26601,
498,
13903,
198... | 2.184211 | 1,672 |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC, expected_conditions
from selenium.webdriver.support.wait import WebDriverWait as wait
from fixtures.params import DEFAULT_PASSWORD
| [
6738,
384,
11925,
1505,
13,
12384,
26230,
13,
11321,
13,
1525,
1330,
2750,
198,
6738,
384,
11925,
1505,
13,
12384,
26230,
13,
11284,
1330,
2938,
62,
17561,
1756,
355,
13182,
11,
2938,
62,
17561,
1756,
198,
6738,
384,
11925,
1505,
13,
... | 3.602941 | 68 |
from RNAseq import *
| [
6738,
25897,
41068,
1330,
1635,
628
] | 3.666667 | 6 |
import os
import subprocess
from clams import arg, Command
from . import current_project
version = Command(
name='version',
title='Utilities for versioning and releases.',
description='Utilities for versioning and releases.',
)
def _get_version():
"""Read and return the project version number."""
from unb_cli import version
v = version.read(current_project().version_file_path)
return v or ''
def _list_tags():
"""List tags."""
subprocess.call(['git', 'tag', '-l', '-n'])
def _tag(name, message, prefix='', suffix=''):
"""Create a git tag.
Parameters
----------
name : str
The name of the tag to create
message : str
A short message about the tag
prefix : str
A prefix to add to the name
suffix : str
A suffix to add to the name
Returns
-------
None
"""
name = prefix + name + suffix
subprocess.call(['git', 'tag', '-a', name, '-m', message])
def _push_tags():
"""Run `git push --follow-tags`."""
subprocess.call(['git', 'push', '--follow-tags'])
@version.register('bump')
@arg('part', nargs='?', default='patch')
def bump(part):
"""Bump the version number."""
from unb_cli import version
version.bump_file(current_project().version_file_path, part, '0.0.0')
@version.register('tag')
@arg('message', nargs='?', default='',
help='Annotate the tag with a message.')
@arg('--name', nargs='?', default='',
help='Specify a tag name explicitly.')
@arg('--prefix', nargs='?', default='',
help="""A prefix to add to the name.
This is most useful when the name parameter is omitted. For example, if
the current version number were 1.2.3, ``unb version tag --prefix=v``
would produce a tag named ``v1.2.3``.""")
@arg('--suffix', nargs='?', default='',
help="""A suffix to add to the name.
This is most useful when the name parameter is omitted. For example, if
the current version number were 1.2.3, ``unb version tag --suffix=-dev``
would produce a tag named ``1.2.3-dev``.""")
def tag(message, name, prefix, suffix):
"""Create a git tag.
If the tag name is not given explicitly, its name will equal the contents of
the file project_root/VERSION.
"""
if not name:
name = _get_version()
_tag(name, message, prefix, suffix)
@version.register('push-tags')
def push_tags():
"""Push and follow tags. (`git push --follow-tags`)"""
_push_tags()
@version.register('list-tags')
def list_tags():
"""List git tags."""
_list_tags()
@version.register('version')
def get_version():
"""Get the version number of the current project."""
print _get_version()
| [
11748,
28686,
198,
11748,
850,
14681,
198,
198,
6738,
537,
4105,
1330,
1822,
11,
9455,
198,
198,
6738,
764,
1330,
1459,
62,
16302,
628,
198,
9641,
796,
9455,
7,
198,
220,
220,
220,
1438,
11639,
9641,
3256,
198,
220,
220,
220,
3670,
... | 2.788284 | 973 |
import scrapy
from scrapy.selector import Selector
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from crawlers.items import Zgka8Item
from scrapy.http import TextResponse,FormRequest,Request
import json
| [
11748,
15881,
88,
198,
6738,
15881,
88,
13,
19738,
273,
1330,
9683,
273,
198,
6738,
15881,
88,
13,
2815,
365,
742,
974,
669,
1330,
7502,
11627,
40450,
198,
6738,
15881,
88,
13,
2777,
4157,
1330,
327,
13132,
41294,
11,
14330,
198,
6738... | 3.571429 | 70 |
"""
Week 4, Day 4: Uncrossed Lines
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
A[i] == B[j];
The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting
lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines,
because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Notes:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
Hint:
Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:]
[the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as
a recursion?
Remark:
The given solution comes from
https://massivealgorithms.blogspot.com/2019/06/leetcode-1035-uncrossed-lines.html
The approach is, to find the longest sequence of numbers that is common to both integer lists,
by applying a two dimensional memoization (the DP matrix.)
"""
from typing import List
if __name__ == '__main__':
o = Solution()
A = [1, 4, 2]
B = [1, 2, 4]
expected = 2
print(o.maxUncrossedLines(A, B) == expected)
A = [2, 5, 1, 2, 5]
B = [10, 5, 2, 1, 5, 2]
expected = 3
print(o.maxUncrossedLines(A, B) == expected)
A = [1, 3, 7, 1, 7, 5]
B = [1, 9, 2, 5, 1]
expected = 2
print(o.maxUncrossedLines(A, B) == expected)
# last line of code
| [
37811,
198,
20916,
604,
11,
3596,
604,
25,
791,
19692,
276,
26299,
198,
198,
1135,
3551,
262,
37014,
286,
317,
290,
347,
357,
259,
262,
1502,
484,
389,
1813,
8,
319,
734,
4553,
16021,
3951,
13,
198,
198,
3844,
11,
356,
743,
3197,
... | 2.55599 | 768 |
#!/bin/python
# Priority queue that allows updating priorities
# Todo: don't do busy waiting...
import time
from heapq import * # Basic heap implementation
import Queue # Need to pull in exceptions
from tools import * # For RWLock
class DPQueue(object):
"""Thread-safe Priority queue that can update priorities"""
if __name__ == "__main__":
# Test...
print "Creating..."
dpq = DPQueue(maxsize = 5, prio = lambda e: e)
print "Empty:", dpq.empty()
print "Putting..."
dpq.put(1)
print "Empty:", dpq.empty()
dpq.put(5)
dpq.put(3)
dpq.put(2)
print "Full:", dpq.full()
dpq.put(4)
print "Full:", dpq.full()
print "Reprioritize..."
dpq.prio = lambda e: -e
dpq.reprioritize()
print "Getting..."
e = dpq.get()
print "Got:", e
dpq.task_done()
print "Full:", dpq.full()
e = dpq.get()
print "Got:", e
dpq.task_done()
e = dpq.get()
print "Got:", e
dpq.task_done()
e = dpq.get()
print "Got:", e
dpq.task_done()
print "Empty:", dpq.empty()
e = dpq.get()
print "Got:", e
dpq.task_done()
print "Empty:", dpq.empty()
print "Join..."
dpq.join()
| [
2,
48443,
8800,
14,
29412,
198,
198,
2,
34416,
16834,
326,
3578,
19698,
15369,
198,
198,
2,
309,
24313,
25,
836,
470,
466,
8179,
4953,
986,
628,
198,
11748,
640,
198,
6738,
24575,
80,
1330,
1635,
1303,
14392,
24575,
7822,
198,
11748,
... | 1.959641 | 669 |
import requests
from bs4 import BeautifulSoup as BS
params = {"p1":"108001","p2":"108136","l":"0","type":"5"}
res = requests.post("http://www.9800.com.tw/trend.asp",data = params)
lottery_page = BS(res.text,"html.parser")
lottery_info = lottery_page.select("tbody")[4].select("td")
data = []
for i in range(len(lottery_info)):
if lottery_info[i].text.replace("-","").isdigit():
data.append(lottery_info[i].text)
lottery_infos = []
count = 1
for i in range(0,len(data),7):
lottery_infos.append(
{"id":count,"period":int(data[i]),"period_date":data[i+1],
"num1":data[i+2],"num2":data[i+3],"num3":data[i+4],"num4":data[i+5],"num5":data[i+6]
})
count +=1
# I just suffered from an issue.
# When I was spiding the lottery web,the fetched text was not correct.
# Then,about two hours later,I finally found the solution.
# It's the lxml problem.You need use html.parser to decoding the page. | [
11748,
7007,
201,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
355,
24218,
201,
198,
201,
198,
37266,
796,
19779,
79,
16,
2404,
940,
7410,
16,
2430,
79,
17,
2404,
15711,
20809,
2430,
75,
2404,
15,
2430,
4906,
2404,
20,
20662,
201... | 2.268623 | 443 |