text stringlengths 0 1.05M | meta dict |
|---|---|
"""A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example,
the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this
sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum
of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can
be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis
even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is
less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers."""
from math import sqrt
def find_divisor(n):
for i in xrange(1, int(sqrt(n)+1)):
if n%i == 0:
yield i
if i is not n / i and i is not 1:
yield n/i
def is_abundant(n):
if sum(find_divisor(n)) > n:
return True
return False
abundant_numbers = []
for x in range(12, 28124):
if is_abundant(x):
abundant_numbers.append(x)
sum_of_two_abundant_numbers = [False]*28124
for id, x in enumerate(abundant_numbers):
for y in abundant_numbers[id:]:
if x + y < 28124:
sum_of_two_abundant_numbers[x+y] = True
sum_of_non_abundant = 0
for id, x in enumerate(sum_of_two_abundant_numbers):
if not x and id < 28124:
sum_of_non_abundant += id
print sum_of_non_abundant | {
"repo_name": "mmax5/project-euler",
"path": "Problem 23.py",
"copies": "1",
"size": "1712",
"license": "apache-2.0",
"hash": 2441513419158981000,
"line_mean": 36.2391304348,
"line_max": 117,
"alpha_frac": 0.6857476636,
"autogenerated": false,
"ratio": 3.465587044534413,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9623999860625072,
"avg_score": 0.005466969501868027,
"num_lines": 46
} |
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the
# proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
#
# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
#
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant
# numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two
# abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest
# number that cannot be expressed as the sum of two abundant numbers is less than this limit.
#
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
# ans = 4179871
import time
#########################################################
MIN_ABUNDANT = 12
ABUNDANT_LIMIT = 28123
abundant_list = []
abundant_sums_list = []
#########################################################
# Fill the abundant_list and primes_list lists
#########################################################
def generate_lists():
for i in range(1, ABUNDANT_LIMIT + 1):
sum = 0
for div in range(1, int(i/2)+1): #int(math.sqrt(i)) + 1
if(i % div == 0):
sum += div
if(sum > i):
abundant_list.append(i)
#########################################################
def find_all_sums():
global abundant_sums_list
for i in abundant_list:
for j in abundant_list:
temp_sum = i + j
if(temp_sum <= ABUNDANT_LIMIT):
abundant_sums_list.append(temp_sum)
#########################################################
def euler_problem_23():
print "Problem 23:"
generate_lists()
find_all_sums()
abundant_sums_set = set(abundant_sums_list)
full_set = set(range(1, ABUNDANT_LIMIT+1))
final_set = full_set - abundant_sums_set
ans = sum(list(final_set))
print ans
#########################################################
start_time = time.time()
euler_problem_23()
end_time = time.time()
print "total calculation time is ", (end_time - start_time), " [Sec]"
| {
"repo_name": "shultzd/Euler",
"path": "problem_23.py",
"copies": "1",
"size": "2444",
"license": "cc0-1.0",
"hash": -4025699234838310000,
"line_mean": 34.4202898551,
"line_max": 132,
"alpha_frac": 0.55400982,
"autogenerated": false,
"ratio": 3.9355877616747184,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4989597581674718,
"avg_score": null,
"num_lines": null
} |
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
#from itertools import filterfalse, takewhile
from Utils import sumFactors
def is_abundant(n):
factorSum = sumFactors(n)
if factorSum > n:
return True
else:
return False
limit = 28123
abundants = set(filter(lambda x: is_abundant(x), range(11, limit)))
non_append_sums = 0
for n in range(1, limit):
if not any((n-a in abundants) for a in abundants):
non_append_sums += n
print(non_append_sums)
#4179871
#not 1,973,502 or 395,465,626
# abundants = list(filter(lambda x: is_abundant(x), range(1, limit)))
# possible_sums = []
# for i in range(len(abundants)):
# for j in range(i, len(abundants)):
# possible_sums.append(abundants[i]+abundants[j])
# possible_sums.sort()
# current = possible_sums[0]
# final_sums = []
# i = 0
# while current < limit:
# final_sums.append(current)
# i += 1
# current = possible_sums[i]
# #final_sums = takewhile(lambda x: x < limit, possible_sums)
# non_append_sums = 0
# for i in range(1, limit):
# if i not in final_sums:
# non_append_sums += i
# print(non_append_sums)
# # current = 0
# for i in range(len(abundants)):
# for j in range(i, len(abundants)):
# possible_sums.append(abundants[i]+abundants[j])
# final_sums = takewhile(lambda x: x < 28135, possible_sums)
# # now have all possible sums
# nums = list(filterfalse(lambda x: x in final_sums, range(1, limit)))
# non_append_sums = 0
# for i in nums:
# non_append_sums += i
# print(non_append_sums)
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#solution from stackoverflow:
# def d(n):
# sum = 1
# t = sqrt(n)
# for i in range(2, int(t)+1):
# if n % i == 0:
# sum += i + n//i
# if t == int(t):
# sum -= t
# return sum
# limit = 20162
# sum = 0
# abn = set()
# for n in range(1, limit):
# if is_abundant(n):#if d(n) > n:
# abn.add(n)
# if not any((n-a in abn) for a in abn):
# sum += n
# print(sum)
#4179871
| {
"repo_name": "ledbutter/ProjectEulerPython",
"path": "Problem23.py",
"copies": "1",
"size": "2922",
"license": "mit",
"hash": -1915235241607143400,
"line_mean": 28.4583333333,
"line_max": 478,
"alpha_frac": 0.6413415469,
"autogenerated": false,
"ratio": 2.9396378269617705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8573733246136328,
"avg_score": 0.10144922554508844,
"num_lines": 96
} |
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
# For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means
# that 28 is a perfect number.
# A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant
# if this sum exceeds n.
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written
# as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers
# greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot
# be reduced any further by analysis even though it is known that the greatest number that cannot be expressed
# as the sum of two abundant numbers is less than this limit.
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
from common.math_util import is_abundant
abundants = [x for x in xrange(12, 28123) if is_abundant(x)]
# print abundants
possible_numbers = range(1, 28123)
for a1 in abundants:
for a2 in abundants:
a_sum = a1 + a2
if a_sum in possible_numbers:
possible_numbers.remove(a_sum)
print "Solution: {}".format(sum(possible_numbers))
| {
"repo_name": "doctoryes/project_euler",
"path": "prob23.py",
"copies": "1",
"size": "1319",
"license": "mit",
"hash": -4871649984462744000,
"line_mean": 49.7307692308,
"line_max": 110,
"alpha_frac": 0.7300985595,
"autogenerated": false,
"ratio": 3.633608815426997,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48637073749269977,
"avg_score": null,
"num_lines": null
} |
# A perfect number is a number for which the sum of its proper divisors is
# exactly equal to the number. For example, the sum of the proper divisors
# of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect
# number.
# A number n is called deficient if the sum of its proper divisors is less
# than n and it is called abundant if this sum exceeds n.
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
# number that can be written as the sum of two abundant numbers is 24. By
# mathematical analysis, it can be shown that all integers greater than
# 28123 can be written as the sum of two abundant numbers. However, this
# upper limit cannot be reduced any further by analysis even though it is
# known that the greatest number that cannot be expressed as the sum of
# two abundant numbers is less than this limit.
# Find the sum of all the positive integers which cannot be written as
# the sum of two abundant numbers.
from math import sqrt
def is_abundant(num):
ret = 1
for p in range(2, int(sqrt(num)) + 1):
if num % p == 0:
ret += p
if num / p <> p:
ret += num / p
return ret > num
abundant = set(filter(lambda x: is_abundant(x), range(12, 28123)))
def is_abundant_sum(num):
for i in abundant:
if num - i < 0:
break
if num - i in abundant:
return True
return False
print sum(filter(lambda x: not is_abundant_sum(x), range(1, 28123)))
| {
"repo_name": "cloudzfy/euler",
"path": "src/23.py",
"copies": "1",
"size": "1418",
"license": "mit",
"hash": 5083962561342053000,
"line_mean": 33.5853658537,
"line_max": 77,
"alpha_frac": 0.7038081805,
"autogenerated": false,
"ratio": 3.3053613053613056,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4509169485861306,
"avg_score": null,
"num_lines": null
} |
"""A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors of 28
would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A
number n is called deficient if the sum of its proper divisors is less than n
and it is called abundant if this sum exceeds n. As 12 is the smallest abundant
number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the
sum of two abundant numbers is 24. By mathematical analysis, it can be shown
that all integers greater than 28123 can be written as the sum of two abundant
numbers. However, this upper limit cannot be reduced any further by analysis
even though it is known that the greatest number that cannot be expressed as
the sum of two abundant numbers is less than this limit. Find the sum of all
the positive integers which cannot be written as the sum of two abundant
numbers."""
from nose.tools import *
import itertools
import math
def solve_p023():
abundants = list(filter(is_abundant, range(1,28124)))
abundant_combos = itertools.combinations_with_replacement(abundants, 2)
abundant_sums = {sum(combo) for combo in abundant_combos}
return sum([i for i in range(1, 28124) if i not in abundant_sums])
def find_divisors(num):
divisors = {i for i in range(1, int(math.sqrt(num)+1)) if num%i == 0}
divisors.update({num/divisor for divisor in divisors})
divisors.discard(num)
return divisors
def is_abundant(num):
divisors = find_divisors(num)
return sum(divisors) > num
def test_28_is_not_abundant():
assert_false(is_abundant(28))
def test_8_is_not_abundant():
assert_false(is_abundant(8))
def test_12_is_abundant():
assert_true(is_abundant(12))
if __name__ == '__main__':
print(solve_p023())
| {
"repo_name": "piohhmy/euler",
"path": "p023.py",
"copies": "1",
"size": "1823",
"license": "mit",
"hash": -5813735864642950000,
"line_mean": 37,
"line_max": 79,
"alpha_frac": 0.7229840922,
"autogenerated": false,
"ratio": 3.3821892393320963,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46051733315320964,
"avg_score": null,
"num_lines": null
} |
"""A perfect power is a classification of positive integers:
In mathematics, a perfect power is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that mk = n.
Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair m and k with mk = n as a proof. Otherwise return Nothing, Nil, null, None or your language's equivalent.
Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it.
Examples
isPP(4) => [2,2]
isPP(9) => [3,2]
isPP(5) => None"""
def isPP(n):
from math import sqrt
if sqrt(n).is_integer():
return [sqrt(n), 2]
for i in range(2, n+1):
for x in range(2, n+1):
if i ** x == n:
return [i, x]
elif i ** x > n:
break
return None | {
"repo_name": "Copenbacon/code-katas",
"path": "katas/perfectpower.py",
"copies": "1",
"size": "1075",
"license": "mit",
"hash": -4551573001248893000,
"line_mean": 43.8333333333,
"line_max": 229,
"alpha_frac": 0.6465116279,
"autogenerated": false,
"ratio": 3.4455128205128207,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9559294289916525,
"avg_score": 0.006546031699259051,
"num_lines": 24
} |
"""A performance profiling suite for a variety of SQLAlchemy use cases.
Each suite focuses on a specific use case with a particular performance
profile and associated implications:
* bulk inserts
* individual inserts, with or without transactions
* fetching large numbers of rows
* running lots of short queries
All suites include a variety of use patterns illustrating both Core
and ORM use, and are generally sorted in order of performance from worst
to greatest, inversely based on amount of functionality provided by SQLAlchemy,
greatest to least (these two things generally correspond perfectly).
A command line tool is presented at the package level which allows
individual suites to be run::
$ python -m examples.performance --help
usage: python -m examples.performance [-h] [--test TEST] [--dburl DBURL]
[--num NUM] [--profile] [--dump]
[--echo]
{bulk_inserts,large_resultsets,single_inserts}
positional arguments:
{bulk_inserts,large_resultsets,single_inserts}
suite to run
optional arguments:
-h, --help show this help message and exit
--test TEST run specific test name
--dburl DBURL database URL, default sqlite:///profile.db
--num NUM Number of iterations/items/etc for tests;
default is module-specific
--profile run profiling and dump call counts
--dump dump full call profile (implies --profile)
--echo Echo SQL output
An example run looks like::
$ python -m examples.performance bulk_inserts
Or with options::
$ python -m examples.performance bulk_inserts \\
--dburl mysql+mysqldb://scott:tiger@localhost/test \\
--profile --num 1000
.. seealso::
:ref:`faq_how_to_profile`
File Listing
-------------
.. autosource::
Running all tests with time
---------------------------
This is the default form of run::
$ python -m examples.performance single_inserts
Tests to run: test_orm_commit, test_bulk_save,
test_bulk_insert_dictionaries, test_core,
test_core_query_caching, test_dbapi_raw_w_connect,
test_dbapi_raw_w_pool
test_orm_commit : Individual INSERT/COMMIT pairs via the
ORM (10000 iterations); total time 13.690218 sec
test_bulk_save : Individual INSERT/COMMIT pairs using
the "bulk" API (10000 iterations); total time 11.290371 sec
test_bulk_insert_dictionaries : Individual INSERT/COMMIT pairs using
the "bulk" API with dictionaries (10000 iterations);
total time 10.814626 sec
test_core : Individual INSERT/COMMIT pairs using Core.
(10000 iterations); total time 9.665620 sec
test_core_query_caching : Individual INSERT/COMMIT pairs using Core
with query caching (10000 iterations); total time 9.209010 sec
test_dbapi_raw_w_connect : Individual INSERT/COMMIT pairs w/ DBAPI +
connection each time (10000 iterations); total time 9.551103 sec
test_dbapi_raw_w_pool : Individual INSERT/COMMIT pairs w/ DBAPI +
connection pool (10000 iterations); total time 8.001813 sec
Dumping Profiles for Individual Tests
--------------------------------------
A Python profile output can be dumped for all tests, or more commonly
individual tests::
$ python -m examples.performance single_inserts --test test_core --num 1000 --dump
Tests to run: test_core
test_core : Individual INSERT/COMMIT pairs using Core. (1000 iterations); total fn calls 186109
186109 function calls (186102 primitive calls) in 1.089 seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1000 0.634 0.001 0.634 0.001 {method 'commit' of 'sqlite3.Connection' objects}
1000 0.154 0.000 0.154 0.000 {method 'execute' of 'sqlite3.Cursor' objects}
1000 0.021 0.000 0.074 0.000 /Users/classic/dev/sqlalchemy/lib/sqlalchemy/sql/compiler.py:1950(_get_colparams)
1000 0.015 0.000 0.034 0.000 /Users/classic/dev/sqlalchemy/lib/sqlalchemy/engine/default.py:503(_init_compiled)
1 0.012 0.012 1.091 1.091 examples/performance/single_inserts.py:79(test_core)
...
.. _examples_profiling_writeyourown:
Writing your Own Suites
-----------------------
The profiler suite system is extensible, and can be applied to your own set
of tests. This is a valuable technique to use in deciding upon the proper
approach for some performance-critical set of routines. For example,
if we wanted to profile the difference between several kinds of loading,
we can create a file ``test_loads.py``, with the following content::
from examples.performance import Profiler
from sqlalchemy import Integer, Column, create_engine, ForeignKey
from sqlalchemy.orm import relationship, joinedload, subqueryload, Session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = None
session = None
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
# Init with name of file, default number of items
Profiler.init("test_loads", 1000)
@Profiler.setup_once
def setup_once(dburl, echo, num):
"setup once. create an engine, insert fixture data"
global engine
engine = create_engine(dburl, echo=echo)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
sess = Session(engine)
sess.add_all([
Parent(children=[Child() for j in range(100)])
for i in range(num)
])
sess.commit()
@Profiler.setup
def setup(dburl, echo, num):
"setup per test. create a new Session."
global session
session = Session(engine)
# pre-connect so this part isn't profiled (if we choose)
session.connection()
@Profiler.profile
def test_lazyload(n):
"load everything, no eager loading."
for parent in session.query(Parent):
parent.children
@Profiler.profile
def test_joinedload(n):
"load everything, joined eager loading."
for parent in session.query(Parent).options(joinedload("children")):
parent.children
@Profiler.profile
def test_subqueryload(n):
"load everything, subquery eager loading."
for parent in session.query(Parent).options(subqueryload("children")):
parent.children
if __name__ == '__main__':
Profiler.main()
We can run our new script directly::
$ python test_loads.py --dburl postgresql+psycopg2://scott:tiger@localhost/test
Running setup once...
Tests to run: test_lazyload, test_joinedload, test_subqueryload
test_lazyload : load everything, no eager loading. (1000 iterations); total time 11.971159 sec
test_joinedload : load everything, joined eager loading. (1000 iterations); total time 2.754592 sec
test_subqueryload : load everything, subquery eager loading. (1000 iterations); total time 2.977696 sec
""" # noqa
import argparse
import cProfile
import gc
import os
import pstats
import re
import sys
import time
class Profiler(object):
tests = []
_setup = None
_setup_once = None
name = None
num = 0
def __init__(self, options):
self.test = options.test
self.dburl = options.dburl
self.profile = options.profile
self.dump = options.dump
self.raw = options.raw
self.callers = options.callers
self.num = options.num
self.echo = options.echo
self.sort = options.sort
self.gc = options.gc
self.stats = []
@classmethod
def init(cls, name, num):
cls.name = name
cls.num = num
@classmethod
def profile(cls, fn):
if cls.name is None:
raise ValueError(
"Need to call Profile.init(<suitename>, <default_num>) first."
)
cls.tests.append(fn)
return fn
@classmethod
def setup(cls, fn):
if cls._setup is not None:
raise ValueError("setup function already set to %s" % cls._setup)
cls._setup = staticmethod(fn)
return fn
@classmethod
def setup_once(cls, fn):
if cls._setup_once is not None:
raise ValueError(
"setup_once function already set to %s" % cls._setup_once
)
cls._setup_once = staticmethod(fn)
return fn
def run(self):
if self.test:
tests = [fn for fn in self.tests if fn.__name__ == self.test]
if not tests:
raise ValueError("No such test: %s" % self.test)
else:
tests = self.tests
if self._setup_once:
print("Running setup once...")
self._setup_once(self.dburl, self.echo, self.num)
print("Tests to run: %s" % ", ".join([t.__name__ for t in tests]))
for test in tests:
self._run_test(test)
self.stats[-1].report()
def _run_with_profile(self, fn, sort):
pr = cProfile.Profile()
pr.enable()
try:
result = fn(self.num)
finally:
pr.disable()
stats = pstats.Stats(pr)
self.stats.append(TestResult(self, fn, stats=stats, sort=sort))
return result
def _run_with_time(self, fn):
now = time.time()
try:
return fn(self.num)
finally:
total = time.time() - now
self.stats.append(TestResult(self, fn, total_time=total))
def _run_test(self, fn):
if self._setup:
self._setup(self.dburl, self.echo, self.num)
if self.gc:
# gc.set_debug(gc.DEBUG_COLLECTABLE)
gc.set_debug(gc.DEBUG_STATS)
if self.profile or self.dump:
self._run_with_profile(fn, self.sort)
else:
self._run_with_time(fn)
if self.gc:
gc.set_debug(0)
@classmethod
def main(cls):
parser = argparse.ArgumentParser("python -m examples.performance")
if cls.name is None:
parser.add_argument(
"name", choices=cls._suite_names(), help="suite to run"
)
if len(sys.argv) > 1:
potential_name = sys.argv[1]
try:
__import__(__name__ + "." + potential_name)
except ImportError:
pass
parser.add_argument("--test", type=str, help="run specific test name")
parser.add_argument(
"--dburl",
type=str,
default="sqlite:///profile.db",
help="database URL, default sqlite:///profile.db",
)
parser.add_argument(
"--num",
type=int,
default=cls.num,
help="Number of iterations/items/etc for tests; "
"default is %d module-specific" % cls.num,
)
parser.add_argument(
"--profile",
action="store_true",
help="run profiling and dump call counts",
)
parser.add_argument(
"--sort",
type=str,
default="cumulative",
help="profiling sort, defaults to cumulative",
)
parser.add_argument(
"--dump",
action="store_true",
help="dump full call profile (implies --profile)",
)
parser.add_argument(
"--raw",
type=str,
help="dump raw profile data to file (implies --profile)",
)
parser.add_argument(
"--callers",
action="store_true",
help="print callers as well (implies --dump)",
)
parser.add_argument(
"--gc", action="store_true", help="turn on GC debug stats"
)
parser.add_argument(
"--echo", action="store_true", help="Echo SQL output"
)
args = parser.parse_args()
args.dump = args.dump or args.callers
args.profile = args.profile or args.dump or args.raw
if cls.name is None:
__import__(__name__ + "." + args.name)
Profiler(args).run()
@classmethod
def _suite_names(cls):
suites = []
for file_ in os.listdir(os.path.dirname(__file__)):
match = re.match(r"^([a-z].*).py$", file_)
if match:
suites.append(match.group(1))
return suites
class TestResult(object):
def __init__(
self, profile, test, stats=None, total_time=None, sort="cumulative"
):
self.profile = profile
self.test = test
self.stats = stats
self.total_time = total_time
self.sort = sort
def report(self):
print(self._summary())
if self.profile.profile:
self.report_stats()
def _summary(self):
summary = "%s : %s (%d iterations)" % (
self.test.__name__,
self.test.__doc__,
self.profile.num,
)
if self.total_time:
summary += "; total time %f sec" % self.total_time
if self.stats:
summary += "; total fn calls %d" % self.stats.total_calls
return summary
def report_stats(self):
if self.profile.dump:
self._dump(self.sort)
elif self.profile.raw:
self._dump_raw()
def _dump(self, sort):
self.stats.sort_stats(*re.split(r"[ ,]", self.sort))
self.stats.print_stats()
if self.profile.callers:
self.stats.print_callers()
def _dump_raw(self):
self.stats.dump_stats(self.profile.raw)
| {
"repo_name": "monetate/sqlalchemy",
"path": "examples/performance/__init__.py",
"copies": "3",
"size": "14210",
"license": "mit",
"hash": -3862619600632018400,
"line_mean": 31.0767494357,
"line_max": 132,
"alpha_frac": 0.587825475,
"autogenerated": false,
"ratio": 4.104563835932987,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 443
} |
# A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
# Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
# Below are the permutations of string ABC.
# ABC, ACB, BAC, BCA, CAB, CBA
# Here is a solution using backtracking.
# From: http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
#Swap values for elements in index i and j of a list
def swap(list, i, j):
t = list[i]
list[i] = list[j]
list[j] = t
####
# Function to print permutations of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
####
def permunate(list,i,n):
if(i==n):
print(*list, sep='') #upack char list into string and print it
else:
for j in range(i, n+1):
# print("i:"+ str(i) + " j: "+ str(j))
swap(list,i,j)
permunate(list,i+1,n)
swap(list,i,j)
l_test = list("abcd")
# swap(l1,0,1)
# print(l1)
# swap(l1,0,1)
# print(l1)
print("----start-----")
permunate(l_test,0,len(l_test)-1)
print("----end-----")
| {
"repo_name": "nakayamaqs/PythonModule",
"path": "Algorithm/permutation.py",
"copies": "2",
"size": "1264",
"license": "mit",
"hash": 8014354477882882000,
"line_mean": 31.2051282051,
"line_max": 209,
"alpha_frac": 0.6313694268,
"autogenerated": false,
"ratio": 2.835214446952596,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.939421500615907,
"avg_score": 0.014473773518705336,
"num_lines": 39
} |
# A permutation of a string s is a string t in which each character of s appears
# once and only once in t
# s = aab, then t = aba is a permutation.
# s = xyz, then t = zxy is a permutation.
#
# Problem:
# given a string, construct a list of all possible permutations of that string.
#
# Example:
# given ABC we want the list
# ['ABC','ACB','BAC','BCA','CAB','CBA']
#
# This reminds you of the recursive defn of factorial fact(n) is defined in terms
# of smaller factorials this suggests that the list of all permutations could be
# defined in terms of smaller permutations.
#
# To find all permutations of n objects:
# For a given object
# Find all permutations of n-1 objects
# Insert the given object into all possible positions
# of each permutation of n-1 objects
#
# Example: given ABC
# Find all permutations of BC
# BC and CB
# Insert the remaining object A into all possible positions
# marked by a *, in each of the permutations of BC
# *B*C* and *C*B*
def insert_at_all_positions(c, t):
l = []
for j in range(len(t)+1): # + 1 for the rightmost spot
l.append(t[:j]+c+t[j:])
return l
# let us try this out in the example
insert_at_all_positions('A', 'BC') # ['ABC', 'BAC', 'BCA']
insert_at_all_positions('A', 'CB') # ['ACB', 'CAB', 'CBA']
# now we have to put together all of these solutions
def permutations(s):
result = []
if len(s) == 1:
result.append(s)
return result
else:
first = s[0]
rest = s[1:]
simpler = permutations(rest)
for p in simpler:
additions = insert_at_all_positions(first,p)
result = result + additions
return result
| {
"repo_name": "sshastry/intro-to-computing-103",
"path": "src/09-permutations.py",
"copies": "1",
"size": "1668",
"license": "mit",
"hash": 903702428301336000,
"line_mean": 29.3272727273,
"line_max": 81,
"alpha_frac": 0.6510791367,
"autogenerated": false,
"ratio": 3.3971486761710796,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45482278128710796,
"avg_score": null,
"num_lines": null
} |
# A persistent cache of pre-compiled formulas
import os
import stat
import cPickle
import hashlib
class TimeStampedObject:
"An object and the last time it was updated"
def __init__(self,obj,time,file=None):
self.time = time
self.obj = obj
self.cache_file = file
class T:
def __init__(self,dir="~/.gnofract4d-cache"):
self.dir = os.path.expanduser(dir)
self.files = {}
def init(self):
if not os.path.exists(self.dir):
os.makedirs(self.dir)
self._loadHash()
def _indexName(self):
return os.path.join(self.dir,"index_v00.pkl")
def _loadHash(self):
if os.path.exists(self._indexName()):
self.files = self.loadPickledFile(self._indexName())
def save(self):
self.createPickledFile(self._indexName(), self.files)
def clear(self):
for f in os.listdir(self.dir):
try:
os.remove(os.path.join(self.dir,f))
except:
pass
def makefilename(self,name,ext):
return os.path.join(self.dir, "fract4d_%s%s" % (name, ext))
def hashcode(self,s,*extras):
hash = hashlib.md5(s)
for x in extras:
hash.update(x)
return hash.hexdigest()
def makePickleName(self,s,*extras):
name = self.hashcode(s,*extras) +".pkl"
fullname = os.path.join(self.dir, name)
return fullname
def createPickledFile(self,file,contents):
f = open(file,"wb")
try:
cPickle.dump(contents,f,True)
#print "created %s" % file
finally:
f.close()
def loadPickledFile(self,file):
f = open(file, "rb")
try:
contents = cPickle.load(f)
finally:
f.close()
return contents
def getcontents(self,file,parser):
mtime = os.stat(file)[stat.ST_MTIME]
tso = self.files.get(file,None)
if tso:
if tso.time == mtime:
return tso.obj
val = parser(open(file))
hashname = self.makePickleName(file)
#self.createPickledFile(hashname,val)
self.files[file] = TimeStampedObject(val,mtime,hashname)
return val
| {
"repo_name": "ericchill/gnofract4d",
"path": "fract4d/cache.py",
"copies": "1",
"size": "2353",
"license": "bsd-3-clause",
"hash": 8465099323660242000,
"line_mean": 25.7386363636,
"line_max": 67,
"alpha_frac": 0.5397365066,
"autogenerated": false,
"ratio": 3.729001584786054,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47687380913860544,
"avg_score": null,
"num_lines": null
} |
"""Aperture Load Balancer.
Based on work from finagle's aperture load balancer.
See https://github.com/twitter/finagle/blob/master/finagle-core/src/main/scala/com/twitter/finagle/loadbalancer/Aperture.scala
The aperture balancer attempts to keep the average load going into the underlying
server set between a load band (by default .5 <= load <= 2.
Load is determined via an ema of load over a smoothing window (5 seconds).
The load average is essentially the average number of concurrent requests each
node in the balancer is handling.
"""
import random
from .heap import HeapBalancerSink
from ..asynchronous import AsyncResult
from ..constants import (ChannelState, SinkProperties, SinkRole)
from ..sink import SinkProvider
from ..timer_queue import LOW_RESOLUTION_TIMER_QUEUE, LOW_RESOLUTION_TIME_SOURCE
from ..varz import (
Ema,
Gauge,
MonoClock,
Source,
VarzBase
)
class ApertureBalancerSink(HeapBalancerSink):
"""A load balancer that keeps an aperture adjusted by a load average."""
class ApertureVarz(VarzBase):
"""
idle - The number of nodes idle in the pool (not in the aperture)
active - The number of nodes active in the pool (in the aperture)
load_average - The most recently calculated load average.
"""
_VARZ_BASE_NAME = 'scales.loadbalancer.Aperture'
_VARZ = {
'idle': Gauge,
'active': Gauge,
'load_average': Gauge
}
def __init__(self, next_provider, sink_properties, global_properties):
self._idle_endpoints = set()
self._total = 0
self._ema = Ema(5)
self._time = MonoClock()
self._min_size = sink_properties.min_size
self._max_size = sink_properties.max_size
self._min_load = sink_properties.min_load
self._max_load = sink_properties.max_load
self._jitter_min = sink_properties.jitter_min_sec
self._jitter_max = sink_properties.jitter_max_sec
service_name = global_properties[SinkProperties.Label]
self.__varz = self.ApertureVarz(Source(service=service_name))
self._pending_endpoints = set()
super(ApertureBalancerSink, self).__init__(next_provider, sink_properties, global_properties)
if self._jitter_min > 0:
self._ScheduleNextJitter()
def _UpdateSizeVarz(self):
"""Update active and idle varz"""
self.__varz.active(self._size)
self.__varz.idle(len(self._idle_endpoints))
def _AddSink(self, endpoint, sink_factory):
"""Invoked when a node is added to the underlying server set.
If the number of healthy nodes is < the minimum aperture size, the node
will be added to the aperture, otherwise it will be added to the idle channel
list.
Args:
endpoint - The endpoint being added to the server set.
sink_factory - A callable used to create a sink for the endpoint.
"""
num_healthy = len([c for c in self._heap[1:] if c.channel.is_open])
if num_healthy < self._min_size:
super(ApertureBalancerSink, self)._AddSink(endpoint, sink_factory)
else:
self._idle_endpoints.add(endpoint)
self._UpdateSizeVarz()
def _RemoveSink(self, endpoint):
"""Invoked when a node is removed from the underlying server set.
If the node is currently active, it is removed from the aperture and replaced
by an idle node (if one is available). Otherwise, it is simply discarded.
Args:
endpoint - The endpoint being removed from the server set.
"""
removed = super(ApertureBalancerSink, self)._RemoveSink(endpoint)
if removed:
self._TryExpandAperture()
if endpoint in self._idle_endpoints:
self._idle_endpoints.discard(endpoint)
self._UpdateSizeVarz()
def _TryExpandAperture(self, leave_pending=False):
"""Attempt to expand the aperture. By calling this it's assumed the aperture
needs to be expanded.
The aperture can be expanded if there are idle sinks available.
"""
endpoints = list(self._idle_endpoints)
added_node = None
new_endpoint = None
if endpoints:
new_endpoint = random.choice(endpoints)
self._idle_endpoints.discard(new_endpoint)
self._log.debug('Expanding aperture to include %s.' % str(new_endpoint))
new_sink = self._servers[new_endpoint]
self._pending_endpoints.add(new_endpoint)
added_node = super(ApertureBalancerSink, self)._AddSink(new_endpoint, new_sink)
self._UpdateSizeVarz()
if added_node:
if not leave_pending:
added_node.ContinueWith(
lambda ar: self._pending_endpoints.discard(new_endpoint))
return added_node, new_endpoint
else:
return AsyncResult.Complete(), None
def _ContractAperture(self, force=False):
"""Attempt to contract the aperture. By calling this it's assume the aperture
needs to be contracted.
The aperture can be contracted if it's current size is larger than the
min size.
"""
if self._pending_endpoints and not force:
return
num_healthy = len([c for c in self._heap[1:] if c.channel.is_open])
if num_healthy > self._min_size:
least_loaded_endpoint = None
# Scan the heap for any closed endpoints.
for n in self._heap[1:]:
if n.channel.is_closed and n.endpoint not in self._pending_endpoints:
least_loaded_endpoint = n.endpoint
break
if not least_loaded_endpoint:
# Scan the heap for the least-loaded node. This isn't exactly in-order,
# but "close enough"
for n in self._heap[1:]:
if n.endpoint not in self._pending_endpoints:
least_loaded_endpoint = n.endpoint
break
if least_loaded_endpoint:
self._idle_endpoints.add(least_loaded_endpoint)
super(ApertureBalancerSink, self)._RemoveSink(least_loaded_endpoint)
self._log.debug('Contracting aperture to remove %s' % str(least_loaded_endpoint))
self._UpdateSizeVarz()
def _OnNodeDown(self, node):
"""Invoked by the base class when a node is marked down.
In this case, if the downed node is currently in the aperture, we want to
remove if, and then attempt to adjust the aperture.
"""
if node.channel.state != ChannelState.Idle:
ar, _ = self._TryExpandAperture()
return ar
else:
return AsyncResult.Complete()
def _OnGet(self, node):
"""Invoked by the parent class when a node has been retrieved from the pool
and is about to be used.
Increases the load average of the pool, and adjust the aperture if needed.
"""
self._AdjustAperture(1)
def _OnPut(self, node):
"""Invoked by the parent class when a node is being returned to the pool.
Decreases the load average and adjust the aperture if needed.
"""
self._AdjustAperture(-1)
def _ScheduleNextJitter(self):
"""Schedule the aperture to jitter in a random amount of time between
_jitter_min and _jitter_max.
"""
next_jitter = random.randint(self._jitter_min, self._jitter_max)
now = LOW_RESOLUTION_TIME_SOURCE.now
self._next_jitter = LOW_RESOLUTION_TIMER_QUEUE.Schedule(
now + next_jitter, self._Jitter)
def _Jitter(self):
"""Attempt to expand the aperture by one node, and if successful,
contract it by a node (excluding the one that was just added). This is
done asynchronously.
"""
try:
ar, endpoint = self._TryExpandAperture(True)
if endpoint:
try:
ar.wait()
if not ar.exception:
self._ContractAperture(True)
finally:
self._pending_endpoints.discard(endpoint)
finally:
self._ScheduleNextJitter()
def _AdjustAperture(self, amount):
"""Adjusts the load average of the pool, and adjusts the aperture size
if required by the new load average.
Args:
amount - The amount to change the load by. May be +/-1
"""
self._total += amount
avg = self._ema.Update(self._time.Sample(), self._total)
aperture_size = self._size
if aperture_size == 0:
# Essentially infinite load.
aperture_load = self._max_load
else:
aperture_load = avg / aperture_size
self.__varz.load_average(aperture_load)
if (aperture_load >= self._max_load
and self._idle_endpoints
and aperture_size < self._max_size):
self._TryExpandAperture()
elif aperture_load <= self._min_load and aperture_size > self._min_size:
self._ContractAperture()
ApertureBalancerSink.Builder = SinkProvider(
ApertureBalancerSink,
SinkRole.LoadBalancer,
smoothing_window = 5,
min_size = 1,
max_size = 2**31,
min_load = 0.5,
max_load = 2.0,
server_set_provider = None,
jitter_min_sec = 120,
jitter_max_sec = 240)
| {
"repo_name": "steveniemitz/scales",
"path": "scales/loadbalancer/aperture.py",
"copies": "1",
"size": "8636",
"license": "mit",
"hash": -2087603574710530800,
"line_mean": 34.393442623,
"line_max": 126,
"alpha_frac": 0.6779759148,
"autogenerated": false,
"ratio": 3.6255247691015953,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9753652344064783,
"avg_score": 0.009969667967362308,
"num_lines": 244
} |
"""aperturesynth - a tool for registering and combining series of photographs.
Usage:
aperturesynth combine [--no-transform] [--out FILE] [--windows FILE] <images>...
aperturesynth choose_windows <base_image> <window_file>
Options:
-h --help Show this help screen.
--out FILE Optional output file. If not specified the output will
be written to a tiff file with same name as the
baseline image with 'transformed_' prepended. The
output format is chosen by the file extension.
--windows FILE Optional file to specify the coordinates of the windows
to register. This file can be generated using the
choose_windows subcommand, or can be written by hand
as a comma separated value file. Each row of this file
is the integer x,y coordinates of a point in the image.
Consecutive rows are interpreted as the top left and
bottom right of each window.
--no-transform Combine images without transforming first. Useful for
visualising the impact of registration.
The combine command is the main interface for synthesising images: it can be
called with just the images as arguments and will present a GUI to select the
focal regions. The first image passed in will be the baseline image to which
all following images will be matched.
When selecting focal regions using choose_windows or combine with no windows
file specified, consecutive pairs of points *must* indicate the top left and
bottom right of the rectangular focal regions.
"""
import multiprocessing as mp
import numpy as np
from skimage import io, img_as_ubyte, img_as_float
from docopt import docopt
import os.path
from .register import Registrator
from .gui import get_windows
def save_image(image, filename):
"""Saves the image to the given filename, ensuring uint8 output. """
io.imsave(filename, img_as_ubyte(image))
def load_image(image):
"""Loads the given file and converts to float32 format. """
return img_as_float(io.imread(image))
def register_images(image_list, registrator):
"""A generator to register a series of images.
The first image is taken as the baseline and is not transformed.
"""
yield load_image(image_list[0])
for image_file in image_list[1:]:
transformed_image, transform = registrator(load_image(image_file))
# Stub for future operations that examine the transformation
yield transformed_image
def no_transform(image):
"""Pass through the original image without transformation.
Returns a tuple with None to maintain compatability with processes that
evaluate the transform.
"""
return (image, None)
def process_images(image_list, registrator, fusion=None):
"""Apply the given transformation to each listed image and find the mean.
Parameters
----------
image_list: list of filepaths
Image files to be loaded and transformed.
registrator: callable
Returns the desired transformation of a given image.
fusion: callable (optional, default=None)
Returns the fusion of the given images. If not specified the images are
combined by averaging.
Returns
-------
image: MxNx[3]
The combined image as an ndarray.
"""
registered = register_images(image_list, registrator)
if fusion is not None: # Stub for future alternative fusion methods
return fusion(registered)
else:
output = sum(registered)
output /= len(image_list)
return output
def main():
"""Registers and transforms each input image and saves the result."""
args = docopt(__doc__)
if args['choose_windows']:
reference = load_image(args['<base_image>'])
windows = get_windows(reference)
np.savetxt(args['<window_file>'], windows.astype('int'), fmt='%i')
elif args['combine']:
images = args['<images>']
# Is an output filename specified, or do I need to generate my own?
if args['--out']:
output_file = args['--out']
else:
head, ext = os.path.splitext(images[0])
head, tail = os.path.split(head)
output_file = os.path.join(head, 'transformed_' + tail + '.tiff')
# Are the windows specified, or do I have to provide a gui to choose?
if args['--no-transform']:
pass # No windows are needed for the averaging case
elif args['--windows']:
windows = np.genfromtxt(args['--windows'])
else:
baseline = load_image(images[0])
windows = get_windows(baseline)
# What kind of registration am I performing?
if args['--no-transform']:
registrator = no_transform
else:
try: # Only load the baseline if not loaded earlier.
baseline.shape
except NameError:
baseline = load_image(images[0])
registrator = Registrator(windows, baseline)
output = process_images(images, registrator)
save_image(output, output_file)
| {
"repo_name": "SamHames/aperturesynth",
"path": "aperturesynth/synthesise.py",
"copies": "1",
"size": "5285",
"license": "mit",
"hash": -7464353572382036000,
"line_mean": 32.8782051282,
"line_max": 84,
"alpha_frac": 0.6418164617,
"autogenerated": false,
"ratio": 4.490229396771453,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5632045858471453,
"avg_score": null,
"num_lines": null
} |
APESECTION = "APE"
MODULES_SECTION = 'MODULES'
FILE_TIMESTAMP = "%Y_%m_%d_%I:%M:%S_%p"
VERSION = "2014.12.28"
SUBCOMMAND_GROUP = 'theape.subcommands'
# these imports mean users of the parts of the ape need to have all dependencies installed
# even if the part they use doesn't need it...
from infrastructure.baseclass import BaseClass, BaseThreadClass
from infrastructure.errors import ApeError, DontCatchError, ConfigurationError
from infrastructure.indexbuilder import create_toctree
from plugins.base_plugin import BasePlugin, SubConfiguration, BaseConfiguration
from components.component import Component
# color_constants
BLUE = "\033[34m"
RED = "\033[31m"
BOLD = "\033[1m"
RESET = "\033[0;0m"
NEWLINE = '\n'
# constants for formatting output
RED_THING = "{red}{{{{thing}}}}{reset} {{verb}}".format(red=RED, reset=RESET)
BOLD_THING = "{bold}{{thing}}{reset} {{{{value}}}}".format(bold=BOLD, reset=RESET)
BLUE_WARNING = "{blue}{{thing}}{reset}".format(blue=BLUE, reset=RESET)
CALLED_ON = "'{blue}{{attribute}}{reset}' attribute called on {red}{{thing}}{reset}".format(blue=BLUE,
red=RED,
reset=RESET)
CREATION = RED_THING.format(verb='Created')
ARGS = BOLD_THING.format(thing='Args:')
KWARGS = BOLD_THING.format(thing='Kwargs:')
CALLED = RED_THING.format(verb='Called')
NOT_IMPLEMENTED = RED_THING.format(verb='Not Implemented')
| {
"repo_name": "rsnakamura/theape",
"path": "theape/__init__.py",
"copies": "1",
"size": "1527",
"license": "mit",
"hash": 631591242278560300,
"line_mean": 41.4166666667,
"line_max": 105,
"alpha_frac": 0.6430910282,
"autogenerated": false,
"ratio": 3.5022935779816513,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4645384606181651,
"avg_score": null,
"num_lines": null
} |
def template_test_class():
return '''/**
* @author {author}
*/
@isTest
private class {class_name}Test {{
{class_body}
}}
'''
# Apex Test Method Template
def template_test_method():
return '''
/**
* This is a test method for {function_name}
*/
static testMethod void test_{function_name}() {{
// PageReference pageRef = Page.{page_name};
// Test.setCurrentPage(pageRef);
// pageRef.getParameters().put('param1', 'param1');
Test.startTest();
{function_body}
Test.stopTest();
// Check
// System.assert(ApexPages.hasMessages());
// for(ApexPages.Message msg : ApexPages.getMessages()) {{
// System.assertEquals('Upload file is NULL', msg.getSummary());
// System.assertEquals(ApexPages.Severity.ERROR, msg.getSeverity());
// }}
}}
'''
# Apex Class Template
def template_class():
return '''/**
* @author {author}
*/
public class {class_name}{class_type} {{
public {class_name}{class_type}() {{
{constructor_body}
}}
{class_body}
}}
'''
# Apex Class Without Constructor Template
def template_no_con_class():
return '''/**
* @author {author}
*/
public class {class_name}{class_type} {{
{class_body}
}}
'''
# Apex Class Template
def template_class_with_sharing():
return '''/**
* @author {author}
*/
public with sharing class {class_name}{class_type} {{
public {class_name}{class_type}() {{
{constructor_body}
}}
{class_body}
}}
'''
# constructor method
def template_constructor_fun():
return '''
public {class_name}({args}) {{
{constructor_body}
}}
'''
# VisualForce table td Template
def template_html_table_content():
return '''
<tr>
<th class="mythclass">
<apex:outputPanel rendered="" >
<span class="mod-icon-note">必須</span>
</apex:outputPanel>
<apex:outputText value="{th_body}" />
</th>
<td>
{td_body}
</td>
</tr>
'''
# VisualForce table td Template
def template_html_table_content_with_validate():
return '''
<tr>
<th class="mythclass">
<apex:outputPanel rendered="" >
<span class="mod-icon-note">必須</span>
</apex:outputPanel>
<apex:outputText value="{th_body}" />
</th>
<td>
{td_body}
<apex:outputPanel layout="block" rendered="{{!!ISBlank({td_body2})}}">
<apex:outputText style="color:red;" value="{{!{td_body2}}}"/>
</apex:outputPanel>
</td>
</tr>
'''
def template_list_vf_table_body():
return '''
<tbody>
<tr>
{th_header}
</tr>
<apex:repeat value="{{!{list_dto_instance}}}" var="{dto_instance}" >
<tr>
{table_body}
</tr>
</apex:repeat>
</tbody>
'''
# VisualForce Template
def template_vf_inputform():
return '''<apex:page showHeader="false" standardStylesheets="false" applyHtmlTag="false" applyBodyTag="false" sidebar="false" showChat="false" cache="false" docType="html-5.0" controller="{controller}">
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>{title}</title>
</head>
<style>
.ul-search {{
list-style-type: none;
}}
.li_search {{
display: table;
width: 100%;
margin-bottom: 20px;
}}
.li_title {{
width: 120px
}}
.li_title,
.li_content {{
display: table-cell;
vertical-align: middle
}}
table.type1 {{
border-collapse: separate;
border-spacing: 1px;
text-align: center;
line-height: 1.5;
}}
table.type1 th {{
width: 155px;
padding: 10px;
font-weight: bold;
vertical-align: top;
color: #fff;
background: #036;
}}
table.type1 td {{
width: 155px;
padding: 10px;
vertical-align: top;
border-bottom: 1px solid #ccc;
background: #eee;
}}
</style>
<body>
<apex:form id="mainform">
<!-- START OF Edit Mode -->
<apex:outputText rendered="{{!isEditMode}}">
{search_vf}
<div class="frame-wrapper">
<table class="type1">
{edit_table_body}
</table>
</div>
<div class="btn">
<apex:commandButton value="Return" action="{{!doBack}}" onclick=""/>
<apex:commandButton value="Next" action="{{!doNext}}" onclick=""/>
</div>
</apex:outputText>
<!-- END OF Edit Mode -->
<!-- START OF View Mode -->
<apex:outputText rendered="{{!isViewMode}}">
{search_vf}
<div class="frame-wrapper">
<table class="type1">
{view_table_body}
</table>
</div>
<div class="btn">
<apex:commandButton value="Return" action="{{!doBack}}" onclick=""/>
<apex:commandButton value="Next" action="{{!doNext}}" onclick=""/>
<apex:commandButton value="Save" action="{{!doSave}}" onclick=""/>
</div>
</apex:outputText>
<!-- END OF View Mode -->
<!-- START OF Message Mode -->
<apex:outputText rendered="{{!isMessageMode}}">
<div class="frame-wrapper">
Message Mode
</div>
<div class="btn">
<apex:commandButton value="Return" action="{{!doBack}}" onclick=""/>
<apex:commandButton value="Next" action="{{!doNext}}" onclick=""/>
</div>
</apex:outputText>
<!-- END OF Message Mode -->
</apex:form>
</body>
</html>
</apex:page>
'''
# VisualForce Template
def template_vf_search():
return '''
<div class="search">
<ul class="ul-search">
{search_vf_item}
<li class="li-search">
<div class="li_title">KeyWord</div>
<div class="li_content"><apex:input type="text" value="{{!keywords}}" /></div>
</li>
<li class="li-search">
<div class="li_title"></div>
<div class="li_content"><apex:commandButton value="Search" action="{{!search}}" onclick=""/></div>
</li>
</ul>
</div>
'''
# VisualForce Template
def template_search_snippet(data_type):
vf_code = ""
if data_type == 'picklist':
vf_code = '''
<li class="li-search">
<div class="li_title">{field_label}</div>
<div class="li_content">
<apex:selectList size="1" value="{{!{field_name}}}" >
<apex:selectOptions value="{{!{field_name}List}}" />
</apex:selectList>
</div>
</li>
'''
return vf_code
def template_sfdcxycontroller():
return '''/**
* @author {author}
*/
public virtual class SfdcXyController {{
// Return URL
public String retUrl {{get;set;}}
// Return Current Url
public String currentUrl {{get;set;}}
// Page Mode
public Integer modeIndex {{get;set;}}
public static final Integer MODE_EDIT = 0;
public static final Integer MODE_VIEW = 1;
public static final Integer MODE_MESSAGE = 2;
public Boolean isEditMode {{
get{{
return (modeIndex == MODE_EDIT);
}}
}}
public Boolean isViewMode {{
get{{
return (modeIndex == MODE_VIEW);
}}
}}
public Boolean isMessageMode {{
get{{
return (modeIndex == MODE_MESSAGE);
}}
}}
public SfdcXyController() {{
this.modeIndex = MODE_EDIT;
this.retUrl = ApexPages.currentPage().getParameters().get('retUrl');
this.currentUrl = ApexPages.currentPage().getURL();
this.retUrl = String.isBlank(this.retUrl) ? this.currentUrl : this.retUrl;
}}
/**
* Go Next
*/
public virtual PageReference doNext() {{
Boolean result = doCheck();
setNextMode(result);
return null;
}}
/**
* Go Back
*/
public virtual PageReference doBack() {{
Boolean result = true;
setBackMode(result);
return null;
}}
/**
* Go Cancel
*/
public virtual PageReference doCancel() {{
if (String.isBlank(retUrl)) {{
retUrl = '/';
}}
PageReference nextPage = new PageReference(retUrl);
nextPage.setRedirect(true);
return nextPage;
}}
/**
* do Check
*/
public virtual Boolean doCheck() {{
Boolean result = true;
return result;
}}
/**
* set next mode
*/
public virtual void setNextMode(Boolean flg) {{
if(!flg) return;
if(modeIndex == MODE_EDIT) modeIndex = MODE_VIEW;
else if(modeIndex == MODE_VIEW) modeIndex = MODE_MESSAGE;
else if(modeIndex == MODE_MESSAGE) modeIndex = MODE_MESSAGE;
}}
/**
* set back mode
*/
public virtual void setBackMode(Boolean flg) {{
if(!flg) return;
if(modeIndex == MODE_EDIT) modeIndex = MODE_EDIT;
else if(modeIndex == MODE_VIEW) modeIndex = MODE_EDIT;
else if(modeIndex == MODE_MESSAGE) modeIndex = MODE_VIEW;
}}
}}
'''
def template_controller_class():
return '''/**
* @author {author}
*/
public with sharing class {controller} extends SfdcXyController {{
// DTO Bean
public {dto} {dto_instance} {{get;set;}}
public {controller}() {{
search();
}}
private void search(){{
String id = ApexPages.currentPage().getParameters().get('id');
if(String.isBlank(id)){{
this.{dto_instance} = new {dto}();
}}else{{
this.{dto_instance} = new {dto}({dao}.get{sobj_api}ById(id));
}}
}}
/**
* upsert Dto
*/
public PageReference doSave() {{
Boolean result;
Savepoint sp = Database.setSavepoint();
try {{
upsert {dto_instance}.getSobject();
result = true;
}} catch(DMLException e) {{
Database.rollback(sp);
System.debug('saveDto DMLException:' + e.getMessage());
result = false;
}} catch(Exception e) {{
Database.rollback(sp);
System.debug('saveDto Exception:' + e.getMessage());
result = false;
}}
return null;
}}
/**
* Go Next
*/
public override PageReference doNext() {{
Boolean result = doCheck();
setNextMode(result);
return null;
}}
/**
* Go Back
*/
public override PageReference doBack() {{
Boolean result = true;
setBackMode(result);
return null;
}}
/**
* do Check
*/
public override Boolean doCheck() {{
Boolean result = true;
return result;
}}
}}
'''
def template_list_controller_class():
return '''/**
* @author {author}
*/
public with sharing class {list_controller} extends SfdcXyController {{
// DTO Bean
public {list_dto} {list_dto_instance} {{get;set;}}
// Search DTO Bean
public {dto} searchDto {{get;set;}}
// Search keywords
public String keywords {{get;set;}}
public {list_controller}() {{
this.searchDto = new {dto}();
search();
}}
public void search(){{
this.{list_dto_instance} = new {list_dto}();
for( {sobject__c} {sobj_api_low_cap} : {dao}.get{sobj_api}List(keywords,searchDto)){{
this.{list_dto_instance}.add(new {dto}({sobj_api_low_cap}));
}}
}}
/**
* upsert Dto
*/
public PageReference doSave() {{
Boolean result;
Savepoint sp = Database.setSavepoint();
try {{
List<{sobject__c}> {sobj_api_low_cap}List = new List<{sobject__c}>();
for({dto} dto : this.{list_dto_instance}){{
{sobj_api_low_cap}List.add(dto.getSobject());
}}
update {sobj_api_low_cap}List;
result = true;
}} catch(DMLException e) {{
Database.rollback(sp);
System.debug('saveDto DMLException:' + e.getMessage());
result = false;
}} catch(Exception e) {{
Database.rollback(sp);
System.debug('saveDto Exception:' + e.getMessage());
result = false;
}}
return null;
}}
/**
* Go Next
*/
public override PageReference doNext() {{
Boolean result = doCheck();
setNextMode(result);
return null;
}}
/**
* Go Back
*/
public override PageReference doBack() {{
Boolean result = true;
setBackMode(result);
return null;
}}
/**
* do Check
*/
public override Boolean doCheck() {{
Boolean result = true;
return result;
}}
}}
'''
def template_dao_class():
return '''/**
* @author {author}
*/
public with sharing class {dao} {{
/**
* get soql query string
*/
public static String getQueryField(){{
String query_str = '';
{soql_src}
return query_str;
}}
/**
* get all {sobject__c}
* @return list of {sobject__c}
*/
public static List<{sobject__c}> getAll{sobj_api}List(){{
String query_str = getQueryField();
query_str += ' limit 10000';
List<{sobject__c}> {sobj_api_low_cap}List = Database.query(query_str);
return {sobj_api_low_cap}List;
}}
/**
* get {sobject__c} by Set<id>
* @return list of {sobject__c}
*/
public static List<{sobject__c}> get{sobj_api}List(Set<String> ids){{
String query_str = getQueryField();
query_str += ' WHERE id IN:ids ';
List<{sobject__c}> {sobj_api_low_cap}List = Database.query(query_str);
return {sobj_api_low_cap}List;
}}
/**
* get {sobject__c} by id
* @return one of {sobject__c}
*/
public static {sobject__c} get{sobj_api}ById(String id){{
String query_str = getQueryField();
query_str += ' WHERE id =: id ';
query_str += ' limit 1 ';
List<{sobject__c}> {sobj_api_low_cap}List = Database.query(query_str);
if({sobj_api_low_cap}List.isEmpty())
return null;
else
return {sobj_api_low_cap}List.get(0);
}}
/**
* get {sobject__c} by keywords
* @return list of {sobject__c}
*/
public static List<{sobject__c}> get{sobj_api}List(String keywords,{dto} searchDto){{
String soql = getQueryField();
String query_str = '';
List<String> query_list = new List<String>();
if(String.isNotBlank(keywords)){{
String[] keywordsArr = keywords.replace(' ',' ').split(' ');
List<String> keywordsFilters = new List<String>();
for(String f: keywordsArr){{
if(String.isBlank(f)) continue;
f = f.replace('%', '\\\\%').replace('_','\\\\_');
keywordsFilters.add('%' + f + '%');
}}
{keywords_conditions}
query_list.add(query_str);
}}
{searchDto_conditions}
if(query_list.size() > 0){{
soql += ' WHERE ';
soql += String.join(query_list, ' and ');
}}
soql += ' limit 10000';
List<{sobject__c}> {sobj_api_low_cap}List = Database.query(soql);
return {sobj_api_low_cap}List;
}}
}}
'''
# def template_dao_class():
# return '''/**
# * @author {author}
# */
# public with sharing class {dao} {{
# /**
# * get all {sobject__c}
# * @return list of {sobject__c}
# */
# public static List<{sobject__c}> getAll{sobj_api}List(){{
# List<{sobject__c}> {sobj_api_low_cap}List = [
# {soql_src}
# limit 10000
# ];
# return {sobj_api_low_cap}List;
# }}
# /**
# * get {sobject__c} by Set<id>
# * @return list of {sobject__c}
# */
# public static List<{sobject__c}> get{sobj_api}List(Set<String> ids){{
# List<{sobject__c}> {sobj_api_low_cap}List = [
# {soql_src}
# WHERE id IN:ids
# ];
# return {sobj_api_low_cap}List;
# }}
# /**
# * get {sobject__c} by id
# * @return one of {sobject__c}
# */
# public static {sobject__c} get{sobj_api}ById(String id){{
# List<{sobject__c}> {sobj_api_low_cap}List = [
# {soql_src}
# WHERE id =: id
# limit 1
# ];
# if({sobj_api_low_cap}List.isEmpty())
# return null;
# else
# return {sobj_api_low_cap}List.get(0);
# }}
# /**
# * get {sobject__c} by keywords
# * @return list of {sobject__c}
# */
# public static List<{sobject__c}> get{sobj_api}List(String keywords){{
# if(String.isBlank(keywords)) return getAll{sobj_api}List();
# String[] keywordsArr = keywords.replace(' ',' ').split(' ');
# List<String> keywordsFilters = new List<String>();
# for(String f: keywordsArr){{
# if(String.isBlank(f)) continue;
# f = f.replace('%', '\\\\%').replace('_','\\\\_');
# keywordsFilters.add('%' + f + '%');
# }}
# List<{sobject__c}> {sobj_api_low_cap}List = [
# {soql_src}
# WHERE
# {keywords_conditions}
# ];
# return {sobj_api_low_cap}List;
# }}
# }}
# '''
def template_dto_class():
return '''/**
* @author {author}
*/
public class {dto} {{
{class_body}
public {dto}() {{
init();
}}
public {dto}({sobject__c} sobj) {{
init();
if(sobj != null){{
{constructor_body}
}}
}}
/**
* init method
*/
public void init(){{
{init_body}
}}
/**
* Change the dto to sobject
* get sobject {sobject__c} from dto
* @return {sobject__c}
*/
public {sobject__c} getSobject(){{
{sobject__c} sobj = new {sobject__c}();
{getSobject_body}
return sobj;
}}
}}
'''
def get_vf_edit_snippet(data_type):
vf_code = ""
if data_type == 'id' or data_type == 'ID' or data_type == 'reference':
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
elif data_type == 'string':
vf_code = '''<apex:input type="text" value="{{!{field_name}}}" />'''
elif data_type == 'url' :
vf_code = '''<apex:input type="text" value="{{!{field_name}}}" />'''
elif data_type == 'email':
vf_code = '''<apex:input type="email" value="{{!{field_name}}}" />'''
elif data_type == 'phone':
vf_code = '''<apex:input type="text" value="{{!{field_name}}}" />'''
elif data_type == 'textarea':
vf_code = '''<apex:inputTextarea value="{{!{field_name}}}" />'''
elif data_type == 'picklist':
vf_code = '''<apex:selectList size="1" value="{{!{field_name}}}" >
<apex:selectOptions value="{{!{field_name}List}}" />
</apex:selectList>'''
elif data_type == 'multipicklist':
vf_code = '''<apex:selectList size="10" value="{{!{field_name}}}" multiselect="true">
<apex:selectOptions value="{{!{field_name}List}}" />
</apex:selectList>'''
elif data_type == 'int' or data_type == 'percent' or data_type == 'long' or data_type == 'currency' or data_type == 'double':
vf_code = '''<apex:input type="number" value="{{!{field_name}}}" />'''
elif data_type == 'boolean' or data_type == 'combobox':
vf_code = '''<apex:inputCheckbox value="{{!{field_name}}}" />'''
elif data_type == 'datetime' :
vf_code = '''<apex:input type="datetime-local" value="{{!{field_name}}}" />'''
elif data_type == 'date' :
vf_code = '''<apex:input type="date" value="{{!{field_name}}}" />'''
return vf_code
def get_vf_show_snippet(data_type):
if data_type == 'id' \
or data_type == 'ID' \
or data_type == 'reference' \
or data_type == 'string' \
or data_type == 'url' \
or data_type == 'email' \
or data_type == 'phone' \
or data_type == 'picklist' \
or data_type == 'int' or data_type == 'percent' \
or data_type == 'long' or data_type == 'currency' or data_type == 'double' \
or data_type == 'boolean' or data_type == 'combobox':
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
elif data_type == 'textarea':
# white-space: pre;
vf_code = '''<div style="white-space: pre-wrap; word-break: break-all; ">
<apex:outputText value="{{!{field_name}}}" />
</div>'''
elif data_type == 'multipicklist':
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
# vf_code = '''<apex:selectList size="10" value="{{!{field_name}}}" multiselect="true">
# <apex:selectOptions value="{{!{field_name}List}}" />
# </apex:selectList>'''
elif data_type == 'datetime' :
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
# vf_code = '''<apex:input type="datetime-local" value="{{!{field_name}}}" />'''
elif data_type == 'date' :
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
# vf_code = '''<apex:input type="date" value="{{!{field_name}}}" />'''
else :
vf_code = '''<apex:outputText value="{{!{field_name}}}" />'''
return vf_code
| {
"repo_name": "exiahuang/SalesforceXyTools",
"path": "template.py",
"copies": "1",
"size": "23996",
"license": "apache-2.0",
"hash": -1032512850101457000,
"line_mean": 28.5295566502,
"line_max": 206,
"alpha_frac": 0.4688464426,
"autogenerated": false,
"ratio": 3.771904986628913,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9729301915367847,
"avg_score": 0.0022899027722131124,
"num_lines": 812
} |
"A phenotype holder"
import pandas as pd
class Phenotypes(object):
"""
A container for the set of phenotypes and exposures associated with an
Individual in a population
"""
def __init__(self, data=None):
self.data = dict(data) if data is not None else dict()
def __contains__(self, key):
return self.has_phenotype(key)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, val):
self.data[key] = val
def __delitem__(self, key):
self.clear_phenotype(key)
def get(self, key, default):
"Gets a phenotype or default value if not present"
return self.data.get(key, default)
def keys(self):
"Iterate over the available phenotype names"
return self.data.keys()
def values(self):
"Iterate over the available phenotype values"
return self.data.values()
def items(self):
"Iterate over phenotype name, value pairs"
return self.data.items()
def has_phenotype(self, key):
"""
Does the individual have a certain phenotype?
:param phenotype: what phenotype are we looking for
:type phenotype: string
:returns: True if phenotype present and not None
:rtype: bool
"""
return key in self.data and self.data[key] != None
def delete_phenotype(self, key):
"Clears the phenotype from the object"
try:
del self.data[key]
except KeyError:
pass
def clear(self):
"Clears all phenotypes from the object"
self.data = dict()
def update(self, other):
"Updates the current Phenotype object with data from the other"
if isinstance(other, Phenotypes):
self.data.update(other.data)
else:
self.data.update(other)
def to_series(self):
"Returns phenotypes as a pandas Series"
return pd.Series(self.data)
| {
"repo_name": "jameshicks/pydigree",
"path": "pydigree/phenotypes.py",
"copies": "1",
"size": "1986",
"license": "apache-2.0",
"hash": -1407523365795396600,
"line_mean": 25.8378378378,
"line_max": 75,
"alpha_frac": 0.6022155086,
"autogenerated": false,
"ratio": 3.956175298804781,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5058390807404781,
"avg_score": null,
"num_lines": null
} |
"""A Phi accrual failure detector."""
import decimal
import logging
import math
import sys
import time
class AccrualFailureDetector(object):
""" Python implementation of 'The Phi Accrual Failure Detector'
by Hayashibara et al.
* Taken from https://github.com/rschildmeijer/elastica/blob/
a41f9427f80b5207891597ec430e76949e4948df/elastica/afd.py
* Licensed under under Apache version 2 according to the README.rst.
* Original version by Brandon Williams (github.com/driftx)
* modified by Roger Schildmeijer (github.com/rchildmeijer))
Failure detection is the process of determining which nodes in
a distributed fault-tolerant system have failed. Original Phi
Accrual Failure Detection paper: http://ddg.jaist.ac.jp/pub/HDY+04.pdf
A low threshold is prone to generate many wrong suspicions but
ensures a quick detection in the event of a real crash. Conversely,
a high threshold generates fewer mistakes but needs more time to
detect actual crashes.
We use the algorithm to self-tune sensor timeouts for presence.
"""
max_sample_size = 1000
# 1 = 10% error rate, 2 = 1%, 3 = 0.1%.., (eg threshold=3. no
# heartbeat for >6s => node marked as dead
threshold = 3
def __init__(self):
self._intervals = []
self._mean = 60
self._timestamp = None
@classmethod
def from_dict(cls, values):
detector = cls()
detector._intervals = values['intervals']
detector._mean = values['mean']
detector._timestamp = values['timestamp']
return detector
def to_dict(self):
return {
'intervals': self._intervals,
'mean': self._mean,
'timestamp': self._timestamp
}
def heartbeat(self, now=None):
""" Call when host has indicated being alive (aka heartbeat) """
if now is None:
now = time.time()
if self._timestamp is None:
self._timestamp = now
return
interval = now - self._timestamp
self._timestamp = now
self._intervals.append(interval)
if len(self._intervals) > self.max_sample_size:
self._intervals.pop(0)
if len(self._intervals) > 0:
self._mean = sum(self._intervals) / float(len(self._intervals))
logging.debug('mean = %s', self._mean)
def _probability(self, diff):
if self._mean == 0:
# we've only seen one heartbeat
# so use a different formula
# for probability
return sys.float_info.max
# cassandra does this, citing: /* Exponential CDF = 1 -e^-lambda*x */
# but the paper seems to call for a probability density function
# which I can't figure out :/
exponent = -1.0 * diff / self._mean
return 1 - (1.0 - math.pow(math.e, exponent))
def phi(self, timestamp=None):
if self._timestamp is None:
# we've never seen a heartbeat,
# so it must be missing...
return self.threshold
if timestamp is None:
timestamp = time.time()
diff = timestamp - self._timestamp
prob = self._probability(diff)
logging.debug('Proability = %s', prob)
if decimal.Decimal(str(prob)).is_zero():
# a very small number, avoiding ValueError: math domain error
prob = 1E-128
return -1 * math.log10(prob)
def is_alive(self, timestamp=None):
phi = self.phi(timestamp)
logging.debug('Phi = %s', phi)
return phi < self.threshold
def is_dead(self, timestamp=None):
return not self.is_alive(timestamp)
| {
"repo_name": "tomwilkie/awesomation",
"path": "src/common/detector.py",
"copies": "1",
"size": "3389",
"license": "mit",
"hash": 6679678616858333000,
"line_mean": 29.2589285714,
"line_max": 73,
"alpha_frac": 0.668338743,
"autogenerated": false,
"ratio": 3.659827213822894,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48281659568228935,
"avg_score": null,
"num_lines": null
} |
'''A (PHP) Docblock generator plugin for Coda'''
import cp_actions as cp
from Docblock import Docblock
def act(controller, bundle, options):
'''
Required action method
Supplying a lang option will override the automatic language guessing
(which might not be such a bad thing...)
'''
context = cp.get_context(controller)
lang = cp.get_option(options, 'lang', 'auto').lower()
# get the file extension so we can guess the language.
if lang == 'auto':
path = context.path()
if path is not None:
pos = path.rfind('.')
if pos != -1:
lang = path[pos+1:]
d = Docblock.get(lang)
# get the current line
text, target_range = cp.lines_and_range(context)
# keep going until we find a non-empty line to document (up to X lines below the current line)
tries_left = 3
while tries_left and not text.strip():
text, target_range = cp.get_line_after_and_range(context, target_range)
if text is None:
# we're at the end of the document?
cp.beep()
return
tries_left -= 1
insert_range = cp.new_range(target_range.location, 0)
d.setLineEnding(cp.get_line_ending(context))
docblock = d.doc(text)
if docblock:
cp.insert_text_with_insertion_point(context, docblock, insert_range)
else:
cp.beep() | {
"repo_name": "bobthecow/CodaDocblock",
"path": "src/Support/Scripts/GenerateDocblock.py",
"copies": "1",
"size": "1446",
"license": "mit",
"hash": 6478677454306442000,
"line_mean": 27.3725490196,
"line_max": 98,
"alpha_frac": 0.59197787,
"autogenerated": false,
"ratio": 3.8870967741935485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49790746441935485,
"avg_score": null,
"num_lines": null
} |
"""API and implementations for loading templates from different data
sources.
"""
import importlib.util
import os
import sys
import typing as t
import weakref
import zipimport
from collections import abc
from hashlib import sha1
from importlib import import_module
from types import ModuleType
from .exceptions import TemplateNotFound
from .utils import internalcode
from .utils import open_if_exists
if t.TYPE_CHECKING:
from .environment import Environment
from .environment import Template
def split_template_path(template: str) -> t.List[str]:
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split("/"):
if (
os.path.sep in piece
or (os.path.altsep and os.path.altsep in piece)
or piece == os.path.pardir
):
raise TemplateNotFound(template)
elif piece and piece != ".":
pieces.append(piece)
return pieces
class BaseLoader:
"""Baseclass for all loaders. Subclass this and override `get_source` to
implement a custom loading mechanism. The environment provides a
`get_template` method that calls the loader's `load` method to get the
:class:`Template` object.
A very basic example for a loader that looks up templates on the file
system could look like this::
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with open(path) as f:
source = f.read()
return source, path, lambda: mtime == getmtime(path)
"""
#: if set to `False` it indicates that the loader cannot provide access
#: to the source of templates.
#:
#: .. versionadded:: 2.4
has_source_access = True
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
"""Get the template source, filename and reload helper for a template.
It's passed the environment and template name and has to return a
tuple in the form ``(source, filename, uptodate)`` or raise a
`TemplateNotFound` error if it can't locate the template.
The source part of the returned tuple must be the source of the
template as a string. The filename should be the name of the
file on the filesystem if it was loaded from there, otherwise
``None``. The filename is used by Python for the tracebacks
if no loader extension is used.
The last item in the tuple is the `uptodate` function. If auto
reloading is enabled it's always called to check if the template
changed. No arguments are passed so the function must store the
old state somewhere (for example in a closure). If it returns `False`
the template will be reloaded.
"""
if not self.has_source_access:
raise RuntimeError(
f"{type(self).__name__} cannot provide access to the source"
)
raise TemplateNotFound(template)
def list_templates(self) -> t.List[str]:
"""Iterates over all templates. If the loader does not support that
it should raise a :exc:`TypeError` which is the default behavior.
"""
raise TypeError("this loader cannot iterate over all templates")
@internalcode
def load(
self,
environment: "Environment",
name: str,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
"""
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, filename, uptodate = self.get_source(environment, name)
# try to load the code from the bytecode cache if there is a
# bytecode cache configured.
bcc = environment.bytecode_cache
if bcc is not None:
bucket = bcc.get_bucket(environment, name, filename, source)
code = bucket.code
# if we don't have code so far (not cached, no longer up to
# date) etc. we compile the template
if code is None:
code = environment.compile(source, name, filename)
# if the bytecode cache is available and the bucket doesn't
# have a code so far, we give the bucket the new code and put
# it back to the bytecode cache.
if bcc is not None and bucket.code is None:
bucket.code = code
bcc.set_bucket(bucket)
return environment.template_class.from_code(
environment, code, globals, uptodate
)
class FileSystemLoader(BaseLoader):
"""Load templates from a directory in the file system.
The path can be relative or absolute. Relative paths are relative to
the current working directory.
.. code-block:: python
loader = FileSystemLoader("templates")
A list of paths can be given. The directories will be searched in
order, stopping at the first matching template.
.. code-block:: python
loader = FileSystemLoader(["/override/templates", "/default/templates"])
:param searchpath: A path, or list of paths, to the directory that
contains the templates.
:param encoding: Use this encoding to read the text from template
files.
:param followlinks: Follow symbolic links in the path.
.. versionchanged:: 2.8
Added the ``followlinks`` parameter.
"""
def __init__(
self,
searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],
encoding: str = "utf-8",
followlinks: bool = False,
) -> None:
if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
searchpath = [searchpath]
self.searchpath = [os.fspath(p) for p in searchpath]
self.encoding = encoding
self.followlinks = followlinks
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, str, t.Callable[[], bool]]:
pieces = split_template_path(template)
for searchpath in self.searchpath:
filename = os.path.join(searchpath, *pieces)
f = open_if_exists(filename)
if f is None:
continue
try:
contents = f.read().decode(self.encoding)
finally:
f.close()
mtime = os.path.getmtime(filename)
def uptodate() -> bool:
try:
return os.path.getmtime(filename) == mtime
except OSError:
return False
return contents, filename, uptodate
raise TemplateNotFound(template)
def list_templates(self) -> t.List[str]:
found = set()
for searchpath in self.searchpath:
walk_dir = os.walk(searchpath, followlinks=self.followlinks)
for dirpath, _, filenames in walk_dir:
for filename in filenames:
template = (
os.path.join(dirpath, filename)[len(searchpath) :]
.strip(os.path.sep)
.replace(os.path.sep, "/")
)
if template[:2] == "./":
template = template[2:]
if template not in found:
found.add(template)
return sorted(found)
class PackageLoader(BaseLoader):
"""Load templates from a directory in a Python package.
:param package_name: Import name of the package that contains the
template directory.
:param package_path: Directory within the imported package that
contains the templates.
:param encoding: Encoding of template files.
The following example looks up templates in the ``pages`` directory
within the ``project.ui`` package.
.. code-block:: python
loader = PackageLoader("project.ui", "pages")
Only packages installed as directories (standard pip behavior) or
zip/egg files (less common) are supported. The Python API for
introspecting data in packages is too limited to support other
installation methods the way this loader requires.
There is limited support for :pep:`420` namespace packages. The
template directory is assumed to only be in one namespace
contributor. Zip files contributing to a namespace are not
supported.
.. versionchanged:: 3.0
No longer uses ``setuptools`` as a dependency.
.. versionchanged:: 3.0
Limited PEP 420 namespace package support.
"""
def __init__(
self,
package_name: str,
package_path: "str" = "templates",
encoding: str = "utf-8",
) -> None:
if package_path == os.path.curdir:
package_path = ""
elif package_path[:2] == os.path.curdir + os.path.sep:
package_path = package_path[2:]
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
self.package_path = package_path
self.package_name = package_name
self.encoding = encoding
# Make sure the package exists. This also makes namespace
# packages work, otherwise get_loader returns None.
import_module(package_name)
spec = importlib.util.find_spec(package_name)
assert spec is not None, "An import spec was not found for the package."
loader = spec.loader
assert loader is not None, "A loader was not found for the package."
self._loader = loader
self._archive = None
template_root = None
if isinstance(loader, zipimport.zipimporter):
self._archive = loader.archive
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
template_root = os.path.join(pkgdir, package_path)
elif spec.submodule_search_locations:
# This will be one element for regular packages and multiple
# for namespace packages.
for root in spec.submodule_search_locations:
root = os.path.join(root, package_path)
if os.path.isdir(root):
template_root = root
break
if template_root is None:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)
self._template_root = template_root
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
p = os.path.join(self._template_root, *split_template_path(template))
up_to_date: t.Optional[t.Callable[[], bool]]
if self._archive is None:
# Package is a directory.
if not os.path.isfile(p):
raise TemplateNotFound(template)
with open(p, "rb") as f:
source = f.read()
mtime = os.path.getmtime(p)
def up_to_date() -> bool:
return os.path.isfile(p) and os.path.getmtime(p) == mtime
else:
# Package is a zip file.
try:
source = self._loader.get_data(p) # type: ignore
except OSError:
raise TemplateNotFound(template)
# Could use the zip's mtime for all template mtimes, but
# would need to safely reload the module if it's out of
# date, so just report it as always current.
up_to_date = None
return source.decode(self.encoding), p, up_to_date
def list_templates(self) -> t.List[str]:
results: t.List[str] = []
if self._archive is None:
# Package is a directory.
offset = len(self._template_root)
for dirpath, _, filenames in os.walk(self._template_root):
dirpath = dirpath[offset:].lstrip(os.path.sep)
results.extend(
os.path.join(dirpath, name).replace(os.path.sep, "/")
for name in filenames
)
else:
if not hasattr(self._loader, "_files"):
raise TypeError(
"This zip import does not have the required"
" metadata to list templates."
)
# Package is a zip file.
prefix = (
self._template_root[len(self._archive) :].lstrip(os.path.sep)
+ os.path.sep
)
offset = len(prefix)
for name in self._loader._files.keys(): # type: ignore
# Find names under the templates directory that aren't directories.
if name.startswith(prefix) and name[-1] != os.path.sep:
results.append(name[offset:].replace(os.path.sep, "/"))
results.sort()
return results
class DictLoader(BaseLoader):
"""Loads a template from a Python dict mapping template names to
template source. This loader is useful for unittesting:
>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
"""
def __init__(self, mapping: t.Mapping[str, str]) -> None:
self.mapping = mapping
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, None, t.Callable[[], bool]]:
if template in self.mapping:
source = self.mapping[template]
return source, None, lambda: source == self.mapping.get(template)
raise TemplateNotFound(template)
def list_templates(self) -> t.List[str]:
return sorted(self.mapping)
class FunctionLoader(BaseLoader):
"""A loader that is passed a function which does the loading. The
function receives the name of the template and has to return either
a string with the template source, a tuple in the form ``(source,
filename, uptodatefunc)`` or `None` if the template does not exist.
>>> def load_template(name):
... if name == 'index.html':
... return '...'
...
>>> loader = FunctionLoader(load_template)
The `uptodatefunc` is a function that is called if autoreload is enabled
and has to return `True` if the template is still up to date. For more
details have a look at :meth:`BaseLoader.get_source` which has the same
return value.
"""
def __init__(
self,
load_func: t.Callable[
[str],
t.Optional[
t.Union[
str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
]
],
],
) -> None:
self.load_func = load_func
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
rv = self.load_func(template)
if rv is None:
raise TemplateNotFound(template)
if isinstance(rv, str):
return rv, None, None
return rv
class PrefixLoader(BaseLoader):
"""A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
by loading ``'app2/index.html'`` the file from the second.
"""
def __init__(
self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
) -> None:
self.mapping = mapping
self.delimiter = delimiter
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
try:
prefix, name = template.split(self.delimiter, 1)
loader = self.mapping[prefix]
except (ValueError, KeyError):
raise TemplateNotFound(template)
return loader, name
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
loader, name = self.get_loader(template)
try:
return loader.get_source(environment, name)
except TemplateNotFound:
# re-raise the exception with the correct filename here.
# (the one that includes the prefix)
raise TemplateNotFound(template)
@internalcode
def load(
self,
environment: "Environment",
name: str,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
loader, local_name = self.get_loader(name)
try:
return loader.load(environment, local_name, globals)
except TemplateNotFound:
# re-raise the exception with the correct filename here.
# (the one that includes the prefix)
raise TemplateNotFound(name)
def list_templates(self) -> t.List[str]:
result = []
for prefix, loader in self.mapping.items():
for template in loader.list_templates():
result.append(prefix + self.delimiter + template)
return result
class ChoiceLoader(BaseLoader):
"""This loader works like the `PrefixLoader` just that no prefix is
specified. If a template could not be found by one loader the next one
is tried.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/system/templates')
... ])
This is useful if you want to allow users to override builtin templates
from a different location.
"""
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
self.loaders = loaders
def get_source(
self, environment: "Environment", template: str
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
for loader in self.loaders:
try:
return loader.get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
@internalcode
def load(
self,
environment: "Environment",
name: str,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
for loader in self.loaders:
try:
return loader.load(environment, name, globals)
except TemplateNotFound:
pass
raise TemplateNotFound(name)
def list_templates(self) -> t.List[str]:
found = set()
for loader in self.loaders:
found.update(loader.list_templates())
return sorted(found)
class _TemplateModule(ModuleType):
"""Like a normal module but with support for weak references"""
class ModuleLoader(BaseLoader):
"""This loader loads templates from precompiled templates.
Example usage:
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
Templates can be precompiled with :meth:`Environment.compile_templates`.
"""
has_source_access = False
def __init__(
self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]
) -> None:
package_name = f"_jinja2_module_templates_{id(self):x}"
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if not isinstance(path, abc.Iterable) or isinstance(path, str):
path = [path]
mod.__path__ = [os.fspath(p) for p in path] # type: ignore
sys.modules[package_name] = weakref.proxy(
mod, lambda x: sys.modules.pop(package_name, None)
)
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
@staticmethod
def get_template_key(name: str) -> str:
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
@staticmethod
def get_module_filename(name: str) -> str:
return ModuleLoader.get_template_key(name) + ".py"
@internalcode
def load(
self,
environment: "Environment",
name: str,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
key = self.get_template_key(name)
module = f"{self.package_name}.{key}"
mod = getattr(self.module, module, None)
if mod is None:
try:
mod = __import__(module, None, None, ["root"])
except ImportError:
raise TemplateNotFound(name)
# remove the entry from sys.modules, we only want the attribute
# on the module object we have stored on the loader.
sys.modules.pop(module, None)
if globals is None:
globals = {}
return environment.template_class.from_module_dict(
environment, mod.__dict__, globals
)
| {
"repo_name": "pallets/jinja",
"path": "src/jinja2/loaders.py",
"copies": "1",
"size": "22350",
"license": "bsd-3-clause",
"hash": -4806619699705855000,
"line_mean": 33.8130841121,
"line_max": 88,
"alpha_frac": 0.5983892617,
"autogenerated": false,
"ratio": 4.3952802359882,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5493669497688201,
"avg_score": null,
"num_lines": null
} |
"""API and implementations for loading templates from different data
sources.
"""
import importlib.util
import os
import sys
import weakref
import zipimport
from collections import abc
from hashlib import sha1
from importlib import import_module
from types import ModuleType
from .exceptions import TemplateNotFound
from .utils import internalcode
from .utils import open_if_exists
def split_template_path(template):
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split("/"):
if (
os.path.sep in piece
or (os.path.altsep and os.path.altsep in piece)
or piece == os.path.pardir
):
raise TemplateNotFound(template)
elif piece and piece != ".":
pieces.append(piece)
return pieces
class BaseLoader:
"""Baseclass for all loaders. Subclass this and override `get_source` to
implement a custom loading mechanism. The environment provides a
`get_template` method that calls the loader's `load` method to get the
:class:`Template` object.
A very basic example for a loader that looks up templates on the file
system could look like this::
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with open(path) as f:
source = f.read()
return source, path, lambda: mtime == getmtime(path)
"""
#: if set to `False` it indicates that the loader cannot provide access
#: to the source of templates.
#:
#: .. versionadded:: 2.4
has_source_access = True
def get_source(self, environment, template):
"""Get the template source, filename and reload helper for a template.
It's passed the environment and template name and has to return a
tuple in the form ``(source, filename, uptodate)`` or raise a
`TemplateNotFound` error if it can't locate the template.
The source part of the returned tuple must be the source of the
template as a string. The filename should be the name of the
file on the filesystem if it was loaded from there, otherwise
``None``. The filename is used by Python for the tracebacks
if no loader extension is used.
The last item in the tuple is the `uptodate` function. If auto
reloading is enabled it's always called to check if the template
changed. No arguments are passed so the function must store the
old state somewhere (for example in a closure). If it returns `False`
the template will be reloaded.
"""
if not self.has_source_access:
raise RuntimeError(
f"{self.__class__.__name__} cannot provide access to the source"
)
raise TemplateNotFound(template)
def list_templates(self):
"""Iterates over all templates. If the loader does not support that
it should raise a :exc:`TypeError` which is the default behavior.
"""
raise TypeError("this loader cannot iterate over all templates")
@internalcode
def load(self, environment, name, globals=None):
"""Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
"""
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, filename, uptodate = self.get_source(environment, name)
# try to load the code from the bytecode cache if there is a
# bytecode cache configured.
bcc = environment.bytecode_cache
if bcc is not None:
bucket = bcc.get_bucket(environment, name, filename, source)
code = bucket.code
# if we don't have code so far (not cached, no longer up to
# date) etc. we compile the template
if code is None:
code = environment.compile(source, name, filename)
# if the bytecode cache is available and the bucket doesn't
# have a code so far, we give the bucket the new code and put
# it back to the bytecode cache.
if bcc is not None and bucket.code is None:
bucket.code = code
bcc.set_bucket(bucket)
return environment.template_class.from_code(
environment, code, globals, uptodate
)
class FileSystemLoader(BaseLoader):
"""Load templates from a directory in the file system.
The path can be relative or absolute. Relative paths are relative to
the current working directory.
.. code-block:: python
loader = FileSystemLoader("templates")
A list of paths can be given. The directories will be searched in
order, stopping at the first matching template.
.. code-block:: python
loader = FileSystemLoader(["/override/templates", "/default/templates"])
:param searchpath: A path, or list of paths, to the directory that
contains the templates.
:param encoding: Use this encoding to read the text from template
files.
:param followlinks: Follow symbolic links in the path.
.. versionchanged:: 2.8
Added the ``followlinks`` parameter.
"""
def __init__(self, searchpath, encoding="utf-8", followlinks=False):
if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
searchpath = [searchpath]
self.searchpath = list(searchpath)
self.encoding = encoding
self.followlinks = followlinks
def get_source(self, environment, template):
pieces = split_template_path(template)
for searchpath in self.searchpath:
filename = os.path.join(searchpath, *pieces)
f = open_if_exists(filename)
if f is None:
continue
try:
contents = f.read().decode(self.encoding)
finally:
f.close()
mtime = os.path.getmtime(filename)
def uptodate():
try:
return os.path.getmtime(filename) == mtime
except OSError:
return False
return contents, filename, uptodate
raise TemplateNotFound(template)
def list_templates(self):
found = set()
for searchpath in self.searchpath:
walk_dir = os.walk(searchpath, followlinks=self.followlinks)
for dirpath, _, filenames in walk_dir:
for filename in filenames:
template = (
os.path.join(dirpath, filename)[len(searchpath) :]
.strip(os.path.sep)
.replace(os.path.sep, "/")
)
if template[:2] == "./":
template = template[2:]
if template not in found:
found.add(template)
return sorted(found)
class PackageLoader(BaseLoader):
"""Load templates from a directory in a Python package.
:param package_name: Import name of the package that contains the
template directory.
:param package_path: Directory within the imported package that
contains the templates.
:param encoding: Encoding of template files.
The following example looks up templates in the ``pages`` directory
within the ``project.ui`` package.
.. code-block:: python
loader = PackageLoader("project.ui", "pages")
Only packages installed as directories (standard pip behavior) or
zip/egg files (less common) are supported. The Python API for
introspecting data in packages is too limited to support other
installation methods the way this loader requires.
There is limited support for :pep:`420` namespace packages. The
template directory is assumed to only be in one namespace
contributor. Zip files contributing to a namespace are not
supported.
.. versionchanged:: 3.0
No longer uses ``setuptools`` as a dependency.
.. versionchanged:: 3.0
Limited PEP 420 namespace package support.
"""
def __init__(self, package_name, package_path="templates", encoding="utf-8"):
if package_path == os.path.curdir:
package_path = ""
elif package_path[:2] == os.path.curdir + os.path.sep:
package_path = package_path[2:]
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
self.package_path = package_path
self.package_name = package_name
self.encoding = encoding
# Make sure the package exists. This also makes namespace
# packages work, otherwise get_loader returns None.
import_module(package_name)
spec = importlib.util.find_spec(package_name)
self._loader = loader = spec.loader
self._archive = None
self._template_root = None
if isinstance(loader, zipimport.zipimporter):
self._archive = loader.archive
pkgdir = next(iter(spec.submodule_search_locations))
self._template_root = os.path.join(pkgdir, package_path)
elif spec.submodule_search_locations:
# This will be one element for regular packages and multiple
# for namespace packages.
for root in spec.submodule_search_locations:
root = os.path.join(root, package_path)
if os.path.isdir(root):
self._template_root = root
break
if self._template_root is None:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)
def get_source(self, environment, template):
p = os.path.join(self._template_root, *split_template_path(template))
if self._archive is None:
# Package is a directory.
if not os.path.isfile(p):
raise TemplateNotFound(template)
with open(p, "rb") as f:
source = f.read()
mtime = os.path.getmtime(p)
def up_to_date():
return os.path.isfile(p) and os.path.getmtime(p) == mtime
else:
# Package is a zip file.
try:
source = self._loader.get_data(p)
except OSError:
raise TemplateNotFound(template)
# Could use the zip's mtime for all template mtimes, but
# would need to safely reload the module if it's out of
# date, so just report it as always current.
up_to_date = None
return source.decode(self.encoding), p, up_to_date
def list_templates(self):
results = []
if self._archive is None:
# Package is a directory.
offset = len(self._template_root)
for dirpath, _, filenames in os.walk(self._template_root):
dirpath = dirpath[offset:].lstrip(os.path.sep)
results.extend(
os.path.join(dirpath, name).replace(os.path.sep, "/")
for name in filenames
)
else:
if not hasattr(self._loader, "_files"):
raise TypeError(
"This zip import does not have the required"
" metadata to list templates."
)
# Package is a zip file.
prefix = (
self._template_root[len(self._archive) :].lstrip(os.path.sep)
+ os.path.sep
)
offset = len(prefix)
for name in self._loader._files.keys():
# Find names under the templates directory that aren't directories.
if name.startswith(prefix) and name[-1] != os.path.sep:
results.append(name[offset:].replace(os.path.sep, "/"))
results.sort()
return results
class DictLoader(BaseLoader):
"""Loads a template from a Python dict mapping template names to
template source. This loader is useful for unittesting:
>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
"""
def __init__(self, mapping):
self.mapping = mapping
def get_source(self, environment, template):
if template in self.mapping:
source = self.mapping[template]
return source, None, lambda: source == self.mapping.get(template)
raise TemplateNotFound(template)
def list_templates(self):
return sorted(self.mapping)
class FunctionLoader(BaseLoader):
"""A loader that is passed a function which does the loading. The
function receives the name of the template and has to return either
a string with the template source, a tuple in the form ``(source,
filename, uptodatefunc)`` or `None` if the template does not exist.
>>> def load_template(name):
... if name == 'index.html':
... return '...'
...
>>> loader = FunctionLoader(load_template)
The `uptodatefunc` is a function that is called if autoreload is enabled
and has to return `True` if the template is still up to date. For more
details have a look at :meth:`BaseLoader.get_source` which has the same
return value.
"""
def __init__(self, load_func):
self.load_func = load_func
def get_source(self, environment, template):
rv = self.load_func(template)
if rv is None:
raise TemplateNotFound(template)
elif isinstance(rv, str):
return rv, None, None
return rv
class PrefixLoader(BaseLoader):
"""A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
by loading ``'app2/index.html'`` the file from the second.
"""
def __init__(self, mapping, delimiter="/"):
self.mapping = mapping
self.delimiter = delimiter
def get_loader(self, template):
try:
prefix, name = template.split(self.delimiter, 1)
loader = self.mapping[prefix]
except (ValueError, KeyError):
raise TemplateNotFound(template)
return loader, name
def get_source(self, environment, template):
loader, name = self.get_loader(template)
try:
return loader.get_source(environment, name)
except TemplateNotFound:
# re-raise the exception with the correct filename here.
# (the one that includes the prefix)
raise TemplateNotFound(template)
@internalcode
def load(self, environment, name, globals=None):
loader, local_name = self.get_loader(name)
try:
return loader.load(environment, local_name, globals)
except TemplateNotFound:
# re-raise the exception with the correct filename here.
# (the one that includes the prefix)
raise TemplateNotFound(name)
def list_templates(self):
result = []
for prefix, loader in self.mapping.items():
for template in loader.list_templates():
result.append(prefix + self.delimiter + template)
return result
class ChoiceLoader(BaseLoader):
"""This loader works like the `PrefixLoader` just that no prefix is
specified. If a template could not be found by one loader the next one
is tried.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/system/templates')
... ])
This is useful if you want to allow users to override builtin templates
from a different location.
"""
def __init__(self, loaders):
self.loaders = loaders
def get_source(self, environment, template):
for loader in self.loaders:
try:
return loader.get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
@internalcode
def load(self, environment, name, globals=None):
for loader in self.loaders:
try:
return loader.load(environment, name, globals)
except TemplateNotFound:
pass
raise TemplateNotFound(name)
def list_templates(self):
found = set()
for loader in self.loaders:
found.update(loader.list_templates())
return sorted(found)
class _TemplateModule(ModuleType):
"""Like a normal module but with support for weak references"""
class ModuleLoader(BaseLoader):
"""This loader loads templates from precompiled templates.
Example usage:
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
Templates can be precompiled with :meth:`Environment.compile_templates`.
"""
has_source_access = False
def __init__(self, path):
package_name = f"_jinja2_module_templates_{id(self):x}"
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if not isinstance(path, abc.Iterable) or isinstance(path, str):
path = [path]
mod.__path__ = [os.fspath(p) for p in path]
sys.modules[package_name] = weakref.proxy(
mod, lambda x: sys.modules.pop(package_name, None)
)
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
@staticmethod
def get_template_key(name):
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
@staticmethod
def get_module_filename(name):
return ModuleLoader.get_template_key(name) + ".py"
@internalcode
def load(self, environment, name, globals=None):
key = self.get_template_key(name)
module = f"{self.package_name}.{key}"
mod = getattr(self.module, module, None)
if mod is None:
try:
mod = __import__(module, None, None, ["root"])
except ImportError:
raise TemplateNotFound(name)
# remove the entry from sys.modules, we only want the attribute
# on the module object we have stored on the loader.
sys.modules.pop(module, None)
return environment.template_class.from_module_dict(
environment, mod.__dict__, globals
)
| {
"repo_name": "mitsuhiko/jinja2",
"path": "src/jinja2/loaders.py",
"copies": "3",
"size": "19892",
"license": "bsd-3-clause",
"hash": 2879844534511713000,
"line_mean": 34.1448763251,
"line_max": 83,
"alpha_frac": 0.6089885381,
"autogenerated": false,
"ratio": 4.557159221076747,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6666147759176747,
"avg_score": null,
"num_lines": null
} |
""" API annotations and assorted wrappers. """
import json, traceback, bson
import api
from api.common import WebSuccess, WebError, WebException, InternalException, SevereInternalException
from datetime import datetime
from functools import wraps
from flask import session, request, abort
write_logs_to_db = False # Default value, can be overwritten by api.py
log = api.logger.use(__name__)
_get_message = lambda exception: exception.args[0]
def log_action(f):
"""
Logs a given request if available.
"""
@wraps(f)
def wrapper(*args, **kwds):
"""
Provides contextual information to the logger.
"""
log_information = {
"name": "{}.{}".format(f.__module__, f.__name__),
"args": args,
"kwargs": kwds,
"result": None,
}
try:
log_information["result"] = f(*args, **kwds)
except WebException as error:
log_information["exception"] = _get_message(error)
raise
finally:
log.info(log_information)
return log_information["result"]
return wrapper
def api_wrapper(f):
"""
Wraps api routing and handles potential exceptions
"""
@wraps(f)
def wrapper(*args, **kwds):
web_result = {}
wrapper_log = api.logger.use(f.__module__)
try:
web_result = f(*args, **kwds)
except WebException as error:
web_result = WebError(_get_message(error), error.data)
except InternalException as error:
message = _get_message(error)
if type(error) == SevereInternalException:
wrapper_log.critical(traceback.format_exc())
web_result = WebError("There was a critical internal error. Contact an administrator.")
else:
wrapper_log.error(traceback.format_exc())
web_result = WebError(message)
except Exception as error:
wrapper_log.error(traceback.format_exc())
return bson.json_util.dumps(web_result)
return wrapper
def require_login(f):
"""
Wraps routing functions that require a user to be logged in
"""
@wraps(f)
def wrapper(*args, **kwds):
if not api.auth.is_logged_in():
raise WebException("You must be logged in")
return f(*args, **kwds)
return wrapper
def require_teacher(f):
"""
Wraps routing functions that require a user to be a teacher
"""
@require_login
@wraps(f)
def wrapper(*args, **kwds):
if not api.user.is_teacher() or not api.config.enable_teachers:
raise WebException("You must be a teacher!")
return f(*args, **kwds)
return wrapper
def check_csrf(f):
@wraps(f)
@require_login
def wrapper(*args, **kwds):
if 'token' not in session:
raise InternalException("CSRF token not in session")
if 'token' not in request.form:
raise InternalException("CSRF token not in form")
if session['token'] != request.form['token']:
raise InternalException("CSRF token is not correct")
return f(*args, **kwds)
return wrapper
def deny_blacklisted(f):
@wraps(f)
@require_login
def wrapper(*args, **kwds):
#if auth.is_blacklisted(session['tid']):
# abort(403)
return f(*args, **kwds)
return wrapper
def require_admin(f):
"""
Wraps routing functions that require a user to be an admin
"""
@wraps(f)
def wrapper(*args, **kwds):
if not api.user.is_admin():
raise WebException("You do not have permission to view this page.")
return f(*args, **kwds)
return wrapper
def block_before_competition(return_result):
"""
Wraps a routing function that should be blocked before the start time of the competition
"""
def decorator(f):
"""
Inner decorator
"""
@wraps(f)
def wrapper(*args, **kwds):
if datetime.utcnow().timestamp() > api.config.start_time.timestamp():
return f(*args, **kwds)
else:
return return_result
return wrapper
return decorator
def block_after_competition(return_result):
"""
Wraps a routing function that should be blocked after the end time of the competition
"""
def decorator(f):
"""
Inner decorator
"""
@wraps(f)
def wrapper(*args, **kwds):
if datetime.utcnow().timestamp() < api.config.end_time.timestamp():
return f(*args, **kwds)
else:
return return_result
return wrapper
return decorator
| {
"repo_name": "stuyCTF/stuyCTF-Platform",
"path": "api/api/annotations.py",
"copies": "1",
"size": "4732",
"license": "mit",
"hash": 224814695286586720,
"line_mean": 26.8352941176,
"line_max": 103,
"alpha_frac": 0.5845308538,
"autogenerated": false,
"ratio": 4.169162995594713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.003518724960218898,
"num_lines": 170
} |
""" API annotations and assorted wrappers. """
import json, traceback
import api
from api.common import WebSuccess, WebError, WebException, InternalException, SevereInternalException
from datetime import datetime
from functools import wraps
from flask import session, request, abort
write_logs_to_db = False # Default value, can be overwritten by api.py
log = api.logger.use(__name__)
_get_message = lambda exception: exception.args[0]
def log_action(f):
"""
Logs a given request if available.
"""
@wraps(f)
def wrapper(*args, **kwds):
"""
Provides contextual information to the logger.
"""
log_information = {
"name": "{}.{}".format(f.__module__, f.__name__),
"args": args,
"kwargs": kwds,
"result": None,
}
try:
log_information["result"] = f(*args, **kwds)
except WebException as error:
log_information["exception"] = _get_message(error)
raise
finally:
log.info(log_information)
return log_information["result"]
return wrapper
def api_wrapper(f):
"""
Wraps api routing and handles potential exceptions
"""
@wraps(f)
def wrapper(*args, **kwds):
web_result = {}
wrapper_log = api.logger.use(f.__module__)
try:
web_result = f(*args, **kwds)
except WebException as error:
web_result = WebError(_get_message(error), error.data)
except InternalException as error:
message = _get_message(error)
if type(error) == SevereInternalException:
wrapper_log.critical(traceback.format_exc())
web_result = WebError("There was a critical internal error. Contact an administrator.")
else:
wrapper_log.error(traceback.format_exc())
web_result = WebError(message)
except Exception as error:
wrapper_log.error(traceback.format_exc())
return json.dumps(web_result)
return wrapper
def require_login(f):
"""
Wraps routing functions that require a user to be logged in
"""
@wraps(f)
def wrapper(*args, **kwds):
if not api.auth.is_logged_in():
raise WebException("You must be logged in")
return f(*args, **kwds)
return wrapper
def require_teacher(f):
"""
Wraps routing functions that require a user to be a teacher
"""
@require_login
@wraps(f)
def wrapper(*args, **kwds):
if not api.user.is_teacher() or not api.config.enable_teachers:
raise WebException("You must be a teacher!")
return f(*args, **kwds)
return wrapper
def check_csrf(f):
@wraps(f)
@require_login
def wrapper(*args, **kwds):
if 'token' not in session:
raise InternalException("CSRF token not in session")
if 'token' not in request.form:
raise InternalException("CSRF token not in form")
if session['token'] != request.form['token']:
raise InternalException("CSRF token is not correct")
return f(*args, **kwds)
return wrapper
def deny_blacklisted(f):
@wraps(f)
@require_login
def wrapper(*args, **kwds):
#if auth.is_blacklisted(session['tid']):
# abort(403)
return f(*args, **kwds)
return wrapper
def require_admin(f):
"""
Wraps routing functions that require a user to be an admin
"""
@wraps(f)
def wrapper(*args, **kwds):
if not session.get('admin', False):
raise WebException("You must be an admin!")
return f(*args, **kwds)
return wrapper
def block_before_competition(return_result):
"""
Wraps a routing function that should be blocked before the start time of the competition
"""
def decorator(f):
"""
Inner decorator
"""
@wraps(f)
def wrapper(*args, **kwds):
if datetime.utcnow().timestamp() > api.config.start_time.timestamp():
return f(*args, **kwds)
else:
return return_result
return wrapper
return decorator
def block_after_competition(return_result):
"""
Wraps a routing function that should be blocked after the end time of the competition
"""
def decorator(f):
"""
Inner decorator
"""
@wraps(f)
def wrapper(*args, **kwds):
if datetime.utcnow().timestamp() < api.config.end_time.timestamp():
return f(*args, **kwds)
else:
return return_result
return wrapper
return decorator
| {
"repo_name": "PATechmasters/techmaster-ctf",
"path": "api/api/annotations.py",
"copies": "9",
"size": "4700",
"license": "mit",
"hash": -8689923633381090000,
"line_mean": 26.6470588235,
"line_max": 103,
"alpha_frac": 0.5829787234,
"autogenerated": false,
"ratio": 4.1852181656277825,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9268196889027782,
"avg_score": null,
"num_lines": null
} |
"""API Approval
Presents the revised policy created by Security Fairy,
and waits for the user to Approve or Cancel the policy
change.
"""
from __future__ import print_function
import string
import json
import boto3
from requests.utils import unquote
from botocore.exceptions import ProfileNotFound
try:
SESSION = boto3.session.Session(profile_name='training',
region_name='us-east-1')
except ProfileNotFound as pnf:
SESSION = boto3.session.Session()
def lambda_handler(event, context):
""" Executed by the Lambda service.
Returns the API website for users who are at the Approve
or Cancel stage of the Security Fairy tool.
"""
method = event['httpMethod']
domain = get_domain(event)
if method == 'GET':# and event['queryStringParameters'] is not None:
return api_website(event, domain)
# Default API Response returns an error
return {
"statusCode": 500,
"headers":{
"Content-Type":"application/json"
},
"body":"Something Broke"
}
def get_domain(event):
"""Return the domain that will display the new policy."""
if event['headers'] is None:
return "https://testinvocation/approve"
if 'amazonaws.com' in event['headers']['Host']:
return "https://{domain}/{stage}/".format( domain=event['headers']['Host'],
stage=event['requestContext']['stage'])
else:
return "https://{domain}/".format(domain=event['headers']['Host'])
def api_website(event, domain):
"""Displays a front end website for Approval or Cancel by the user."""
dynamodb_client = SESSION.client('dynamodb')
entity_arn = ''
entity_name = ''
dynamodb_client = SESSION.client('dynamodb')
try:
execution_id = event['queryStringParameters']['execution-id']
print(execution_id)
response_item = dynamodb_client.get_item( TableName=os.environ['dynamodb_table'],
Key={
"execution_id": {
"S": "{execution_id}".format(execution_id=execution_id)
}
})['Item']
missing_permissions = response_item['missing_permissions']['S']
entity_arn = response_item['entity_arn']['S']
entity_name = entity_arn.split('/')[1]
print(response_item)
except Exception as error:
print(error)
new_policy = {"Error": "This executionId has either expired or is invalid."}
body = """
<html>
<body bgcolor=\"#E6E6FA\">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.code {
max-height: 500px;
width: 600px;
overflow: scroll;
text-align: left;
margin-bottom: 20px;
}
</style>
<script>
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var dict = {};
var executionId = getUrlParameter('execution-id');
dict['execution_id']=executionId;
function submitRequest(approval){
$.ajax({
type: 'POST',
headers: {
'Content-Type':'application/json',
'Accept':'text/html'
},
url:'$domain'+approval,
crossDomain: true,
data: JSON.stringify(dict),
dataType: 'text',
success: function(responseData) {
document.getElementById("output").innerHTML = responseData;
},
error: function (responseData) {
alert('POST failed: '+ JSON.stringify(responseData));
}
});
};
function redirect(){
var url = "https://console.aws.amazon.com/iam/home?region=us-east-1#/roles/$entity_name";
document.location.href = url;
};
$(document).ready(function(){
document.getElementById("output").innerHTML = JSON.stringify($missing_permissions, null, "\\t");
$("#approve").click(function(){
console.log("Approve button clicked");
submitRequest("approve");
setTimeout(redirect,2000);
});
$("#deny").click(function(){
console.log("deny button clicked");
submitRequest("deny");
});
});
</script>
</head>
<body>
<center>
<title>IAM Security Fairy</title>
<h1><span class="glyphicon glyphicon-fire text-danger" ></span> IAM Security Fairy</h1>
<h2></h2>
<div class="code"><pre>$entity_arn</pre></div>
<div class="code"><pre id='output'></pre></div>
<button class="btn btn-primary" id='approve'>Apply</button>
<button class="btn btn-danger" id='deny'>Cancel</button>
</center>
</body>
</html>"""
replace_dict = dict(missing_permissions=missing_permissions, domain=domain, entity_arn=entity_arn, entity_name=entity_name)
string.Template(body).safe_substitute(replace_dict)
return {
"statusCode": 200,
"headers": {
"Content-Type": "text/html",
"Access-Control-Allow-Origin": "*"
},
"body": string.Template(body).safe_substitute(replace_dict)
}
if __name__ == '__main__':
EVENT = { }
lambda_handler(EVENT, {})
| {
"repo_name": "1Strategy/security-fairy",
"path": "api_missing_permissions.py",
"copies": "1",
"size": "6459",
"license": "apache-2.0",
"hash": -2986150212167216000,
"line_mean": 34.2950819672,
"line_max": 220,
"alpha_frac": 0.5215977706,
"autogenerated": false,
"ratio": 4.323293172690763,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5344890943290762,
"avg_score": null,
"num_lines": null
} |
"""API around S3, SQS, and MK64 database"""
import boto
import json
import multiprocessing
import os
import requests
import time
import uuid
import syslog
from subprocess import call
from boto.sqs.message import Message
from boto.sqs.message import RawMessage
from boto.exception import *
import boto.utils
from const import *
class EC2(object):
def killself(self):
asg = boto.connect_autoscale()
instanceID = boto.utils.get_instance_identity()['document']['instanceId']
asg.terminate_instance(instanceID)
def get_launch_time(self):
#TODO This.
pass
class SQS(object):
def __init__(self, queue_names):
self.conn = boto.connect_sqs()
self.queues = {q : self.conn.get_queue(q) for q in queue_names}
def delete_message(self, msg):
return msg.delete()
def listen(self, queue_name):
try:
q = self.queues[queue_name]
raw_msg = q.get_messages(wait_time_seconds=WAIT)[0]
msg = json.loads(raw_msg.get_body())
url = str(msg['video_url'])
video_id = str(msg['id'])
rv = {'msg':raw_msg,'id':video_id,'url':url}
return rv
except UnicodeDecodeError:
filename = None
except Exception as ex:
# No messages
return None
def write(self, queue_name, payload):
try:
msg = Message()
msg.set_body(payload)
return self.queues[queue_name].write(msg)
except SQSError:
return None
class S3(object):
def __init__(self, bucket_names):
self.conn = boto.connect_s3()
self.buckets = {b : self.conn.get_bucket(b) for b in bucket_names}
def upload(self, bucket, file_path):
k = boto.s3.key.Key(self.buckets[bucket])
name = file_path.split('/')[-1]
k.key = 'raw/%s/%s' % (str(uuid.uuid1()), name)
k.set_contents_from_filename(file_path)
return k.key
def download_url(self, data_type, url, data_id):
filename = None
if 'race' in data_type:
name = 'race-videos'
elif 'session' in data_type:
name = 'session-videos'
elif 'audio' in data_type:
name = 'race-audio'
else:
raise ValueError("Invalid video type")
try:
key_name = url.split('.com/')[-1]
bucket = self.buckets[name]
key = bucket.get_key(key_name)
ext = url.split('.')[-1]
filename = '%s%s.%s' % (name, data_id, ext)
key.get_contents_to_filename(filename)
except:
filename = None
finally:
return filename
class DB(object):
def __init__(self):
self.database = 'http://n64storageflask-env.elasticbeanstalk.com'
self.port = 80
def get_regions(self, race_id):
url = '%s:%d/races/%d' % (self.database, self.port, race_id)
res = requests.get(url)
if res.ok:
return res.json()['player_regions']
else:
print 'DB Error: ' + res.json()['message']
return None
def post_events(self, race_id, events):
responses = []
url = '%s:%d/races/%s/events' % (self.database, self.port, race_id)
for e in events:
payload = json.dumps(e)
header = {'Content-Type': 'application/json'}
res = requests.post(url, data=payload, headers=header)
if res.ok:
responses.append(res.json()['id'])
else:
responses.append(None)
return responses
def post_race(self, session_id, payload):
"""Sends race JSON object to database for storage"""
url = '%s:%d/sessions/%d/races' % (self.database, self.port, session_id)
headers = {'content-type': 'application/json'}
res = requests.post(url, data=json.dumps(payload), headers=headers)
if res.ok:
return res.json()['id']
else:
return None
def update_race(self, race_id, payload):
"""Sends race JSON object to database for storage"""
url = '%s:%d/races/%s' % (self.database, self.port, race_id)
headers = {'content-type': 'application/json'}
res = requests.put(url, data=json.dumps(payload), headers=headers)
return res.ok
def update_session(self, session_id):
"""Sends race JSON object to database for storage"""
url = '%s:%d/sessions/%s' % (self.database, self.port, session_id)
headers = {'content-type': 'application/json'}
payload = {
'video_split' : True
}
res = requests.put(url, data=json.dumps(payload), headers=headers)
return res.ok
| {
"repo_name": "kartyboyz/n64-img-processing",
"path": "api.py",
"copies": "1",
"size": "4768",
"license": "mit",
"hash": 6379815850740521000,
"line_mean": 31.4353741497,
"line_max": 81,
"alpha_frac": 0.5652265101,
"autogenerated": false,
"ratio": 3.7425431711145998,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48077696812146,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API disponibile'
apiAttachNotAvailable = u'Non disponibile'
apiAttachPendingAuthorization = u'In attesa di autorizzazione'
apiAttachRefused = u'Rifiutato'
apiAttachSuccess = u'Riuscito'
apiAttachUnknown = u'Sconosciuto'
budDeletedFriend = u"Eliminato dall'elenco amici"
budFriend = u'Amico'
budNeverBeenFriend = u'Mai stato in elenco amici'
budPendingAuthorization = u'In attesa di autorizzazione'
budUnknown = u'Sconosciuto'
cfrBlockedByRecipient = u'Chiamata bloccata dal destinatario'
cfrMiscError = u'Errori vari'
cfrNoCommonCodec = u'Nessun codec comune'
cfrNoProxyFound = u'Nessun proxy trovato'
cfrNotAuthorizedByRecipient = u'Utente corrente non autorizzato dal destinatario'
cfrRecipientNotFriend = u'Il destinatario non \xe8 un amico'
cfrRemoteDeviceError = u'Problema con la periferica audio remota'
cfrSessionTerminated = u'Sessione conclusa'
cfrSoundIOError = u'Errore I/O audio'
cfrSoundRecordingError = u'Errore di registrazione audio'
cfrUnknown = u'Sconosciuto'
cfrUserDoesNotExist = u'Utente o numero di telefono inesistente'
cfrUserIsOffline = u'Non \xe8 in linea'
chsAllCalls = u'Finestra versione'
chsDialog = u'Dialogo'
chsIncomingCalls = u'In attesa di riscontro'
chsLegacyDialog = u'Finestra versione'
chsMissedCalls = u'Dialogo'
chsMultiNeedAccept = u'In attesa di riscontro'
chsMultiSubscribed = u'Multi-iscritti'
chsOutgoingCalls = u'Multi-iscritti'
chsUnknown = u'Sconosciuto'
chsUnsubscribed = u'Disiscritto'
clsBusy = u'Occupato'
clsCancelled = u'Cancellato'
clsEarlyMedia = u'Esecuzione Early Media in corso (Playing Early Media)'
clsFailed = u'spiacente, chiamata non riuscita!'
clsFinished = u'Terminata'
clsInProgress = u'Chiamata in corso'
clsLocalHold = u'Chiamata in sospeso da utente locale'
clsMissed = u'Chiamata persa'
clsOnHold = u'Sospesa'
clsRefused = u'Rifiutato'
clsRemoteHold = u'Chiamata in sospeso da utente remoto'
clsRinging = u'in chiamata'
clsRouting = u'Routing'
clsTransferred = u'Sconosciuto'
clsTransferring = u'Sconosciuto'
clsUnknown = u'Sconosciuto'
clsUnplaced = u'Mai effettuata'
clsVoicemailBufferingGreeting = u'Buffering del saluto in corso'
clsVoicemailCancelled = u'La voicemail \xe8 stata annullata'
clsVoicemailFailed = u'Messaggio vocale non inviato'
clsVoicemailPlayingGreeting = u'Esecuzione saluto'
clsVoicemailRecording = u'Registrazione del messaggio vocale'
clsVoicemailSent = u'La voicemail \xe8 stata inviata'
clsVoicemailUploading = u'Caricamento voicemail in corso'
cltIncomingP2P = u'Chiamata Peer-to-Peer in arrivo'
cltIncomingPSTN = u'Telefonata in arrivo'
cltOutgoingP2P = u'Chiamata Peer-to-Peer in uscita'
cltOutgoingPSTN = u'Telefonata in uscita'
cltUnknown = u'Sconosciuto'
cmeAddedMembers = u'Membri aggiunti'
cmeCreatedChatWith = u'Chat creata con'
cmeEmoted = u'Sconosciuto'
cmeLeft = u'Uscito'
cmeSaid = u'Detto'
cmeSawMembers = u'Membri visti'
cmeSetTopic = u'Argomento impostato'
cmeUnknown = u'Sconosciuto'
cmsRead = u'Letto'
cmsReceived = u'Ricevuto'
cmsSending = u'Sto inviando...'
cmsSent = u'Inviato'
cmsUnknown = u'Sconosciuto'
conConnecting = u'In connessione'
conOffline = u'Non in linea'
conOnline = u'In linea'
conPausing = u'In pausa'
conUnknown = u'Sconosciuto'
cusAway = u'Torno subito'
cusDoNotDisturb = u'Occupato'
cusInvisible = u'Invisibile'
cusLoggedOut = u'Non in linea'
cusNotAvailable = u'Non disponibile'
cusOffline = u'Non in linea'
cusOnline = u'In linea'
cusSkypeMe = u'Libero per la Chat'
cusUnknown = u'Sconosciuto'
cvsBothEnabled = u'Invio e ricezione video'
cvsNone = u'Assenza video'
cvsReceiveEnabled = u'Ricezione video'
cvsSendEnabled = u'Invio video'
cvsUnknown = u''
grpAllFriends = u'Tutti gli amici'
grpAllUsers = u'Tutti gli utenti'
grpCustomGroup = u'Personalizzato'
grpOnlineFriends = u'Amici online'
grpPendingAuthorizationFriends = u'In attesa di autorizzazione'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Utenti contattati di recente'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Amici Skype'
grpSkypeOutFriends = u'Amici SkypeOut'
grpUngroupedFriends = u'Amici non di gruppo'
grpUnknown = u'Sconosciuto'
grpUsersAuthorizedByMe = u'Autorizzato da me'
grpUsersBlockedByMe = u'Bloccato da me'
grpUsersWaitingMyAuthorization = u'In attesa di mia autorizzazione'
leaAddDeclined = u'Rifiutato'
leaAddedNotAuthorized = u'Deve essere autorizzato'
leaAdderNotFriend = u'Deve essere un amico'
leaUnknown = u'Sconosciuto'
leaUnsubscribe = u'Disiscritto'
leaUserIncapable = u'Utente incapace'
leaUserNotFound = u'Utente non trovato'
olsAway = u'Torno subito'
olsDoNotDisturb = u'Occupato'
olsNotAvailable = u'Non disponibile'
olsOffline = u'Non in linea'
olsOnline = u'In linea'
olsSkypeMe = u'Libero per la Chat'
olsSkypeOut = u'SkypeOut...'
olsUnknown = u'Sconosciuto'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Femmina'
usexMale = u'Maschio'
usexUnknown = u'Sconosciuto'
vmrConnectError = u'Errore di connessione'
vmrFileReadError = u'Errore lettura file'
vmrFileWriteError = u'Errore scrittura file'
vmrMiscError = u'Errori vari'
vmrNoError = u'Nessun errore'
vmrNoPrivilege = u'Nessun privilegio voicemail'
vmrNoVoicemail = u'Voicemail inesistente'
vmrPlaybackError = u'Errore di riproduzione'
vmrRecordingError = u'Errore di registrazione'
vmrUnknown = u'Sconosciuto'
vmsBlank = u'Vuota'
vmsBuffering = u'Buffering'
vmsDeleting = u'Eliminazione in corso'
vmsDownloading = u'Download in corso'
vmsFailed = u'Fallita'
vmsNotDownloaded = u'Non scaricata'
vmsPlayed = u'Riprodotta'
vmsPlaying = u'Riproduzione in corso'
vmsRecorded = u'Registrata'
vmsRecording = u'Registrazione del messaggio vocale'
vmsUnknown = u'Sconosciuto'
vmsUnplayed = u'Non riprodotta'
vmsUploaded = u'Caricata'
vmsUploading = u'Caricamento in corso'
vmtCustomGreeting = u'Saluto personalizzato'
vmtDefaultGreeting = u'Saluto predefinito'
vmtIncoming = u'Messaggio vocale in arrivo'
vmtOutgoing = u'In uscita'
vmtUnknown = u'Sconosciuto'
vssAvailable = u'Disponibile'
vssNotAvailable = u'Non disponibile'
vssPaused = u'In pausa'
vssRejected = u'Rifiutata'
vssRunning = u'In corso'
vssStarting = u'Avvio in corso'
vssStopping = u'Arresto in corso'
vssUnknown = u'Sconosciuto'
| {
"repo_name": "iandev/HarvestMood",
"path": "Skype4Py/Skype4Py/lang/it.py",
"copies": "23",
"size": "7088",
"license": "mit",
"hash": -5589727896447491000,
"line_mean": 36.9037433155,
"line_max": 81,
"alpha_frac": 0.8045993228,
"autogenerated": false,
"ratio": 2.6077998528329656,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0000652145558888744,
"num_lines": 187
} |
apiAttachAvailable = u'API dispon\xedvel'
apiAttachNotAvailable = u'N\xe3o dispon\xedvel'
apiAttachPendingAuthorization = u'Autoriza\xe7\xe3o pendente'
apiAttachRefused = u'Recusado'
apiAttachSuccess = u'Sucesso'
apiAttachUnknown = u'Desconhecido'
budDeletedFriend = u'Exclu\xeddo da lista de amigos'
budFriend = u'Amigo'
budNeverBeenFriend = u'Nunca esteve na Lista de Amigos'
budPendingAuthorization = u'Autoriza\xe7\xe3o pendente'
budUnknown = u'Desconhecido'
cfrBlockedByRecipient = u'Chamada bloqueada pelo destinat\xe1rio'
cfrMiscError = u'Erro diverso'
cfrNoCommonCodec = u'Nenhum codec comum'
cfrNoProxyFound = u'Proxy n\xe3o encontrado'
cfrNotAuthorizedByRecipient = u'O utilizador actual n\xe3o est\xe1 autorizado pelo destinat\xe1rio'
cfrRecipientNotFriend = u'Destinat\xe1rio n\xe3o \xe9 um amigo'
cfrRemoteDeviceError = u'Problema com dispositivo de som remoto'
cfrSessionTerminated = u'Sess\xe3o encerrada'
cfrSoundIOError = u'Erro de I/O de som'
cfrSoundRecordingError = u'Erro de grava\xe7\xe3o de voz'
cfrUnknown = u'Desconhecido'
cfrUserDoesNotExist = u'O utilizador/n\xfamero de telefone n\xe3o existe'
cfrUserIsOffline = u'Ela ou ele est\xe1 offline'
chsAllCalls = u'Di\xe1logo antigo'
chsDialog = u'Di\xe1logo'
chsIncomingCalls = u'Multi Precisa Aceitar'
chsLegacyDialog = u'Di\xe1logo antigo'
chsMissedCalls = u'Di\xe1logo'
chsMultiNeedAccept = u'Multi Precisa Aceitar'
chsMultiSubscribed = u'Multi Registados'
chsOutgoingCalls = u'Multi Registados'
chsUnknown = u'Desconhecido'
chsUnsubscribed = u'Assinatura eliminada'
clsBusy = u'Ocupado'
clsCancelled = u'Cancelada'
clsEarlyMedia = u'Tocar os dados iniciais (Early Media)'
clsFailed = u'Desculpa, falha na liga\xe7\xe3o!'
clsFinished = u'Terminado'
clsInProgress = u'Chamada em Andamento'
clsLocalHold = u'Em espera local'
clsMissed = u'Chamada Perdida'
clsOnHold = u'Em Espera'
clsRefused = u'Recusado'
clsRemoteHold = u'Em espera remota'
clsRinging = u'Chamando'
clsRouting = u'A encaminhar'
clsTransferred = u'Desconhecido'
clsTransferring = u'Desconhecido'
clsUnknown = u'Desconhecido'
clsUnplaced = u'Nunca foi adicionado'
clsVoicemailBufferingGreeting = u'A colocar sauda\xe7\xe3o na mem\xf3ria interm\xe9dia'
clsVoicemailCancelled = u'As mensagens (voicemail) foram canceladas'
clsVoicemailFailed = u'Falha no correio de voz'
clsVoicemailPlayingGreeting = u'A tocar Sauda\xe7\xe3o'
clsVoicemailRecording = u'Gravando correio de voz'
clsVoicemailSent = u'As mensagens (voicemail) foram enviadas'
clsVoicemailUploading = u'A carregar as mensagens (Voicemail)'
cltIncomingP2P = u'A receber chamada peer-to-peer'
cltIncomingPSTN = u'A receber chamada de voz'
cltOutgoingP2P = u'A efectuar chamada peer-to-peer'
cltOutgoingPSTN = u'A efectuar chamada telef\xf3nica'
cltUnknown = u'Desconhecido'
cmeAddedMembers = u'Membros adicionados'
cmeCreatedChatWith = u'Chat criado com'
cmeEmoted = u'Desconhecido'
cmeLeft = u'Saiu'
cmeSaid = u'Disse'
cmeSawMembers = u'Membros vistos'
cmeSetTopic = u'Definir t\xf3pico'
cmeUnknown = u'Desconhecido'
cmsRead = u'Ler'
cmsReceived = u'Recebido'
cmsSending = u'Enviando...'
cmsSent = u'Enviado'
cmsUnknown = u'Desconhecido'
conConnecting = u'Conectando'
conOffline = u'Offline'
conOnline = u'Online'
conPausing = u'A colocar em pausa'
conUnknown = u'Desconhecido'
cusAway = u'Ausente'
cusDoNotDisturb = u'Ocupado'
cusInvisible = u'Invis\xedvel'
cusLoggedOut = u'Offline'
cusNotAvailable = u'N\xe3o dispon\xedvel'
cusOffline = u'Offline'
cusOnline = u'Online'
cusSkypeMe = u'Skype Me'
cusUnknown = u'Desconhecido'
cvsBothEnabled = u'A enviar e receber v\xeddeo'
cvsNone = u'V\xeddeo n\xe3o dispon\xedvel'
cvsReceiveEnabled = u'A receber v\xeddeo'
cvsSendEnabled = u'A enviar v\xeddeo'
cvsUnknown = u''
grpAllFriends = u'Todos os amigos'
grpAllUsers = u'Todos os utilizadores'
grpCustomGroup = u'Personalizado'
grpOnlineFriends = u'Amigos on-line'
grpPendingAuthorizationFriends = u'Autoriza\xe7\xe3o pendente'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Utilizadores contactados recentemente'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Amigos Skype'
grpSkypeOutFriends = u'Amigos SkypeOut'
grpUngroupedFriends = u'Amigos n\xe3o organizados em grupos'
grpUnknown = u'Desconhecido'
grpUsersAuthorizedByMe = u'Autorizado por mim'
grpUsersBlockedByMe = u'Bloqueado por mim'
grpUsersWaitingMyAuthorization = u'\xc0 espera da minha autoriza\xe7\xe3o'
leaAddDeclined = u'Adicionamento recusado'
leaAddedNotAuthorized = u'O adicionado deve ser autorizado'
leaAdderNotFriend = u'Quem adiciona deve ser um amigo'
leaUnknown = u'Desconhecido'
leaUnsubscribe = u'Assinatura eliminada'
leaUserIncapable = u'Utilizador n\xe3o habilitado'
leaUserNotFound = u'Utilizador n\xe3o encontrado'
olsAway = u'Ausente'
olsDoNotDisturb = u'Ocupado'
olsNotAvailable = u'N\xe3o dispon\xedvel'
olsOffline = u'Offline'
olsOnline = u'Online'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Desconhecido'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Feminino'
usexMale = u'Masculino'
usexUnknown = u'Desconhecido'
vmrConnectError = u'Erro de liga\xe7\xe3o'
vmrFileReadError = u'Erro na leitura do ficheiro'
vmrFileWriteError = u'Erro a escrever ficheiro'
vmrMiscError = u'Erro diverso'
vmrNoError = u'N\xe3o h\xe1 erro'
vmrNoPrivilege = u'Sem privil\xe9gio de Voicemail'
vmrNoVoicemail = u'N\xe3o existe tal Voicemail'
vmrPlaybackError = u'Erro de reprodu\xe7\xe3o'
vmrRecordingError = u'Erro a gravar'
vmrUnknown = u'Desconhecido'
vmsBlank = u'Em branco'
vmsBuffering = u'A colocar na mem\xf3ria interm\xe9dia'
vmsDeleting = u'A apagar'
vmsDownloading = u'A transferir'
vmsFailed = u'Falhou'
vmsNotDownloaded = u'N\xe3o transferido'
vmsPlayed = u'Reproduzido'
vmsPlaying = u'A reproduzir'
vmsRecorded = u'Gravado'
vmsRecording = u'Gravando correio de voz'
vmsUnknown = u'Desconhecido'
vmsUnplayed = u'N\xe3o ouvido'
vmsUploaded = u'Carregado'
vmsUploading = u'A carregar'
vmtCustomGreeting = u'Sauda\xe7\xe3o personalizada'
vmtDefaultGreeting = u'Sauda\xe7\xe3o predefinida'
vmtIncoming = u'entrada de correio de voz'
vmtOutgoing = u'De sa\xedda'
vmtUnknown = u'Desconhecido'
vssAvailable = u'Dispon\xedvel'
vssNotAvailable = u'N\xe3o dispon\xedvel'
vssPaused = u'Em pausa'
vssRejected = u'Rejeitada'
vssRunning = u'Em curso'
vssStarting = u'A iniciar'
vssStopping = u'A terminar'
vssUnknown = u'Desconhecido'
| {
"repo_name": "djw8605/htcondor",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/pt.py",
"copies": "10",
"size": "7484",
"license": "apache-2.0",
"hash": 8144147113815494000,
"line_mean": 38.0213903743,
"line_max": 99,
"alpha_frac": 0.7795296633,
"autogenerated": false,
"ratio": 2.3895274584929758,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.8169057121792976,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API el\xe9rheto'
apiAttachNotAvailable = u'Nem el\xe9rheto'
apiAttachPendingAuthorization = u'F\xfcggoben l\xe9vo visszaigazol\xe1s'
apiAttachRefused = u'Elutas\xedtva'
apiAttachSuccess = u'Siker\xfclt'
apiAttachUnknown = u'Ismeretlen'
budDeletedFriend = u'T\xf6r\xf6lve a bar\xe1tok list\xe1j\xe1r\xf3l'
budFriend = u'Bar\xe1t'
budNeverBeenFriend = u'Soha nem volt a bar\xe1tok k\xf6z\xf6tt'
budPendingAuthorization = u'F\xfcggoben l\xe9vo visszaigazol\xe1s'
budUnknown = u'Ismeretlen'
cfrBlockedByRecipient = u'A h\xedv\xe1st blokkolta a c\xedmzett'
cfrMiscError = u'Egy\xe9b hiba'
cfrNoCommonCodec = u'Nincs szabv\xe1nyos kodek'
cfrNoProxyFound = u'Proxy nem tal\xe1lhat\xf3'
cfrNotAuthorizedByRecipient = u'A c\xedmzett nem igazolta vissza az aktu\xe1lis felhaszn\xe1l\xf3t'
cfrRecipientNotFriend = u'C\xedmzett nem tal\xe1lhat\xf3'
cfrRemoteDeviceError = u'Hanghiba a partnern\xe9l'
cfrSessionTerminated = u'V\xe9ge a h\xedv\xe1snak'
cfrSoundIOError = u'Hang I/O hiba'
cfrSoundRecordingError = u'Hangr\xf6gz\xedt\xe9si hiba'
cfrUnknown = u'Ismeretlen'
cfrUserDoesNotExist = u'A felhaszn\xe1l\xf3/telefonsz\xe1m nem l\xe9tezik'
cfrUserIsOffline = u'Kijelentkezett'
chsAllCalls = u'Kor\xe1bbi p\xe1rbesz\xe9d'
chsDialog = u'P\xe1rbesz\xe9d'
chsIncomingCalls = u'T\xf6bben akarj\xe1k fogadni'
chsLegacyDialog = u'Kor\xe1bbi p\xe1rbesz\xe9d'
chsMissedCalls = u'P\xe1rbesz\xe9d'
chsMultiNeedAccept = u'T\xf6bben akarj\xe1k fogadni'
chsMultiSubscribed = u'T\xf6bben feliratkoztak'
chsOutgoingCalls = u'T\xf6bben feliratkoztak'
chsUnknown = u'Ismeretlen'
chsUnsubscribed = u'Nincs feliratkozva'
clsBusy = u'Foglalt'
clsCancelled = u'Megszak\xedtva'
clsEarlyMedia = u'R\xe9gi zenesz\xe1m lej\xe1tsz\xe1sa'
clsFailed = u'A h\xedv\xe1s sikertelen.'
clsFinished = u'K\xe9sz'
clsInProgress = u'A besz\xe9lget\xe9s tart...'
clsLocalHold = u'Helyi h\xedv\xe1start\xe1s'
clsMissed = u'Nem fogadott h\xedv\xe1s tole:'
clsOnHold = u'H\xedv\xe1start\xe1s alatt'
clsRefused = u'Elutas\xedtva'
clsRemoteHold = u'T\xe1voli h\xedv\xe1start\xe1s'
clsRinging = u'h\xedv\xe1s'
clsRouting = u'\xdatvonal ir\xe1ny\xedt\xe1s'
clsTransferred = u'Ismeretlen'
clsTransferring = u'Ismeretlen'
clsUnknown = u'Ismeretlen'
clsUnplaced = u'Soha nem h\xedvta'
clsVoicemailBufferingGreeting = u'K\xf6sz\xf6nt\xe9s pufferel\xe9se'
clsVoicemailCancelled = u'Hang\xfczenet megszak\xedtva'
clsVoicemailFailed = u'Hang\xfczenet-hiba'
clsVoicemailPlayingGreeting = u'K\xf6sz\xf6nt\xe9s lej\xe1tsz\xe1sa'
clsVoicemailRecording = u'Hang\xfczenet felv\xe9tele t\xf6rt\xe9nik'
clsVoicemailSent = u'Hang\xfczenet elk\xfcldve'
clsVoicemailUploading = u'Hang\xfczenet felt\xf6lt\xe9se'
cltIncomingP2P = u'Bej\xf6vo k\xf6zvetlen h\xedv\xe1s'
cltIncomingPSTN = u'Bej\xf6vo telefonh\xedv\xe1s'
cltOutgoingP2P = u'Kimeno k\xf6zvetlen h\xedv\xe1s'
cltOutgoingPSTN = u'Kimeno telefonh\xedv\xe1s'
cltUnknown = u'Ismeretlen'
cmeAddedMembers = u'Hozz\xe1adott tagok'
cmeCreatedChatWith = u'Cseveg\xe9s l\xe9trehozva'
cmeEmoted = u'Ismeretlen'
cmeLeft = u'Elhagyta'
cmeSaid = u'Mondta'
cmeSawMembers = u'L\xe1tott tagok'
cmeSetTopic = u'T\xe9ma be\xe1ll\xedt\xe1sa'
cmeUnknown = u'Ismeretlen'
cmsRead = u'Elolvasva'
cmsReceived = u'Meg\xe9rkezett'
cmsSending = u'K\xfcld\xe9s...'
cmsSent = u'Elk\xfcldve'
cmsUnknown = u'Ismeretlen'
conConnecting = u'Kapcsol\xf3d\xe1s'
conOffline = u'Kijelentkezve'
conOnline = u'El\xe9rheto'
conPausing = u'Sz\xfcnetel'
conUnknown = u'Ismeretlen'
cusAway = u'Nincs a g\xe9pn\xe9l'
cusDoNotDisturb = u'Elfoglalt'
cusInvisible = u'L\xe1thatatlan'
cusLoggedOut = u'Kijelentkezve'
cusNotAvailable = u'Nem el\xe9rheto'
cusOffline = u'Kijelentkezve'
cusOnline = u'El\xe9rheto'
cusSkypeMe = u'H\xedv\xe1sk\xe9sz'
cusUnknown = u'Ismeretlen'
cvsBothEnabled = u'Vide\xf3 k\xfcld\xe9s \xe9s fogad\xe1s'
cvsNone = u'Nincs vide\xf3'
cvsReceiveEnabled = u'Vide\xf3 fogad\xe1s'
cvsSendEnabled = u'Vide\xf3 k\xfcld\xe9s'
cvsUnknown = u''
grpAllFriends = u'Minden bar\xe1t'
grpAllUsers = u'Minden felhaszn\xe1l\xf3'
grpCustomGroup = u'Egyedi'
grpOnlineFriends = u'El\xe9rheto bar\xe1tok'
grpPendingAuthorizationFriends = u'F\xfcggoben l\xe9vo visszaigazol\xe1s'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Legut\xf3bb keresett felhaszn\xe1l\xf3k'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype bar\xe1tok'
grpSkypeOutFriends = u'SkypeOut bar\xe1tok'
grpUngroupedFriends = u'Nem csoportos\xedtott bar\xe1tok'
grpUnknown = u'Ismeretlen'
grpUsersAuthorizedByMe = u'Visszaigazoltak'
grpUsersBlockedByMe = u'Blokkoltak'
grpUsersWaitingMyAuthorization = u'Visszaigazol\xe1sra v\xe1rakoz\xf3k'
leaAddDeclined = u'Hozz\xe1ad\xe1s elutas\xedtva'
leaAddedNotAuthorized = u'A hozz\xe1adott szem\xe9lyt vissza kell igazolni'
leaAdderNotFriend = u'A hozz\xe1ad\xf3nak bar\xe1tnak kell lennie'
leaUnknown = u'Ismeretlen'
leaUnsubscribe = u'Nincs feliratkozva'
leaUserIncapable = u'Felhaszn\xe1l\xf3 nem tudja'
leaUserNotFound = u'Felhaszn\xe1l\xf3 nem tal\xe1lhat\xf3'
olsAway = u'Nincs a g\xe9pn\xe9l'
olsDoNotDisturb = u'Elfoglalt'
olsNotAvailable = u'Nem el\xe9rheto'
olsOffline = u'Kijelentkezve'
olsOnline = u'El\xe9rheto'
olsSkypeMe = u'H\xedv\xe1sk\xe9sz'
olsSkypeOut = u'SkypeOut (?????-????)'
olsUnknown = u'Ismeretlen'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'no'
usexMale = u'f\xe9rfi'
usexUnknown = u'Ismeretlen'
vmrConnectError = u'Csatlakoz\xe1si hiba'
vmrFileReadError = u'F\xe1jl olvas\xe1si hiba'
vmrFileWriteError = u'F\xe1jl \xedr\xe1si hiba'
vmrMiscError = u'Egy\xe9b hiba'
vmrNoError = u'Nincs hiba'
vmrNoPrivilege = u'Nincs hang\xfczenet jogosults\xe1ga'
vmrNoVoicemail = u'Nincs ilyen hang\xfczenet'
vmrPlaybackError = u'Visszaj\xe1tsz\xe1si hiba'
vmrRecordingError = u'Hib\xe1s felv\xe9tel'
vmrUnknown = u'Ismeretlen'
vmsBlank = u'\xdcres'
vmsBuffering = u'Pufferel\xe9s'
vmsDeleting = u'T\xf6rl\xe9s'
vmsDownloading = u'Let\xf6lt\xe9s'
vmsFailed = u'Nem siker\xfclt'
vmsNotDownloaded = u'Nincs let\xf6ltve'
vmsPlayed = u'Lej\xe1tszott'
vmsPlaying = u'Lej\xe1tsz\xe1s'
vmsRecorded = u'R\xf6gz\xedtett'
vmsRecording = u'Hang\xfczenet felv\xe9tele t\xf6rt\xe9nik'
vmsUnknown = u'Ismeretlen'
vmsUnplayed = u'Nem lej\xe1tszott'
vmsUploaded = u'Felt\xf6ltve'
vmsUploading = u'Felt\xf6lt\xe9s'
vmtCustomGreeting = u'Egy\xe9ni k\xf6sz\xf6nt\xe9s'
vmtDefaultGreeting = u'Alap\xe9rtelmezett k\xf6sz\xf6nt\xe9s'
vmtIncoming = u'Hang\xfczenet \xe9rkezik'
vmtOutgoing = u'Kimeno'
vmtUnknown = u'Ismeretlen'
vssAvailable = u'El\xe9rheto'
vssNotAvailable = u'Nem el\xe9rheto'
vssPaused = u'Sz\xfcnetel'
vssRejected = u'Visszautas\xedtva'
vssRunning = u'Fut'
vssStarting = u'Ind\xedt\xe1s'
vssStopping = u'Le\xe1ll\xedt\xe1s'
vssUnknown = u'Ismeretlen'
| {
"repo_name": "pokutnik/skype4py",
"path": "Skype4Py/lang/hu.py",
"copies": "23",
"size": "7624",
"license": "bsd-3-clause",
"hash": 8056354652551004000,
"line_mean": 39.7700534759,
"line_max": 99,
"alpha_frac": 0.795383001,
"autogenerated": false,
"ratio": 2.154889768230639,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API forefindes'
apiAttachNotAvailable = u'Optaget'
apiAttachPendingAuthorization = u'Afventer godkendelse'
apiAttachRefused = u'Afvist'
apiAttachSuccess = u'Succes'
apiAttachUnknown = u'Ukendt'
budDeletedFriend = u'Slettet fra liste over kontaktpersoner'
budFriend = u'Ven'
budNeverBeenFriend = u'Aldrig v\xe6ret p\xe5 liste over kontaktpersoner'
budPendingAuthorization = u'Afventer godkendelse'
budUnknown = u'Ukendt'
cfrBlockedByRecipient = u'Opkald blokeret af modtager'
cfrMiscError = u'Anden fejl'
cfrNoCommonCodec = u'Intet f\xe6lles codec fundet'
cfrNoProxyFound = u'Ingen proxy fundet'
cfrNotAuthorizedByRecipient = u'Aktuel bruger er ikke godkendt af modtager'
cfrRecipientNotFriend = u'Modtager er ikke en ven'
cfrRemoteDeviceError = u'Problem med lydenhed hos modparten'
cfrSessionTerminated = u'Session afsluttet'
cfrSoundIOError = u'Lyd-I/O fejl'
cfrSoundRecordingError = u'Lydoptagelsesfejl'
cfrUnknown = u'Ukendt'
cfrUserDoesNotExist = u'Bruger/telefonnummer findes ikke'
cfrUserIsOffline = u'Han eller hun er offline'
chsAllCalls = u'Dialog med tidligere version'
chsDialog = u'Dialog'
chsIncomingCalls = u'Behov for \xa0accept af flere brugere'
chsLegacyDialog = u'Dialog med tidligere version'
chsMissedCalls = u'Dialog'
chsMultiNeedAccept = u'Behov for \xa0accept af flere brugere'
chsMultiSubscribed = u'Flere brugere deltager'
chsOutgoingCalls = u'Flere brugere deltager'
chsUnknown = u'Ukendt'
chsUnsubscribed = u'Afmeldt'
clsBusy = u'Optaget'
clsCancelled = u'Afbrudt'
clsEarlyMedia = u'Afspiller startmedier (Early Media)'
clsFailed = u'Opkaldet mislykkedes!'
clsFinished = u'Afsluttet'
clsInProgress = u'udf\xf8rer'
clsLocalHold = u'Opkald parkeret (lokalt)'
clsMissed = u'Mistet opkald'
clsOnHold = u'Parkeret'
clsRefused = u'Afvist'
clsRemoteHold = u'Opkald parkeret (fjernsystem)'
clsRinging = u'ringer'
clsRouting = u'Omdirigerer'
clsTransferred = u'Ukendt'
clsTransferring = u'Ukendt'
clsUnknown = u'Ukendt'
clsUnplaced = u'Aldrig foretaget'
clsVoicemailBufferingGreeting = u'Bufferlagring af besked'
clsVoicemailCancelled = u'Stemmebesked er afbrudt'
clsVoicemailFailed = u'Stemmebesked fejlet'
clsVoicemailPlayingGreeting = u'Afspiller besked'
clsVoicemailRecording = u'Optager stemmebesked'
clsVoicemailSent = u'Stemmebesked er afsendt'
clsVoicemailUploading = u'Overf\xf8rer stemmebesked'
cltIncomingP2P = u'Indg\xe5ende peer-to-peer-opkald'
cltIncomingPSTN = u'Indg\xe5ende telefonopkald'
cltOutgoingP2P = u'Udg\xe5ende peer-to-peer-opkald'
cltOutgoingPSTN = u'Udg\xe5ende telefonopkald'
cltUnknown = u'Ukendt'
cmeAddedMembers = u'Tilf\xf8jede medlemmer'
cmeCreatedChatWith = u'Oprettet chat med'
cmeEmoted = u'Ukendt'
cmeLeft = u'Forladt'
cmeSaid = u'Sagt'
cmeSawMembers = u'S\xe5 medlemmer'
cmeSetTopic = u'Angiv emne'
cmeUnknown = u'Ukendt'
cmsRead = u'L\xe6st'
cmsReceived = u'Modtaget'
cmsSending = u'Sender...'
cmsSent = u'Sendt'
cmsUnknown = u'Ukendt'
conConnecting = u'Tilslutter'
conOffline = u'Offline'
conOnline = u'Online'
conPausing = u'Midlertidigt afbrudt'
conUnknown = u'Ukendt'
cusAway = u'Ikke til stede'
cusDoNotDisturb = u'Vil ikke forstyrres'
cusInvisible = u'Usynlig'
cusLoggedOut = u'Offline'
cusNotAvailable = u'Optaget'
cusOffline = u'Offline'
cusOnline = u'Online'
cusSkypeMe = u'Ring til mig'
cusUnknown = u'Ukendt'
cvsBothEnabled = u'Video send og modtag'
cvsNone = u'Ingen video'
cvsReceiveEnabled = u'Video modtag'
cvsSendEnabled = u'Video send'
cvsUnknown = u''
grpAllFriends = u'Alle venner'
grpAllUsers = u'Alle brugere'
grpCustomGroup = u'Tilpasset'
grpOnlineFriends = u'Online-venner'
grpPendingAuthorizationFriends = u'Afventer godkendelse'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Venner kontaktet for nylig'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype-venner'
grpSkypeOutFriends = u'SkypeOut-venner'
grpUngroupedFriends = u'Ikke-grupperede venner'
grpUnknown = u'Ukendt'
grpUsersAuthorizedByMe = u'Godkendt af mig'
grpUsersBlockedByMe = u'Blokeret af mig'
grpUsersWaitingMyAuthorization = u'Afventer min godkendelse'
leaAddDeclined = u'Tilf\xf8jelse afvist'
leaAddedNotAuthorized = u'Tilf\xf8jet skal v\xe6re godkendt'
leaAdderNotFriend = u'Tilf\xf8jet skal v\xe6re ven'
leaUnknown = u'Ukendt'
leaUnsubscribe = u'Afmeldt'
leaUserIncapable = u'Bruger kan ikke forts\xe6tte'
leaUserNotFound = u'Bruger ikke fundet'
olsAway = u'Ikke til stede'
olsDoNotDisturb = u'Vil ikke forstyrres'
olsNotAvailable = u'Optaget'
olsOffline = u'Offline'
olsOnline = u'Online'
olsSkypeMe = u'Ring til mig'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Ukendt'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Kvinde'
usexMale = u'Mand'
usexUnknown = u'Ukendt'
vmrConnectError = u'Fejl ved forbindelse'
vmrFileReadError = u'Der opstod en fejl under l\xe6sning af filen'
vmrFileWriteError = u'Der opstod en fejl under lagring af filen'
vmrMiscError = u'Anden fejl'
vmrNoError = u'Ingen fejl'
vmrNoPrivilege = u'Du kan ikke l\xe6gge en stemmebesked'
vmrNoVoicemail = u'Stemmebeskeden findes ikke'
vmrPlaybackError = u'Afspilningsfejl'
vmrRecordingError = u'Indspilningsfejl'
vmrUnknown = u'Ukendt'
vmsBlank = u'Blank'
vmsBuffering = u'Bufferlagrer'
vmsDeleting = u'Sletter'
vmsDownloading = u'Henter'
vmsFailed = u'Mislykkedes'
vmsNotDownloaded = u'Ikke hentet'
vmsPlayed = u'Afspillet'
vmsPlaying = u'Afspiller'
vmsRecorded = u'Optaget'
vmsRecording = u'Optager stemmebesked'
vmsUnknown = u'Ukendt'
vmsUnplayed = u'Ikke afspillet'
vmsUploaded = u'Overf\xf8rt'
vmsUploading = u'Overf\xf8rer'
vmtCustomGreeting = u'Tilpasset besked'
vmtDefaultGreeting = u'Standardbesked'
vmtIncoming = u'indg\xe5ende voicemail'
vmtOutgoing = u'Udg\xe5ende'
vmtUnknown = u'Ukendt'
vssAvailable = u'Ledig'
vssNotAvailable = u'Optaget'
vssPaused = u'Midlertidigt afbrudt'
vssRejected = u'Afvist'
vssRunning = u'K\xf8rer'
vssStarting = u'Starter'
vssStopping = u'Stopper'
vssUnknown = u'Ukendt'
| {
"repo_name": "pokutnik/skype4py",
"path": "Skype4Py/lang/da.py",
"copies": "23",
"size": "6833",
"license": "bsd-3-clause",
"hash": 2958249102553904000,
"line_mean": 35.5401069519,
"line_max": 75,
"alpha_frac": 0.8015512952,
"autogenerated": false,
"ratio": 2.47124773960217,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 187
} |
apiAttachAvailable = u'API forefindes'
apiAttachNotAvailable = u'Optaget'
apiAttachPendingAuthorization = u'Afventer godkendelse'
apiAttachRefused = u'Afvist'
apiAttachSuccess = u'Succes'
apiAttachUnknown = u'Ukendt'
budDeletedFriend = u'Slettet fra liste over kontaktpersoner'
budFriend = u'Ven'
budNeverBeenFriend = u'Aldrig v\xe6ret p\xe5 liste over kontaktpersoner'
budPendingAuthorization = u'Afventer godkendelse'
budUnknown = u'Ukendt'
cfrBlockedByRecipient = u'Opkald blokeret af modtager'
cfrMiscError = u'Anden fejl'
cfrNoCommonCodec = u'Intet f\xe6lles codec fundet'
cfrNoProxyFound = u'Ingen proxy fundet'
cfrNotAuthorizedByRecipient = u'Aktuel bruger er ikke godkendt af modtager'
cfrRecipientNotFriend = u'Modtager er ikke en ven'
cfrRemoteDeviceError = u'Problem med lydenhed hos modparten'
cfrSessionTerminated = u'Session afsluttet'
cfrSoundIOError = u'Lyd-I/O fejl'
cfrSoundRecordingError = u'Lydoptagelsesfejl'
cfrUnknown = u'Ukendt'
cfrUserDoesNotExist = u'Bruger/telefonnummer findes ikke'
cfrUserIsOffline = u'Han eller hun er offline'
chsAllCalls = u'Dialog med tidligere version'
chsDialog = u'Dialog'
chsIncomingCalls = u'Behov for \xa0accept af flere brugere'
chsLegacyDialog = u'Dialog med tidligere version'
chsMissedCalls = u'Dialog'
chsMultiNeedAccept = u'Behov for \xa0accept af flere brugere'
chsMultiSubscribed = u'Flere brugere deltager'
chsOutgoingCalls = u'Flere brugere deltager'
chsUnknown = u'Ukendt'
chsUnsubscribed = u'Afmeldt'
clsBusy = u'Optaget'
clsCancelled = u'Afbrudt'
clsEarlyMedia = u'Afspiller startmedier (Early Media)'
clsFailed = u'Opkaldet mislykkedes!'
clsFinished = u'Afsluttet'
clsInProgress = u'udf\xf8rer'
clsLocalHold = u'Opkald parkeret (lokalt)'
clsMissed = u'Mistet opkald'
clsOnHold = u'Parkeret'
clsRefused = u'Afvist'
clsRemoteHold = u'Opkald parkeret (fjernsystem)'
clsRinging = u'ringer'
clsRouting = u'Omdirigerer'
clsTransferred = u'Ukendt'
clsTransferring = u'Ukendt'
clsUnknown = u'Ukendt'
clsUnplaced = u'Aldrig foretaget'
clsVoicemailBufferingGreeting = u'Bufferlagring af besked'
clsVoicemailCancelled = u'Stemmebesked er afbrudt'
clsVoicemailFailed = u'Stemmebesked fejlet'
clsVoicemailPlayingGreeting = u'Afspiller besked'
clsVoicemailRecording = u'Optager stemmebesked'
clsVoicemailSent = u'Stemmebesked er afsendt'
clsVoicemailUploading = u'Overf\xf8rer stemmebesked'
cltIncomingP2P = u'Indg\xe5ende peer-to-peer-opkald'
cltIncomingPSTN = u'Indg\xe5ende telefonopkald'
cltOutgoingP2P = u'Udg\xe5ende peer-to-peer-opkald'
cltOutgoingPSTN = u'Udg\xe5ende telefonopkald'
cltUnknown = u'Ukendt'
cmeAddedMembers = u'Tilf\xf8jede medlemmer'
cmeCreatedChatWith = u'Oprettet chat med'
cmeEmoted = u'Ukendt'
cmeLeft = u'Forladt'
cmeSaid = u'Sagt'
cmeSawMembers = u'S\xe5 medlemmer'
cmeSetTopic = u'Angiv emne'
cmeUnknown = u'Ukendt'
cmsRead = u'L\xe6st'
cmsReceived = u'Modtaget'
cmsSending = u'Sender...'
cmsSent = u'Sendt'
cmsUnknown = u'Ukendt'
conConnecting = u'Tilslutter'
conOffline = u'Offline'
conOnline = u'Online'
conPausing = u'Midlertidigt afbrudt'
conUnknown = u'Ukendt'
cusAway = u'Ikke til stede'
cusDoNotDisturb = u'Vil ikke forstyrres'
cusInvisible = u'Usynlig'
cusLoggedOut = u'Offline'
cusNotAvailable = u'Optaget'
cusOffline = u'Offline'
cusOnline = u'Online'
cusSkypeMe = u'Ring til mig'
cusUnknown = u'Ukendt'
cvsBothEnabled = u'Video send og modtag'
cvsNone = u'Ingen video'
cvsReceiveEnabled = u'Video modtag'
cvsSendEnabled = u'Video send'
cvsUnknown = u''
grpAllFriends = u'Alle venner'
grpAllUsers = u'Alle brugere'
grpCustomGroup = u'Tilpasset'
grpOnlineFriends = u'Online-venner'
grpPendingAuthorizationFriends = u'Afventer godkendelse'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Venner kontaktet for nylig'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype-venner'
grpSkypeOutFriends = u'SkypeOut-venner'
grpUngroupedFriends = u'Ikke-grupperede venner'
grpUnknown = u'Ukendt'
grpUsersAuthorizedByMe = u'Godkendt af mig'
grpUsersBlockedByMe = u'Blokeret af mig'
grpUsersWaitingMyAuthorization = u'Afventer min godkendelse'
leaAddDeclined = u'Tilf\xf8jelse afvist'
leaAddedNotAuthorized = u'Tilf\xf8jet skal v\xe6re godkendt'
leaAdderNotFriend = u'Tilf\xf8jet skal v\xe6re ven'
leaUnknown = u'Ukendt'
leaUnsubscribe = u'Afmeldt'
leaUserIncapable = u'Bruger kan ikke forts\xe6tte'
leaUserNotFound = u'Bruger ikke fundet'
olsAway = u'Ikke til stede'
olsDoNotDisturb = u'Vil ikke forstyrres'
olsNotAvailable = u'Optaget'
olsOffline = u'Offline'
olsOnline = u'Online'
olsSkypeMe = u'Ring til mig'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Ukendt'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Kvinde'
usexMale = u'Mand'
usexUnknown = u'Ukendt'
vmrConnectError = u'Fejl ved forbindelse'
vmrFileReadError = u'Der opstod en fejl under l\xe6sning af filen'
vmrFileWriteError = u'Der opstod en fejl under lagring af filen'
vmrMiscError = u'Anden fejl'
vmrNoError = u'Ingen fejl'
vmrNoPrivilege = u'Du kan ikke l\xe6gge en stemmebesked'
vmrNoVoicemail = u'Stemmebeskeden findes ikke'
vmrPlaybackError = u'Afspilningsfejl'
vmrRecordingError = u'Indspilningsfejl'
vmrUnknown = u'Ukendt'
vmsBlank = u'Blank'
vmsBuffering = u'Bufferlagrer'
vmsDeleting = u'Sletter'
vmsDownloading = u'Henter'
vmsFailed = u'Mislykkedes'
vmsNotDownloaded = u'Ikke hentet'
vmsPlayed = u'Afspillet'
vmsPlaying = u'Afspiller'
vmsRecorded = u'Optaget'
vmsRecording = u'Optager stemmebesked'
vmsUnknown = u'Ukendt'
vmsUnplayed = u'Ikke afspillet'
vmsUploaded = u'Overf\xf8rt'
vmsUploading = u'Overf\xf8rer'
vmtCustomGreeting = u'Tilpasset besked'
vmtDefaultGreeting = u'Standardbesked'
vmtIncoming = u'indg\xe5ende voicemail'
vmtOutgoing = u'Udg\xe5ende'
vmtUnknown = u'Ukendt'
vssAvailable = u'Ledig'
vssNotAvailable = u'Optaget'
vssPaused = u'Midlertidigt afbrudt'
vssRejected = u'Afvist'
vssRunning = u'K\xf8rer'
vssStarting = u'Starter'
vssStopping = u'Stopper'
vssUnknown = u'Ukendt'
| {
"repo_name": "bbockelm/htcondor",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/da.py",
"copies": "10",
"size": "7020",
"license": "apache-2.0",
"hash": 2381023731831515600,
"line_mean": 35.5401069519,
"line_max": 75,
"alpha_frac": 0.7801994302,
"autogenerated": false,
"ratio": 2.3788546255506606,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8159054055750661,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API je k dispozici'
apiAttachNotAvailable = u'Nedostupn\xfd'
apiAttachPendingAuthorization = u'Nevyr\xedzen\xe1 autorizace'
apiAttachRefused = u'Odm\xedtnuto'
apiAttachSuccess = u'\xdaspech'
apiAttachUnknown = u'Nezn\xe1m\xfd'
budDeletedFriend = u'Odstranen ze seznamu pr\xe1tel'
budFriend = u'Pr\xedtel'
budNeverBeenFriend = u'Nikdy nebyl v seznamu pr\xe1tel'
budPendingAuthorization = u'Nevyr\xedzen\xe1 autorizace'
budUnknown = u'Nezn\xe1m\xfd'
cfrBlockedByRecipient = u'Hovor je blokov\xe1n pr\xedjemcem.'
cfrMiscError = u'Jin\xe1 chyba'
cfrNoCommonCodec = u'Neobvykl\xfd kodek'
cfrNoProxyFound = u'Server proxy nebyl nalezen.'
cfrNotAuthorizedByRecipient = u'Aktu\xe1ln\xed u\u017eivatel nen\xed pr\xedjemcem autorizov\xe1n.'
cfrRecipientNotFriend = u'Pr\xedjemce nen\xed pr\xedtel.'
cfrRemoteDeviceError = u'Chyba zvukov\xe9ho zar\xedzen\xed volan\xe9ho'
cfrSessionTerminated = u'Hovor ukoncen'
cfrSoundIOError = u'Chyba zvukov\xe9ho V/V'
cfrSoundRecordingError = u'Chyba nahr\xe1v\xe1n\xed zvuku'
cfrUnknown = u'Nezn\xe1m\xfd'
cfrUserDoesNotExist = u'U\u017eivatel/telefonn\xed c\xedslo neexistuje.'
cfrUserIsOffline = u'On nebo Ona je Offline'
chsAllCalls = u'Dialog ve star\xe9m stylu'
chsDialog = u'Dialog'
chsIncomingCalls = u'S v\xedce \xfacastn\xedky, je treba prijet\xed'
chsLegacyDialog = u'Dialog ve star\xe9m stylu'
chsMissedCalls = u'Dialog'
chsMultiNeedAccept = u'S v\xedce \xfacastn\xedky, je treba prijet\xed'
chsMultiSubscribed = u'S v\xedce \xfacastn\xedky'
chsOutgoingCalls = u'S v\xedce \xfacastn\xedky'
chsUnknown = u'Nezn\xe1m\xfd'
chsUnsubscribed = u'Odebran\xfd ze seznamu'
clsBusy = u'Obsazeno'
clsCancelled = u'Zru\u0161eno'
clsEarlyMedia = u'Prehr\xe1v\xe1n\xed m\xe9di\xed pred prijet\xedm hovoru'
clsFailed = u'Bohu\u017eel, ne\xfaspe\u0161n\xe9 vol\xe1n\xed!'
clsFinished = u'Ukonceno'
clsInProgress = u'Prob\xedh\xe1 hovor'
clsLocalHold = u'Pridr\u017eeno m\xedstne'
clsMissed = u'Zme\u0161kan\xfd hovor'
clsOnHold = u'Pridr\u017een'
clsRefused = u'Odm\xedtnuto'
clsRemoteHold = u'Pridr\u017eeno vzd\xe1len\xfdm u\u017eivatelem'
clsRinging = u'vol\xe1te'
clsRouting = u'Smerov\xe1n\xed'
clsTransferred = u'Nezn\xe1m\xfd'
clsTransferring = u'Nezn\xe1m\xfd'
clsUnknown = u'Nezn\xe1m\xfd'
clsUnplaced = u'Nekonal se'
clsVoicemailBufferingGreeting = u'Ukl\xe1d\xe1n\xed pozdravu do vyrovn\xe1vac\xed pameti'
clsVoicemailCancelled = u'Hlasov\xe1 zpr\xe1va byla zru\u0161ena'
clsVoicemailFailed = u'Hlasov\xe1 zpr\xe1va ne\xfaspe\u0161n\xe1'
clsVoicemailPlayingGreeting = u'Prehr\xe1v\xe1n\xed pozdravu'
clsVoicemailRecording = u'Nahr\xe1v\xe1n\xed hlasov\xe9 zpr\xe1vy'
clsVoicemailSent = u'Hlasov\xe1 zpr\xe1va byla odesl\xe1na'
clsVoicemailUploading = u'Odes\xedl\xe1n\xed hlasov\xe9 zpr\xe1vy'
cltIncomingP2P = u'Pr\xedchoz\xed hovor v s\xedti P2P'
cltIncomingPSTN = u'Pr\xedchoz\xed telefonn\xed hovor'
cltOutgoingP2P = u'Odchoz\xed hovor v s\xedti P2P'
cltOutgoingPSTN = u'Odchoz\xed telefonn\xed hovor'
cltUnknown = u'Nezn\xe1m\xfd'
cmeAddedMembers = u'Byli prizv\xe1ni clenov\xe9.'
cmeCreatedChatWith = u'Byl vytvoren chat s v\xedce \xfacastn\xedky.'
cmeEmoted = u'Nezn\xe1m\xfd'
cmeLeft = u'Nekdo opustil chat nebo nebyl pribr\xe1n.'
cmeSaid = u'Rekl(a)'
cmeSawMembers = u'\xdacastn\xedk chatu videl ostatn\xed.'
cmeSetTopic = u'Zmena t\xe9matu'
cmeUnknown = u'Nezn\xe1m\xfd'
cmsRead = u'Precteno'
cmsReceived = u'Prijato'
cmsSending = u'Odes\xedl\xe1m...'
cmsSent = u'Odesl\xe1no'
cmsUnknown = u'Nezn\xe1m\xfd'
conConnecting = u'Spojuji'
conOffline = u'Offline'
conOnline = u'Online'
conPausing = u'Pozastavov\xe1n\xed'
conUnknown = u'Nezn\xe1m\xfd'
cusAway = u'Nepr\xedtomn\xfd'
cusDoNotDisturb = u'Neru\u0161it'
cusInvisible = u'Neviditeln\xfd'
cusLoggedOut = u'Offline'
cusNotAvailable = u'Nedostupn\xfd'
cusOffline = u'Offline'
cusOnline = u'Online'
cusSkypeMe = u'Skype Me'
cusUnknown = u'Nezn\xe1m\xfd'
cvsBothEnabled = u'Odes\xedl\xe1n\xed a pr\xedjem videa'
cvsNone = u'Bez videa'
cvsReceiveEnabled = u'Pr\xedjem videa'
cvsSendEnabled = u'Odes\xedl\xe1n\xed videa'
cvsUnknown = u''
grpAllFriends = u'V\u0161ichni pr\xe1tel\xe9'
grpAllUsers = u'V\u0161ichni u\u017eivatel\xe9'
grpCustomGroup = u'Vlastn\xed'
grpOnlineFriends = u'Pr\xe1tel\xe9 online'
grpPendingAuthorizationFriends = u'Nevyr\xedzen\xe1 autorizace'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Ned\xe1vno kontaktovan\xed u\u017eivatel\xe9'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Pr\xe1tel\xe9 pou\u017e\xedvaj\xedc\xed Skype'
grpSkypeOutFriends = u'Pr\xe1tel\xe9 pou\u017e\xedvaj\xedc\xed SkypeOut'
grpUngroupedFriends = u'Nezarazen\xed pr\xe1tel\xe9'
grpUnknown = u'Nezn\xe1m\xfd'
grpUsersAuthorizedByMe = u'Autorizovan\xed'
grpUsersBlockedByMe = u'Blokovan\xed'
grpUsersWaitingMyAuthorization = u'Cekaj\xedc\xed na autorizaci'
leaAddDeclined = u'Prid\xe1n\xed bylo odm\xedtnuto.'
leaAddedNotAuthorized = u'Prid\xe1van\xfd mus\xed b\xfdt autorizov\xe1n.'
leaAdderNotFriend = u'Prid\xe1vaj\xedc\xed mus\xed b\xfdt pr\xedtel.'
leaUnknown = u'Nezn\xe1m\xfd'
leaUnsubscribe = u'Odebran\xfd ze seznamu'
leaUserIncapable = u'U\u017eivatel je nezpusobil\xfd.'
leaUserNotFound = u'U\u017eivatel nebyl nalezen.'
olsAway = u'Nepr\xedtomn\xfd'
olsDoNotDisturb = u'Neru\u0161it'
olsNotAvailable = u'Nedostupn\xfd'
olsOffline = u'Offline'
olsOnline = u'Online'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'????????? ?? SkypeOut'
olsUnknown = u'Nezn\xe1m\xfd'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\u017dena'
usexMale = u'Mu\u017e'
usexUnknown = u'Nezn\xe1m\xfd'
vmrConnectError = u'Chyba pripojen\xed'
vmrFileReadError = u'Chyba cten\xed souboru'
vmrFileWriteError = u'Chyba z\xe1pisu souboru'
vmrMiscError = u'Jin\xe1 chyba'
vmrNoError = u'Bez chyby'
vmrNoPrivilege = u'Nem\xe1te opr\xe1vnen\xed k hlasov\xe9 schr\xe1nce.'
vmrNoVoicemail = u'Takov\xe1 hlasov\xe1 schr\xe1nka neexistuje.'
vmrPlaybackError = u'Chyba prehr\xe1v\xe1n\xed'
vmrRecordingError = u'Chyba nahr\xe1v\xe1n\xed'
vmrUnknown = u'Nezn\xe1m\xfd'
vmsBlank = u'Pr\xe1zdn\xe9'
vmsBuffering = u'Nac\xedt\xe1n\xed'
vmsDeleting = u'Odstranov\xe1n\xed'
vmsDownloading = u'Stahov\xe1n\xed'
vmsFailed = u'Ne\xfaspe\u0161n\xe9'
vmsNotDownloaded = u'Nesta\u017eeno.'
vmsPlayed = u'Prehr\xe1no'
vmsPlaying = u'Prehr\xe1v\xe1n\xed'
vmsRecorded = u'Nahr\xe1no'
vmsRecording = u'Nahr\xe1v\xe1n\xed hlasov\xe9 zpr\xe1vy'
vmsUnknown = u'Nezn\xe1m\xfd'
vmsUnplayed = u'Neprehr\xe1no'
vmsUploaded = u'Odesl\xe1no'
vmsUploading = u'Odes\xedl\xe1n\xed'
vmtCustomGreeting = u'Vlastn\xed pozdrav'
vmtDefaultGreeting = u'V\xfdchoz\xed pozdrav'
vmtIncoming = u'pr\xedchoz\xed hlasov\xe1 zpr\xe1va'
vmtOutgoing = u'Odchoz\xed'
vmtUnknown = u'Nezn\xe1m\xfd'
vssAvailable = u'Dostupn\xfd'
vssNotAvailable = u'Nedostupn\xfd'
vssPaused = u'Pozastaveno'
vssRejected = u'Odm\xedtnuto'
vssRunning = u'Prob\xedh\xe1'
vssStarting = u'Start'
vssStopping = u'Ukoncov\xe1n\xed'
vssUnknown = u'Nezn\xe1m\xfd'
| {
"repo_name": "james-huang/sk_skype_bot",
"path": "Skype4Py/lang/cs.py",
"copies": "23",
"size": "7855",
"license": "mit",
"hash": -634809563427037800,
"line_mean": 41.0053475936,
"line_max": 98,
"alpha_frac": 0.7882877148,
"autogenerated": false,
"ratio": 2.2208085948543963,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00011343380327337548,
"num_lines": 187
} |
apiAttachAvailable = u'API Kullanilabilir'
apiAttachNotAvailable = u'Kullanilamiyor'
apiAttachPendingAuthorization = u'Yetkilendirme Bekliyor'
apiAttachRefused = u'Reddedildi'
apiAttachSuccess = u'Basarili oldu'
apiAttachUnknown = u'Bilinmiyor'
budDeletedFriend = u'Arkadas Listesinden Silindi'
budFriend = u'Arkadas'
budNeverBeenFriend = u'Arkadas Listesinde Hi\xe7 Olmadi'
budPendingAuthorization = u'Yetkilendirme Bekliyor'
budUnknown = u'Bilinmiyor'
cfrBlockedByRecipient = u'\xc7agri alici tarafindan engellendi'
cfrMiscError = u'Diger Hata'
cfrNoCommonCodec = u'Genel codec yok'
cfrNoProxyFound = u'Proxy bulunamadi'
cfrNotAuthorizedByRecipient = u'Ge\xe7erli kullanici alici tarafindan yetkilendirilmemis'
cfrRecipientNotFriend = u'Alici bir arkadas degil'
cfrRemoteDeviceError = u'Uzak ses aygitinda problem var'
cfrSessionTerminated = u'Oturum sonlandirildi'
cfrSoundIOError = u'Ses G/\xc7 hatasi'
cfrSoundRecordingError = u'Ses kayit hatasi'
cfrUnknown = u'Bilinmiyor'
cfrUserDoesNotExist = u'Kullanici/telefon numarasi mevcut degil'
cfrUserIsOffline = u'\xc7evrim Disi'
chsAllCalls = u'Eski Diyalog'
chsDialog = u'Diyalog'
chsIncomingCalls = u'\xc7oklu Sohbet Kabul\xfc Gerekli'
chsLegacyDialog = u'Eski Diyalog'
chsMissedCalls = u'Diyalog'
chsMultiNeedAccept = u'\xc7oklu Sohbet Kabul\xfc Gerekli'
chsMultiSubscribed = u'\xc7oklu Abonelik'
chsOutgoingCalls = u'\xc7oklu Abonelik'
chsUnknown = u'Bilinmiyor'
chsUnsubscribed = u'Aboneligi Silindi'
clsBusy = u'Mesgul'
clsCancelled = u'Iptal Edildi'
clsEarlyMedia = u'Early Media y\xfcr\xfct\xfcl\xfcyor'
clsFailed = u'\xdczg\xfcn\xfcz, arama basarisiz!'
clsFinished = u'Bitirildi'
clsInProgress = u'Arama Yapiliyor'
clsLocalHold = u'Yerel Beklemede'
clsMissed = u'Cevapsiz Arama'
clsOnHold = u'Beklemede'
clsRefused = u'Reddedildi'
clsRemoteHold = u'Uzak Beklemede'
clsRinging = u'ariyor'
clsRouting = u'Y\xf6nlendirme'
clsTransferred = u'Bilinmiyor'
clsTransferring = u'Bilinmiyor'
clsUnknown = u'Bilinmiyor'
clsUnplaced = u'Asla baglanmadi'
clsVoicemailBufferingGreeting = u'Selamlama Ara Bellege Aliniyor'
clsVoicemailCancelled = u'Sesli Posta Iptal Edildi'
clsVoicemailFailed = u'Sesli Mesaj Basarisiz'
clsVoicemailPlayingGreeting = u'Selamlama Y\xfcr\xfct\xfcl\xfcyor'
clsVoicemailRecording = u'Sesli Mesaj Kaydediliyor'
clsVoicemailSent = u'Sesli Posta G\xf6nderildi'
clsVoicemailUploading = u'Sesli Posta Karsiya Y\xfckleniyor'
cltIncomingP2P = u'Gelen Esler Arasi Telefon \xc7agrisi'
cltIncomingPSTN = u'Gelen Telefon \xc7agrisi'
cltOutgoingP2P = u'Giden Esler Arasi Telefon \xc7agrisi'
cltOutgoingPSTN = u'Giden Telefon \xc7agrisi'
cltUnknown = u'Bilinmiyor'
cmeAddedMembers = u'Eklenen \xdcyeler'
cmeCreatedChatWith = u'Sohbet Olusturuldu:'
cmeEmoted = u'Bilinmiyor'
cmeLeft = u'Birakilan'
cmeSaid = u'Ifade'
cmeSawMembers = u'G\xf6r\xfclen \xdcyeler'
cmeSetTopic = u'Konu Belirleme'
cmeUnknown = u'Bilinmiyor'
cmsRead = u'Okundu'
cmsReceived = u'Alindi'
cmsSending = u'G\xf6nderiliyor...'
cmsSent = u'G\xf6nderildi'
cmsUnknown = u'Bilinmiyor'
conConnecting = u'Baglaniyor'
conOffline = u'\xc7evrim Disi'
conOnline = u'\xc7evrim I\xe7i'
conPausing = u'Duraklatiliyor'
conUnknown = u'Bilinmiyor'
cusAway = u'Uzakta'
cusDoNotDisturb = u'Rahatsiz Etmeyin'
cusInvisible = u'G\xf6r\xfcnmez'
cusLoggedOut = u'\xc7evrim Disi'
cusNotAvailable = u'Kullanilamiyor'
cusOffline = u'\xc7evrim Disi'
cusOnline = u'\xc7evrim I\xe7i'
cusSkypeMe = u'Skype Me'
cusUnknown = u'Bilinmiyor'
cvsBothEnabled = u'Video G\xf6nderme ve Alma'
cvsNone = u'Video Yok'
cvsReceiveEnabled = u'Video Alma'
cvsSendEnabled = u'Video G\xf6nderme'
cvsUnknown = u''
grpAllFriends = u'T\xfcm Arkadaslar'
grpAllUsers = u'T\xfcm Kullanicilar'
grpCustomGroup = u'\xd6zel'
grpOnlineFriends = u'\xc7evrimi\xe7i Arkadaslar'
grpPendingAuthorizationFriends = u'Yetkilendirme Bekliyor'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Son Zamanlarda Iletisim Kurulmus Kullanicilar'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype Arkadaslari'
grpSkypeOutFriends = u'SkypeOut Arkadaslari'
grpUngroupedFriends = u'Gruplanmamis Arkadaslar'
grpUnknown = u'Bilinmiyor'
grpUsersAuthorizedByMe = u'Tarafimdan Yetkilendirilenler'
grpUsersBlockedByMe = u'Engellediklerim'
grpUsersWaitingMyAuthorization = u'Yetkilendirmemi Bekleyenler'
leaAddDeclined = u'Ekleme Reddedildi'
leaAddedNotAuthorized = u'Ekleyen Kisinin Yetkisi Olmali'
leaAdderNotFriend = u'Ekleyen Bir Arkadas Olmali'
leaUnknown = u'Bilinmiyor'
leaUnsubscribe = u'Aboneligi Silindi'
leaUserIncapable = u'Kullanicidan Kaynaklanan Yetersizlik'
leaUserNotFound = u'Kullanici Bulunamadi'
olsAway = u'Uzakta'
olsDoNotDisturb = u'Rahatsiz Etmeyin'
olsNotAvailable = u'Kullanilamiyor'
olsOffline = u'\xc7evrim Disi'
olsOnline = u'\xc7evrim I\xe7i'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Bilinmiyor'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Kadin'
usexMale = u'Erkek'
usexUnknown = u'Bilinmiyor'
vmrConnectError = u'Baglanti Hatasi'
vmrFileReadError = u'Dosya Okuma Hatasi'
vmrFileWriteError = u'Dosya Yazma Hatasi'
vmrMiscError = u'Diger Hata'
vmrNoError = u'Hata Yok'
vmrNoPrivilege = u'Sesli Posta \xd6nceligi Yok'
vmrNoVoicemail = u'B\xf6yle Bir Sesli Posta Yok'
vmrPlaybackError = u'Y\xfcr\xfctme Hatasi'
vmrRecordingError = u'Kayit Hatasi'
vmrUnknown = u'Bilinmiyor'
vmsBlank = u'Bos'
vmsBuffering = u'Ara bellege aliniyor'
vmsDeleting = u'Siliniyor'
vmsDownloading = u'Karsidan Y\xfckleniyor'
vmsFailed = u'Basarisiz Oldu'
vmsNotDownloaded = u'Karsidan Y\xfcklenmedi'
vmsPlayed = u'Y\xfcr\xfct\xfcld\xfc'
vmsPlaying = u'Y\xfcr\xfct\xfcl\xfcyor'
vmsRecorded = u'Kaydedildi'
vmsRecording = u'Sesli Mesaj Kaydediliyor'
vmsUnknown = u'Bilinmiyor'
vmsUnplayed = u'Y\xfcr\xfct\xfclmemis'
vmsUploaded = u'Karsiya Y\xfcklendi'
vmsUploading = u'Karsiya Y\xfckleniyor'
vmtCustomGreeting = u'\xd6zel Selamlama'
vmtDefaultGreeting = u'Varsayilan Selamlama'
vmtIncoming = u'gelen sesli mesaj'
vmtOutgoing = u'Giden'
vmtUnknown = u'Bilinmiyor'
vssAvailable = u'Kullanilabilir'
vssNotAvailable = u'Kullanilamiyor'
vssPaused = u'Duraklatildi'
vssRejected = u'Reddedildi'
vssRunning = u'\xc7alisiyor'
vssStarting = u'Basliyor'
vssStopping = u'Durduruluyor'
vssUnknown = u'Bilinmiyor'
| {
"repo_name": "djw8605/htcondor",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/tr.py",
"copies": "10",
"size": "7343",
"license": "apache-2.0",
"hash": 6630143884859975000,
"line_mean": 37.2673796791,
"line_max": 89,
"alpha_frac": 0.7864632984,
"autogenerated": false,
"ratio": 2.273374613003096,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.8059837911403096,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API saatavilla'
apiAttachNotAvailable = u'Ei saatavilla'
apiAttachPendingAuthorization = u'Odottaa valtuutusta'
apiAttachRefused = u'Ev\xe4tty'
apiAttachSuccess = u'Onnistui'
apiAttachUnknown = u'Tuntematon'
budDeletedFriend = u'Poistettu yst\xe4v\xe4listasta'
budFriend = u'Yst\xe4v\xe4'
budNeverBeenFriend = u'Ei aiempia yst\xe4v\xe4listauksia'
budPendingAuthorization = u'Odottaa valtuutusta'
budUnknown = u'Tuntematon'
cfrBlockedByRecipient = u'Vastaanottaja esti soiton'
cfrMiscError = u'Sekal virhe'
cfrNoCommonCodec = u'Ei yleinen koodekki'
cfrNoProxyFound = u'Proxy ei l\xf6ytynyt'
cfrNotAuthorizedByRecipient = u'K\xe4ytt\xe4j\xe4ll\xe4 ei ole vastaanottajan hyv\xe4ksynt\xe4\xe4'
cfrRecipientNotFriend = u'Vastaanottaja ei ole yst\xe4v\xe4'
cfrRemoteDeviceError = u'Ongelma et\xe4-\xe4\xe4nilaitteessa'
cfrSessionTerminated = u'Istunto p\xe4\xe4ttyi'
cfrSoundIOError = u'\xc4\xe4nen I/O-virhe'
cfrSoundRecordingError = u'\xc4\xe4nentallennusvirhe'
cfrUnknown = u'Tuntematon'
cfrUserDoesNotExist = u'Tuntematon k\xe4ytt\xe4j\xe4/puhelinnumero'
cfrUserIsOffline = u'H\xe4n on Offline-tilassa'
chsAllCalls = u'Vanha dialogi'
chsDialog = u'Dialogi'
chsIncomingCalls = u'Multi-chat odottaa hyv\xe4ksynt\xf6j\xe4'
chsLegacyDialog = u'Vanha dialogi'
chsMissedCalls = u'Dialogi'
chsMultiNeedAccept = u'Multi-chat odottaa hyv\xe4ksynt\xf6j\xe4'
chsMultiSubscribed = u'Multi tilattu'
chsOutgoingCalls = u'Multi tilattu'
chsUnknown = u'Tuntematon'
chsUnsubscribed = u'Ei tilaaja'
clsBusy = u'Varattu'
clsCancelled = u'Peruutettu'
clsEarlyMedia = u'K\xe4sittelee ennakkomediaa (Early Media)'
clsFailed = u'Ik\xe4v\xe4 kyll\xe4, puhelu ep\xe4onnistui!'
clsFinished = u'Valmis'
clsInProgress = u'Puhelu k\xe4ynniss\xe4'
clsLocalHold = u'Paikalliseti pidossa'
clsMissed = u'vastaamaton puhelu'
clsOnHold = u'Pidossa'
clsRefused = u'Ev\xe4tty'
clsRemoteHold = u'Et\xe4pidossa'
clsRinging = u'soittamassa'
clsRouting = u'Reitittt\xe4\xe4'
clsTransferred = u'Tuntematon'
clsTransferring = u'Tuntematon'
clsUnknown = u'Tuntematon'
clsUnplaced = u'Ei koskaan valittu'
clsVoicemailBufferingGreeting = u'Puskuroi tervehdyst\xe4'
clsVoicemailCancelled = u'Puheposti on peruutettu'
clsVoicemailFailed = u'Puheposti ep\xe4onnistui'
clsVoicemailPlayingGreeting = u'Toistaa tervehdyst\xe4'
clsVoicemailRecording = u'Puhepostin \xe4\xe4nitys'
clsVoicemailSent = u'Puheposti on l\xe4hetetty'
clsVoicemailUploading = u'Lataa puhepostia'
cltIncomingP2P = u'Saapuva vertaissoitto'
cltIncomingPSTN = u'Saapuva puhelinsoitto'
cltOutgoingP2P = u'L\xe4htev\xe4 vertaissoitto'
cltOutgoingPSTN = u'L\xe4htev\xe4 puhelinsoitto'
cltUnknown = u'Tuntematon'
cmeAddedMembers = u'Lis\xe4tty j\xe4senet'
cmeCreatedChatWith = u'Luotu chat-yhteys'
cmeEmoted = u'Tuntematon'
cmeLeft = u'Poistunut'
cmeSaid = u'Sanottu'
cmeSawMembers = u'N\xe4hty j\xe4senet'
cmeSetTopic = u'Aseta aihe'
cmeUnknown = u'Tuntematon'
cmsRead = u'Lue'
cmsReceived = u'Vastaanotettu'
cmsSending = u'L\xe4hetet\xe4\xe4n...'
cmsSent = u'L\xe4hetetty'
cmsUnknown = u'Tuntematon'
conConnecting = u'Yhdistet\xe4\xe4n'
conOffline = u'Offline-tila'
conOnline = u'Online-tila'
conPausing = u'Tauko'
conUnknown = u'Tuntematon'
cusAway = u'Poistunut'
cusDoNotDisturb = u'\xc4l\xe4 h\xe4iritse'
cusInvisible = u'Huomaamaton'
cusLoggedOut = u'Offline-tila'
cusNotAvailable = u'Ei saatavilla'
cusOffline = u'Offline-tila'
cusOnline = u'Online-tila'
cusSkypeMe = u'Soita minulle'
cusUnknown = u'Tuntematon'
cvsBothEnabled = u'Videon l\xe4hetys ja vastaanotto'
cvsNone = u'Ei videota'
cvsReceiveEnabled = u'Videon vastaanotto'
cvsSendEnabled = u'Videon l\xe4hetys'
cvsUnknown = u''
grpAllFriends = u'Kaikki yst\xe4v\xe4t'
grpAllUsers = u'Kaikki k\xe4ytt\xe4j\xe4t'
grpCustomGroup = u'R\xe4\xe4t\xe4l\xf6ity'
grpOnlineFriends = u'Netiss\xe4 olevat yst\xe4v\xe4t'
grpPendingAuthorizationFriends = u'Odottaa valtuutusta'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\xc4skett\xe4iset yhteydet'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype-yst\xe4v\xe4t'
grpSkypeOutFriends = u'SkypeOut-yst\xe4v\xe4t'
grpUngroupedFriends = u'Ryhmitt\xe4m\xe4tt\xf6m\xe4t yst\xe4v\xe4ni'
grpUnknown = u'Tuntematon'
grpUsersAuthorizedByMe = u'Valtuutin'
grpUsersBlockedByMe = u'Estin'
grpUsersWaitingMyAuthorization = u'Odottaa valtuutustani'
leaAddDeclined = u'Lis\xe4ys torjuttu'
leaAddedNotAuthorized = u'Lis\xe4tyn t\xe4ytyy olla valtuutettu'
leaAdderNotFriend = u'Lis\xe4\xe4j\xe4n t\xe4ytyy olla yst\xe4v\xe4'
leaUnknown = u'Tuntematon'
leaUnsubscribe = u'Ei tilaaja'
leaUserIncapable = u'K\xe4ytt\xe4j\xe4 esteellinen'
leaUserNotFound = u'K\xe4ytt\xe4j\xe4\xe4 ei l\xf6ytynyt'
olsAway = u'Poistunut'
olsDoNotDisturb = u'\xc4l\xe4 h\xe4iritse'
olsNotAvailable = u'Ei saatavilla'
olsOffline = u'Offline-tila'
olsOnline = u'Online-tila'
olsSkypeMe = u'Soita minulle'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Tuntematon'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Nainen'
usexMale = u'Mies'
usexUnknown = u'Tuntematon'
vmrConnectError = u'Yhdist\xe4misvirhe'
vmrFileReadError = u'Tiedostonlukuvirhe'
vmrFileWriteError = u'Tiedostonkirjoitusvirhe'
vmrMiscError = u'Sekal virhe'
vmrNoError = u'Ei virhett\xe4'
vmrNoPrivilege = u'Ei puhepostioikeutta'
vmrNoVoicemail = u'Tuntematon puheposti'
vmrPlaybackError = u'Toistovirhe'
vmrRecordingError = u'Tallennusvirhe'
vmrUnknown = u'Tuntematon'
vmsBlank = u'Tyhj\xe4'
vmsBuffering = u'Puskuroidaan'
vmsDeleting = u'Poistetaan'
vmsDownloading = u'Imuroidaan'
vmsFailed = u'Ep\xe4onnistui'
vmsNotDownloaded = u'Ei imuroitu'
vmsPlayed = u'Toistettu'
vmsPlaying = u'Toistetaan'
vmsRecorded = u'Tallennettu'
vmsRecording = u'Puhepostin \xe4\xe4nitys'
vmsUnknown = u'Tuntematon'
vmsUnplayed = u'Ei toistettu'
vmsUploaded = u'Ladattu'
vmsUploading = u'Ladataan'
vmtCustomGreeting = u'R\xe4\xe4t\xe4l\xf6ity tervehdys'
vmtDefaultGreeting = u'Oletustervehdys'
vmtIncoming = u'saapuva puheposti'
vmtOutgoing = u'L\xe4htev\xe4'
vmtUnknown = u'Tuntematon'
vssAvailable = u'Saatavilla'
vssNotAvailable = u'Ei saatavilla'
vssPaused = u'Tauko'
vssRejected = u'Torjuttu'
vssRunning = u'Meneill\xe4\xe4n'
vssStarting = u'Aloittaa'
vssStopping = u'Lopetetaan'
vssUnknown = u'Tuntematon'
| {
"repo_name": "mambelli/osg-bosco-marco",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/fi.py",
"copies": "10",
"size": "7319",
"license": "apache-2.0",
"hash": -6067636774727020000,
"line_mean": 37.1390374332,
"line_max": 99,
"alpha_frac": 0.7834403607,
"autogenerated": false,
"ratio": 2.2232685297691375,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000052946471117700005,
"num_lines": 187
} |
apiAttachAvailable = u'API tilgjengelig'
apiAttachNotAvailable = u'Ikke tilgjengelig'
apiAttachPendingAuthorization = u'Venter p\xe5 \xe5 bli godkjent'
apiAttachRefused = u'Avsl\xe5tt'
apiAttachSuccess = u'Vellykket'
apiAttachUnknown = u'Ukjent'
budDeletedFriend = u'Slettet fra kontaktlisten'
budFriend = u'Venn'
budNeverBeenFriend = u'Aldri v\xe6rt i kontaktlisten'
budPendingAuthorization = u'Venter p\xe5 \xe5 bli godkjent'
budUnknown = u'Ukjent'
cfrBlockedByRecipient = u'Anrop blokkert av mottaker'
cfrMiscError = u'Diverse feil'
cfrNoCommonCodec = u'Ingen felles kodek'
cfrNoProxyFound = u'Finner ingen proxy'
cfrNotAuthorizedByRecipient = u'Gjeldende bruker er ikke godkjent av mottakeren.'
cfrRecipientNotFriend = u'Mottakeren er ikke en venn'
cfrRemoteDeviceError = u'Problem med ekstern lydenhet'
cfrSessionTerminated = u'\xd8kt avsluttet'
cfrSoundIOError = u'I/U-feil for lyd'
cfrSoundRecordingError = u'Lydinnspillingsfeil'
cfrUnknown = u'Ukjent'
cfrUserDoesNotExist = u'Bruker/telefonnummer finnes ikke'
cfrUserIsOffline = u'Hun eller han er frakoblet'
chsAllCalls = u'Foreldet dialogboks'
chsDialog = u'Dialogboks'
chsIncomingCalls = u'Flere m\xe5 godkjenne'
chsLegacyDialog = u'Foreldet dialogboks'
chsMissedCalls = u'Dialogboks'
chsMultiNeedAccept = u'Flere m\xe5 godkjenne'
chsMultiSubscribed = u'Flere abonnert'
chsOutgoingCalls = u'Flere abonnert'
chsUnknown = u'Ukjent'
chsUnsubscribed = u'Ikke abonnert'
clsBusy = u'Opptatt'
clsCancelled = u'Avbryt'
clsEarlyMedia = u'Spiller tidlige media (Early Media)'
clsFailed = u'beklager, anropet feilet!'
clsFinished = u'Avsluttet'
clsInProgress = u'Anrop p\xe5g\xe5r'
clsLocalHold = u'Lokalt parkert samtale'
clsMissed = u'Tapt anrop'
clsOnHold = u'Parkert'
clsRefused = u'Avsl\xe5tt'
clsRemoteHold = u'Eksternt parkert samtale'
clsRinging = u'Anrop'
clsRouting = u'Ruting'
clsTransferred = u'Ukjent'
clsTransferring = u'Ukjent'
clsUnknown = u'Ukjent'
clsUnplaced = u'Aldri plassert'
clsVoicemailBufferingGreeting = u'Bufrer talepostintro'
clsVoicemailCancelled = u'Talepostmelding er annullert'
clsVoicemailFailed = u'Talepost feilet'
clsVoicemailPlayingGreeting = u'Spiller av hilsen'
clsVoicemailRecording = u'Tar opp talepost'
clsVoicemailSent = u'Talepostmelding er sendt'
clsVoicemailUploading = u'Laster opp talepost'
cltIncomingP2P = u'Innkommende P2P-anrop'
cltIncomingPSTN = u'Innkommende telefonanrop'
cltOutgoingP2P = u'Utg\xe5ende P2P-anrop'
cltOutgoingPSTN = u'Utg\xe5ende telefonanrop'
cltUnknown = u'Ukjent'
cmeAddedMembers = u'Medlemmer som er lagt til'
cmeCreatedChatWith = u'Opprettet tekstsamtale med'
cmeEmoted = u'Ukjent'
cmeLeft = u'Forlatt'
cmeSaid = u'Sa'
cmeSawMembers = u'Medlemmer som ble sett'
cmeSetTopic = u'Angitt emne'
cmeUnknown = u'Ukjent'
cmsRead = u'Lest'
cmsReceived = u'Mottatt'
cmsSending = u'Sender...'
cmsSent = u'Sendt'
cmsUnknown = u'Ukjent'
conConnecting = u'Kobler til'
conOffline = u'Frakoblet'
conOnline = u'P\xe5logget'
conPausing = u'Settes i pause'
conUnknown = u'Ukjent'
cusAway = u'Borte'
cusDoNotDisturb = u'Opptatt'
cusInvisible = u'Vis som Usynlig'
cusLoggedOut = u'Frakoblet'
cusNotAvailable = u'Ikke tilgjengelig'
cusOffline = u'Frakoblet'
cusOnline = u'P\xe5logget'
cusSkypeMe = u'Skype Meg'
cusUnknown = u'Ukjent'
cvsBothEnabled = u'Videosending og -mottak'
cvsNone = u'Ingen video'
cvsReceiveEnabled = u'Videomottak'
cvsSendEnabled = u'Videosending'
cvsUnknown = u''
grpAllFriends = u'Alle venner'
grpAllUsers = u'Alle brukere'
grpCustomGroup = u'Tilpasset'
grpOnlineFriends = u'Elektroniske venner'
grpPendingAuthorizationFriends = u'Venter p\xe5 \xe5 bli godkjent'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Nylig kontaktede brukere'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype-venner'
grpSkypeOutFriends = u'SkypeOut-venner'
grpUngroupedFriends = u'Usorterte venner'
grpUnknown = u'Ukjent'
grpUsersAuthorizedByMe = u'Godkjent av meg'
grpUsersBlockedByMe = u'Blokkert av meg'
grpUsersWaitingMyAuthorization = u'Venter p\xe5 min godkjenning'
leaAddDeclined = u'Tillegging avvist'
leaAddedNotAuthorized = u'Den som legger til, m\xe5 v\xe6re autorisert'
leaAdderNotFriend = u'Den som legger til, m\xe5 v\xe6re en venn'
leaUnknown = u'Ukjent'
leaUnsubscribe = u'Ikke abonnert'
leaUserIncapable = u'Bruker forhindret'
leaUserNotFound = u'Finner ikke bruker'
olsAway = u'Borte'
olsDoNotDisturb = u'Opptatt'
olsNotAvailable = u'Ikke tilgjengelig'
olsOffline = u'Frakoblet'
olsOnline = u'P\xe5logget'
olsSkypeMe = u'Skype Meg'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Ukjent'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Kvinne'
usexMale = u'Mann'
usexUnknown = u'Ukjent'
vmrConnectError = u'Koblingsfeil'
vmrFileReadError = u'Fillesingsfeil'
vmrFileWriteError = u'Filskrivingsfeil'
vmrMiscError = u'Diverse feil'
vmrNoError = u'Ingen feil'
vmrNoPrivilege = u'Intet talepostprivilegium'
vmrNoVoicemail = u'Ingen slik talepost'
vmrPlaybackError = u'Avspillingsfeil'
vmrRecordingError = u'Innspillingsfeil'
vmrUnknown = u'Ukjent'
vmsBlank = u'Tom'
vmsBuffering = u'Bufring'
vmsDeleting = u'Sletter'
vmsDownloading = u'Laster ned'
vmsFailed = u'Mislyktes'
vmsNotDownloaded = u'Ikke nedlastet'
vmsPlayed = u'Spilt av'
vmsPlaying = u'Spiller av'
vmsRecorded = u'Innspilt'
vmsRecording = u'Tar opp talepost'
vmsUnknown = u'Ukjent'
vmsUnplayed = u'Ikke avspilt'
vmsUploaded = u'Lastet opp'
vmsUploading = u'Laster opp'
vmtCustomGreeting = u'Tilpasset hilsen'
vmtDefaultGreeting = u'Standardhilsen'
vmtIncoming = u'Innkommende talepost'
vmtOutgoing = u'Utg\xe5ende'
vmtUnknown = u'Ukjent'
vssAvailable = u'Tilgjengelig'
vssNotAvailable = u'Ikke tilgjengelig'
vssPaused = u'Satt i pause'
vssRejected = u'Avvist'
vssRunning = u'Kj\xf8rer'
vssStarting = u'Starter'
vssStopping = u'Stanser'
vssUnknown = u'Ukjent'
| {
"repo_name": "donjordano/skype4py",
"path": "Skype4Py/lang/no.py",
"copies": "23",
"size": "6713",
"license": "bsd-3-clause",
"hash": 1055551957546794400,
"line_mean": 34.8983957219,
"line_max": 81,
"alpha_frac": 0.8000893788,
"autogenerated": false,
"ratio": 2.4473204520597887,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API tillg\xe4ngligt'
apiAttachNotAvailable = u'Inte tillg\xe4ngligt'
apiAttachPendingAuthorization = u'Godk\xe4nnande avvaktas'
apiAttachRefused = u'Nekades'
apiAttachSuccess = u'Det lyckades'
apiAttachUnknown = u'Ok\xe4nd'
budDeletedFriend = u'Borttagen fr\xe5n kontaktlistan'
budFriend = u'V\xe4n'
budNeverBeenFriend = u'Aldrig varit i kontaktlistan'
budPendingAuthorization = u'Godk\xe4nnande avvaktas'
budUnknown = u'Ok\xe4nd'
cfrBlockedByRecipient = u'Samtalet blockerades av mottagaren'
cfrMiscError = u'Div fel'
cfrNoCommonCodec = u'Gemensam codec saknas'
cfrNoProxyFound = u'Mellanserver finns inte'
cfrNotAuthorizedByRecipient = u'Aktuell anv\xe4ndare inte godk\xe4nd av mottagaren'
cfrRecipientNotFriend = u'Mottagaren ej en v\xe4n'
cfrRemoteDeviceError = u'Det har uppst\xe5tt problem med motpartens ljudenhet'
cfrSessionTerminated = u'Sessionen avslutad'
cfrSoundIOError = u'I/O-fel p\xe5 ljudet'
cfrSoundRecordingError = u'Ljudinspelningsfel'
cfrUnknown = u'Ok\xe4nd'
cfrUserDoesNotExist = u'Anv\xe4ndaren/telefonnumret finns inte'
cfrUserIsOffline = u'Anv\xe4ndaren \xe4r offline'
chsAllCalls = u'Legacy-dialog'
chsDialog = u'Dialog'
chsIncomingCalls = u'Kr\xe4ver multi-godk\xe4nnande'
chsLegacyDialog = u'Legacy-dialog'
chsMissedCalls = u'Dialog'
chsMultiNeedAccept = u'Kr\xe4ver multi-godk\xe4nnande'
chsMultiSubscribed = u'Multi-abonnerade'
chsOutgoingCalls = u'Multi-abonnerade'
chsUnknown = u'Ok\xe4nd'
chsUnsubscribed = u'Avabonnerad'
clsBusy = u'Upptaget'
clsCancelled = u'Avbruten'
clsEarlyMedia = u'Spelar Early Media'
clsFailed = u'Samtalet kunde inte kopplas'
clsFinished = u'Avslutat'
clsInProgress = u'P\xe5g\xe5ende samtal'
clsLocalHold = u'Lokalt parkerat samtal'
clsMissed = u'missat samtal'
clsOnHold = u'Parkerad'
clsRefused = u'Nekades'
clsRemoteHold = u'Fj\xe4rrparkerat samtal'
clsRinging = u'pratat'
clsRouting = u'Routar'
clsTransferred = u'Ok\xe4nd'
clsTransferring = u'Ok\xe4nd'
clsUnknown = u'Ok\xe4nd'
clsUnplaced = u'Inte uppringt'
clsVoicemailBufferingGreeting = u'Buffrar h\xe4lsningen'
clsVoicemailCancelled = u'R\xf6stmeddelandet avbr\xf6ts'
clsVoicemailFailed = u'R\xf6stmeddelandet misslyckades'
clsVoicemailPlayingGreeting = u'Spelar h\xe4lsningen'
clsVoicemailRecording = u'Spelar in r\xf6stmeddelande'
clsVoicemailSent = u'R\xf6stmeddelandet skickades'
clsVoicemailUploading = u'Laddar upp r\xf6stmeddelande'
cltIncomingP2P = u'Inkommande P2P-samtal'
cltIncomingPSTN = u'Inkommande telefonsamtal'
cltOutgoingP2P = u'Utg\xe5ende P2P-samtal'
cltOutgoingPSTN = u'Utg\xe5ende telefonsamtal'
cltUnknown = u'Ok\xe4nd'
cmeAddedMembers = u'Medlemmar lades till'
cmeCreatedChatWith = u'Startade chatt med'
cmeEmoted = u'Ok\xe4nd'
cmeLeft = u'L\xe4mnade'
cmeSaid = u'Redan sagt'
cmeSawMembers = u'S\xe5g medlemmar'
cmeSetTopic = u'Ange \xe4mne'
cmeUnknown = u'Ok\xe4nd'
cmsRead = u'L\xe4stes'
cmsReceived = u'Togs emot'
cmsSending = u'S\xe4nder...'
cmsSent = u'Skickades'
cmsUnknown = u'Ok\xe4nd'
conConnecting = u'Ansluter...'
conOffline = u'Offline'
conOnline = u'Online'
conPausing = u'Pauserar'
conUnknown = u'Ok\xe4nd'
cusAway = u'Tillf\xe4lligt borta'
cusDoNotDisturb = u'St\xf6r ej'
cusInvisible = u'Osynlig'
cusLoggedOut = u'Offline'
cusNotAvailable = u'Inte tillg\xe4ngligt'
cusOffline = u'Offline'
cusOnline = u'Online'
cusSkypeMe = u'Skype Me'
cusUnknown = u'Ok\xe4nd'
cvsBothEnabled = u'Skickar och tar emot video'
cvsNone = u'Ingen video'
cvsReceiveEnabled = u'Tar emot video'
cvsSendEnabled = u'Skickar video'
cvsUnknown = u''
grpAllFriends = u'Alla kontakter'
grpAllUsers = u'Alla anv\xe4ndare'
grpCustomGroup = u'S\xe4rskild'
grpOnlineFriends = u'Online-v\xe4nner'
grpPendingAuthorizationFriends = u'Godk\xe4nnande avvaktas'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Nyligen kontaktade anv\xe4ndare'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype-kontakter'
grpSkypeOutFriends = u'SkypeOut-kontakter'
grpUngroupedFriends = u'Icke grupperade kontakter'
grpUnknown = u'Ok\xe4nd'
grpUsersAuthorizedByMe = u'Godk\xe4nda av mig'
grpUsersBlockedByMe = u'Blockerade av mig'
grpUsersWaitingMyAuthorization = u'Avvaktar mitt godk\xe4nnande'
leaAddDeclined = u'Till\xe4gg nekades'
leaAddedNotAuthorized = u'Den som l\xe4ggs till m\xe5ste vara godk\xe4nd'
leaAdderNotFriend = u'Den som l\xe4gger till m\xe5ste vara en v\xe4n'
leaUnknown = u'Ok\xe4nd'
leaUnsubscribe = u'Avabonnerad'
leaUserIncapable = u'Anv\xe4ndaren kan inte'
leaUserNotFound = u'Anv\xe4ndaren finns inte'
olsAway = u'Tillf\xe4lligt borta'
olsDoNotDisturb = u'St\xf6r ej'
olsNotAvailable = u'Inte tillg\xe4ngligt'
olsOffline = u'Offline'
olsOnline = u'Online'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Ok\xe4nd'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Kvinna'
usexMale = u'Man'
usexUnknown = u'Ok\xe4nd'
vmrConnectError = u'Anslutningsfel'
vmrFileReadError = u'Fill\xe4sningsfel'
vmrFileWriteError = u'Filskrivningsfel'
vmrMiscError = u'Div fel'
vmrNoError = u'Inget fel'
vmrNoPrivilege = u'Voicemail-beh\xf6righet saknas'
vmrNoVoicemail = u'R\xf6stmeddelande saknas'
vmrPlaybackError = u'Uppspelningsfel'
vmrRecordingError = u'Inspelningsfel'
vmrUnknown = u'Ok\xe4nd'
vmsBlank = u'Tomt'
vmsBuffering = u'Buffrar'
vmsDeleting = u'Tar bort'
vmsDownloading = u'Laddar ner'
vmsFailed = u'Misslyckades'
vmsNotDownloaded = u'Inte nerladdat'
vmsPlayed = u'Uppspelat'
vmsPlaying = u'Spelar upp'
vmsRecorded = u'Inspelat'
vmsRecording = u'Spelar in r\xf6stmeddelande'
vmsUnknown = u'Ok\xe4nd'
vmsUnplayed = u'Inte uppspelat'
vmsUploaded = u'Uppladdat'
vmsUploading = u'Laddar upp'
vmtCustomGreeting = u'S\xe4rskild h\xe4lsning'
vmtDefaultGreeting = u'Standardh\xe4lsning'
vmtIncoming = u'Nytt r\xf6stmeddelande'
vmtOutgoing = u'Utg\xe5ende'
vmtUnknown = u'Ok\xe4nd'
vssAvailable = u'Tillg\xe4ngligt'
vssNotAvailable = u'Inte tillg\xe4ngligt'
vssPaused = u'Pausat'
vssRejected = u'Nekades'
vssRunning = u'P\xe5g\xe5r'
vssStarting = u'Startar'
vssStopping = u'Stannar'
vssUnknown = u'Ok\xe4nd'
| {
"repo_name": "djw8605/htcondor",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/sv.py",
"copies": "10",
"size": "7128",
"license": "apache-2.0",
"hash": -5837045650603632000,
"line_mean": 36.1176470588,
"line_max": 83,
"alpha_frac": 0.7791806958,
"autogenerated": false,
"ratio": 2.2971318079278116,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00006291286568103177,
"num_lines": 187
} |
apiAttachAvailable = u'API \u05d6\u05de\u05d9\u05df'
apiAttachNotAvailable = u'\u05d0\u05d9\u05e0\u05d5 \u05d6\u05de\u05d9\u05df'
apiAttachPendingAuthorization = u'\u05de\u05de\u05ea\u05d9\u05df \u05dc\u05d0\u05d9\u05e9\u05d5\u05e8'
apiAttachRefused = u'\u05e0\u05d3\u05d7\u05d4'
apiAttachSuccess = u'\u05d4\u05e6\u05dc\u05d7\u05d4'
apiAttachUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
budDeletedFriend = u'\u05e0\u05de\u05d7\u05e7 \u05de\u05e8\u05e9\u05d9\u05de\u05ea \u05d7\u05d1\u05e8\u05d9\u05dd'
budFriend = u'\u05d7\u05d1\u05e8'
budNeverBeenFriend = u'\u05dc\u05e2\u05d5\u05dc\u05dd \u05dc\u05d0 \u05d4\u05d9\u05d4 \u05d1\u05e8\u05e9\u05d9\u05de\u05ea \u05d7\u05d1\u05e8\u05d9\u05dd'
budPendingAuthorization = u'\u05de\u05de\u05ea\u05d9\u05df \u05dc\u05d0\u05d9\u05e9\u05d5\u05e8'
budUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cfrBlockedByRecipient = u'\u05d4\u05e9\u05d9\u05d7\u05d4 \u05e0\u05d7\u05e1\u05de\u05d4 \u05e2\u05dc \u05d9\u05d3\u05d9 \u05d4\u05de\u05e7\u05d1\u05dc'
cfrMiscError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05e9\u05d5\u05e0\u05d4'
cfrNoCommonCodec = u'\u05d0\u05d9\u05df \u05e7\u05d9\u05d3\u05d5\u05d3'
cfrNoProxyFound = u'\u05dc\u05d0 \u05e0\u05de\u05e6\u05d0 \u05e4\u05e8\u05d5\u05e7\u05e1\u05d9'
cfrNotAuthorizedByRecipient = u'\u05d4\u05de\u05e9\u05ea\u05de\u05e9 \u05d4\u05e0\u05d5\u05db\u05d7\u05d9 \u05d0\u05d9\u05e0\u05d5 \u05de\u05d0\u05d5\u05e9\u05e8 \u05e2\u05dc \u05d9\u05d3\u05d9 \u05d4\u05de\u05e7\u05d1\u05dc'
cfrRecipientNotFriend = u'\u05d4\u05de\u05e7\u05d1\u05dc \u05d0\u05d9\u05e0\u05d5 \u05d7\u05d1\u05e8'
cfrRemoteDeviceError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05d4\u05ea\u05e7\u05df \u05e6\u05dc\u05d9\u05dc \u05e9\u05dc\u05d0 \u05d1\u05de\u05d7\u05e9\u05d1 \u05d6\u05d4'
cfrSessionTerminated = u'\u05de\u05e4\u05d2\u05e9 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd'
cfrSoundIOError = u'\u05e9\u05d2\u05d9\u05d0\u05ea \u05e7\u05d5\u05dc I/O'
cfrSoundRecordingError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05d4\u05e7\u05dc\u05d8\u05ea \u05e7\u05d5\u05dc'
cfrUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cfrUserDoesNotExist = u'\u05de\u05e9\u05ea\u05de\u05e9/\u05de\u05e1\u05e4\u05e8 \u05d8\u05dc\u05e4\u05d5\u05df \u05d0\u05d9\u05e0\u05d5 \u05e7\u05d9\u05d9\u05dd'
cfrUserIsOffline = u'\u05d4\u05d9\u05d0 \u05d0\u05d5 \u05d4\u05d5\u05d0 \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8\u05d9\u05dd'
chsAllCalls = u'\u05ea\u05d9\u05d1\u05ea \u05d3\u05d5-\u05e9\u05d9\u05d7 \u05e7\u05d5\u05d3\u05de\u05ea'
chsDialog = u'\u05ea\u05d9\u05d1\u05ea \u05d3\u05d5-\u05e9\u05d9\u05d7'
chsIncomingCalls = u"\u05e6\u05d5\u05e8\u05da \u05d1\u05d0\u05d9\u05e9\u05d5\u05e8 \u05e6'\u05d8 \u05de\u05e8\u05d5\u05d1\u05d4 \u05de\u05e9\u05ea\u05ea\u05e4\u05d9\u05dd"
chsLegacyDialog = u'\u05ea\u05d9\u05d1\u05ea \u05d3\u05d5-\u05e9\u05d9\u05d7 \u05e7\u05d5\u05d3\u05de\u05ea'
chsMissedCalls = u'\u05ea\u05d9\u05d1\u05ea \u05d3\u05d5-\u05e9\u05d9\u05d7'
chsMultiNeedAccept = u"\u05e6\u05d5\u05e8\u05da \u05d1\u05d0\u05d9\u05e9\u05d5\u05e8 \u05e6'\u05d8 \u05de\u05e8\u05d5\u05d1\u05d4 \u05de\u05e9\u05ea\u05ea\u05e4\u05d9\u05dd"
chsMultiSubscribed = u"\u05e6'\u05d8 \u05de\u05e8\u05d5\u05d1\u05d4 \u05de\u05e9\u05ea\u05ea\u05e4\u05d9\u05dd"
chsOutgoingCalls = u"\u05e6'\u05d8 \u05de\u05e8\u05d5\u05d1\u05d4 \u05de\u05e9\u05ea\u05ea\u05e4\u05d9\u05dd"
chsUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
chsUnsubscribed = u'\u05d1\u05d9\u05d8\u05d5\u05dc \u05d4\u05e9\u05ea\u05ea\u05e4\u05d5\u05ea'
clsBusy = u'\u05ea\u05e4\u05d5\u05e1'
clsCancelled = u'\u05d1\u05d5\u05d8\u05dc'
clsEarlyMedia = u'\u05e0\u05d2\u05df Early Media'
clsFailed = u'\u05d4\u05e9\u05d9\u05d7\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4'
clsFinished = u'\u05d4\u05e1\u05ea\u05d9\u05d9\u05de\u05d4'
clsInProgress = u'\u05e9\u05d9\u05d7\u05d4 \u05de\u05ea\u05e7\u05d9\u05d9\u05de\u05ea'
clsLocalHold = u'\u05d1\u05d4\u05de\u05ea\u05e0\u05d4'
clsMissed = u'\u05e9\u05d9\u05d7\u05d4 \u05e9\u05dc\u05d0 \u05e0\u05e2\u05e0\u05ea\u05d4'
clsOnHold = u'\u05de\u05d7\u05d6\u05d9\u05e7'
clsRefused = u'\u05e0\u05d3\u05d7\u05d4'
clsRemoteHold = u'\u05d1\u05d4\u05de\u05ea\u05e0\u05d4'
clsRinging = u'\u05de\u05d7\u05d9\u05d9\u05d2'
clsRouting = u'\u05de\u05e0\u05ea\u05d1'
clsTransferred = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
clsTransferring = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
clsUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
clsUnplaced = u'\u05dc\u05d0 \u05d1\u05d5\u05e6\u05e2'
clsVoicemailBufferingGreeting = u'\u05d7\u05d5\u05e6\u05e5 \u05d4\u05d5\u05d3\u05e2\u05ea \u05e4\u05ea\u05d9\u05d7\u05d4'
clsVoicemailCancelled = u'\u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea \u05d1\u05d5\u05d8\u05dc\u05d4'
clsVoicemailFailed = u'\u05d4\u05d4\u05d5\u05d3\u05e2\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4'
clsVoicemailPlayingGreeting = u'\u05de\u05e9\u05de\u05d9\u05e2 \u05d4\u05d5\u05d3\u05e2\u05ea \u05e4\u05ea\u05d9\u05d7\u05d4'
clsVoicemailRecording = u'\u05d4\u05e7\u05dc\u05d8\u05ea \u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea'
clsVoicemailSent = u'\u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea \u05e0\u05e9\u05dc\u05d7\u05d4'
clsVoicemailUploading = u'\u05e9\u05d5\u05dc\u05d7 \u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea'
cltIncomingP2P = u'\u05e9\u05d9\u05d7\u05ea \u05e2\u05de\u05d9\u05ea-\u05dc\u05e2\u05de\u05d9\u05ea \u05e0\u05db\u05e0\u05e1\u05ea'
cltIncomingPSTN = u'\u05e9\u05d9\u05d7\u05ea \u05d8\u05dc\u05e4\u05d5\u05df \u05e0\u05db\u05e0\u05e1\u05ea'
cltOutgoingP2P = u'\u05e9\u05d9\u05d7\u05ea \u05e2\u05de\u05d9\u05ea-\u05dc\u05e2\u05de\u05d9\u05ea \u05d9\u05d5\u05e6\u05d0\u05ea'
cltOutgoingPSTN = u'\u05e9\u05d9\u05d7\u05ea \u05d8\u05dc\u05e4\u05d5\u05df \u05d9\u05d5\u05e6\u05d0\u05ea'
cltUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cmeAddedMembers = u'\u05d7\u05d1\u05e8\u05d9\u05dd \u05e9\u05d4\u05ea\u05d5\u05d5\u05e1\u05e4\u05d5'
cmeCreatedChatWith = u"\u05e6\u05d5\u05e8 \u05e6'\u05d8 \u05e2\u05dd"
cmeEmoted = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cmeLeft = u'\u05e2\u05d6\u05d1'
cmeSaid = u'Said'
cmeSawMembers = u'\u05d7\u05d1\u05e8\u05d9\u05dd \u05e9\u05e0\u05e8\u05d0\u05d5'
cmeSetTopic = u'\u05e7\u05d1\u05e2 \u05e0\u05d5\u05e9\u05d0'
cmeUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cmsRead = u'\u05e0\u05e7\u05e8\u05d0\u05d4'
cmsReceived = u'\u05e0\u05ea\u05e7\u05d1\u05dc\u05d4'
cmsSending = u'....\u05e9\u05d5\u05dc\u05d7'
cmsSent = u'\u05e0\u05e9\u05dc\u05d7\u05d4'
cmsUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
conConnecting = u'\u05de\u05ea\u05d7\u05d1\u05e8'
conOffline = u'\u05de\u05e0\u05d5\u05ea\u05e7'
conOnline = u'\u05de\u05d7\u05d5\u05d1\u05e8'
conPausing = u'\u05d4\u05e4\u05e1\u05e7\u05d4'
conUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cusAway = u'\u05dc\u05d0 \u05e0\u05de\u05e6\u05d0'
cusDoNotDisturb = u'\u05e0\u05d0 \u05dc\u05d0 \u05dc\u05d4\u05e4\u05e8\u05d9\u05e2'
cusInvisible = u'\u05d1\u05dc\u05ea\u05d9 \u05e0\u05e8\u05d0\u05d4'
cusLoggedOut = u'\u05de\u05e0\u05d5\u05ea\u05e7'
cusNotAvailable = u'\u05d0\u05d9\u05e0\u05d5 \u05d6\u05de\u05d9\u05df'
cusOffline = u'\u05de\u05e0\u05d5\u05ea\u05e7'
cusOnline = u'\u05de\u05d7\u05d5\u05d1\u05e8'
cusSkypeMe = u'\u05d3\u05d1\u05e8 \u05d0\u05ea\u05d9'
cusUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
cvsBothEnabled = u'\u05e9\u05dc\u05d7 \u05d5\u05e7\u05d1\u05dc \u05d5\u05d9\u05d3\u05d0\u05d5'
cvsNone = u'\u05d0\u05d9\u05df \u05d5\u05d9\u05d3\u05d0\u05d5'
cvsReceiveEnabled = u'\u05d5\u05d9\u05d3\u05d0\u05d5 \u05d4\u05ea\u05e7\u05d1\u05dc'
cvsSendEnabled = u'\u05d5\u05d9\u05d3\u05d0\u05d5 \u05e0\u05e9\u05dc\u05d7'
cvsUnknown = u''
grpAllFriends = u'\u05db\u05dc \u05d4\u05d7\u05d1\u05e8\u05d9\u05dd'
grpAllUsers = u'\u05db\u05dc \u05d4\u05de\u05e9\u05ea\u05de\u05e9\u05d9\u05dd'
grpCustomGroup = u'\u05de\u05d5\u05ea\u05d0\u05dd \u05d0\u05d9\u05e9\u05d9\u05ea'
grpOnlineFriends = u'\u05d7\u05d1\u05e8\u05d9\u05dd \u05de\u05d7\u05d5\u05d1\u05e8\u05d9\u05dd'
grpPendingAuthorizationFriends = u'\u05de\u05de\u05ea\u05d9\u05df \u05dc\u05d0\u05d9\u05e9\u05d5\u05e8'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\u05de\u05e9\u05ea\u05de\u05e9\u05d9\u05dd \u05d0\u05d9\u05ea\u05dd \u05e0\u05d5\u05e6\u05e8 \u05e7\u05e9\u05e8 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'\u05d7\u05d1\u05e8\u05d9 \u05e1\u05e7\u05d9\u05d9\u05e4'
grpSkypeOutFriends = u'\u05d7\u05d1\u05e8\u05d9 SkypeOut'
grpUngroupedFriends = u'\u05d7\u05d1\u05e8\u05d9\u05dd \u05dc\u05dc\u05d0 \u05e7\u05d1\u05d5\u05e6\u05d4'
grpUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
grpUsersAuthorizedByMe = u'\u05d0\u05d5\u05e9\u05e8 \u05e2\u05dc \u05d9\u05d3\u05d9'
grpUsersBlockedByMe = u'\u05e0\u05d7\u05e1\u05dd \u05e2\u05dc \u05d9\u05d3\u05d9'
grpUsersWaitingMyAuthorization = u'\u05de\u05de\u05ea\u05d9\u05df \u05dc\u05d0\u05d9\u05e9\u05d5\u05e8\u05d9'
leaAddDeclined = u'\u05d4\u05d1\u05e7\u05e9\u05d4 \u05e0\u05d3\u05d7\u05ea\u05d4'
leaAddedNotAuthorized = u'\u05d4\u05de\u05d5\u05e1\u05d9\u05e3 \u05d7\u05d9\u05d9\u05d1 \u05dc\u05d4\u05d9\u05d5\u05ea \u05de\u05d0\u05d5\u05e9\u05e8'
leaAdderNotFriend = u'\u05d4\u05de\u05d5\u05e1\u05d9\u05e3 \u05d7\u05d9\u05d9\u05d1 \u05dc\u05d4\u05d9\u05d5\u05ea \u05d7\u05d1\u05e8'
leaUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
leaUnsubscribe = u'\u05d1\u05d9\u05d8\u05d5\u05dc \u05d4\u05e9\u05ea\u05ea\u05e4\u05d5\u05ea'
leaUserIncapable = u'\u05de\u05e9\u05ea\u05de\u05e9 \u05dc\u05d0 \u05de\u05ea\u05d0\u05d9\u05dd'
leaUserNotFound = u'\u05de\u05e9\u05ea\u05de\u05e9 \u05dc\u05d0 \u05e0\u05de\u05e6\u05d0'
olsAway = u'\u05dc\u05d0 \u05e0\u05de\u05e6\u05d0'
olsDoNotDisturb = u'\u05e0\u05d0 \u05dc\u05d0 \u05dc\u05d4\u05e4\u05e8\u05d9\u05e2'
olsNotAvailable = u'\u05d0\u05d9\u05e0\u05d5 \u05d6\u05de\u05d9\u05df'
olsOffline = u'\u05de\u05e0\u05d5\u05ea\u05e7'
olsOnline = u'\u05de\u05d7\u05d5\u05d1\u05e8'
olsSkypeMe = u'\u05d3\u05d1\u05e8 \u05d0\u05ea\u05d9'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\u05e0\u05e7\u05d1\u05d4'
usexMale = u'\u05d6\u05db\u05e8'
usexUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
vmrConnectError = u'\u05e9\u05d2\u05d9\u05d0\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8'
vmrFileReadError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05e7\u05e8\u05d9\u05d0\u05ea \u05d4\u05e7\u05d5\u05d1\u05e5'
vmrFileWriteError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05db\u05ea\u05d9\u05d1\u05d4 \u05dc\u05e7\u05d5\u05d1\u05e5'
vmrMiscError = u'\u05e9\u05d2\u05d9\u05d0\u05d4 \u05e9\u05d5\u05e0\u05d4'
vmrNoError = u'\u05d0\u05d9\u05df \u05e9\u05d2\u05d9\u05d0\u05d4'
vmrNoPrivilege = u'\u05dc\u05d0 \u05d6\u05db\u05d0\u05d9 \u05dc\u05ea\u05d0 \u05e7\u05d5\u05dc\u05d9'
vmrNoVoicemail = u'\u05ea\u05d0 \u05e7\u05d5\u05dc\u05d9 \u05dc\u05d0 \u05e7\u05d9\u05d9\u05dd'
vmrPlaybackError = u'\u05e9\u05d2\u05d9\u05d0\u05ea \u05d4\u05e9\u05de\u05e2\u05d4'
vmrRecordingError = u'\u05e9\u05d2\u05d9\u05d0\u05ea \u05d4\u05e7\u05dc\u05d8\u05d4'
vmrUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
vmsBlank = u'\u05e8\u05d9\u05e7\u05d4'
vmsBuffering = u'\u05d7\u05e6\u05d9\u05e6\u05d4'
vmsDeleting = u'\u05e0\u05de\u05d7\u05e7\u05ea'
vmsDownloading = u'\u05d4\u05d5\u05e8\u05d3\u05d4'
vmsFailed = u'\u05e0\u05db\u05e9\u05dc\u05d4'
vmsNotDownloaded = u'\u05dc\u05d0 \u05d4\u05d5\u05e8\u05d3\u05d4'
vmsPlayed = u'\u05d4\u05d5\u05e9\u05de\u05e2\u05d4'
vmsPlaying = u'\u05de\u05d5\u05e9\u05de\u05e2\u05ea'
vmsRecorded = u'\u05d4\u05d5\u05e7\u05dc\u05d8\u05d4'
vmsRecording = u'\u05d4\u05e7\u05dc\u05d8\u05ea \u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea'
vmsUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
vmsUnplayed = u'\u05dc\u05d0 \u05d4\u05d5\u05e9\u05de\u05e2\u05d4'
vmsUploaded = u'\u05e0\u05e9\u05dc\u05d7\u05d4'
vmsUploading = u'\u05e0\u05e9\u05dc\u05d7\u05ea'
vmtCustomGreeting = u'\u05d4\u05d5\u05d3\u05e2\u05ea \u05e4\u05ea\u05d9\u05d7\u05d4 \u05de\u05d5\u05ea\u05d0\u05de\u05ea \u05d0\u05d9\u05e9\u05d9\u05ea'
vmtDefaultGreeting = u'\u05d4\u05d5\u05d3\u05e2\u05ea \u05e4\u05ea\u05d9\u05d7\u05d4 - \u05d1\u05e8\u05d9\u05e8\u05ea \u05de\u05d7\u05d3\u05dc'
vmtIncoming = u'\u05e0\u05db\u05e0\u05e1\u05ea \u05d4\u05d5\u05d3\u05e2\u05d4 \u05e7\u05d5\u05dc\u05d9\u05ea'
vmtOutgoing = u'\u05d9\u05d5\u05e6\u05d0\u05ea'
vmtUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
vssAvailable = u'\u05d6\u05de\u05d9\u05e0\u05d4'
vssNotAvailable = u'\u05d0\u05d9\u05e0\u05d5 \u05d6\u05de\u05d9\u05df'
vssPaused = u'\u05d4\u05e4\u05e1\u05e7\u05d4'
vssRejected = u'\u05e0\u05d3\u05d7\u05d4'
vssRunning = u'\u05e4\u05d5\u05e2\u05dc\u05ea'
vssStarting = u'\u05d4\u05ea\u05d7\u05dc'
vssStopping = u'\u05e2\u05e6\u05d9\u05e8\u05d4'
vssUnknown = u'\u05dc\u05d0 \u05d9\u05d3\u05d5\u05e2'
| {
"repo_name": "aodag/skype4py",
"path": "Skype4Py/lang/he.py",
"copies": "23",
"size": "13652",
"license": "bsd-3-clause",
"hash": 1903925072101460000,
"line_mean": 72.0053475936,
"line_max": 225,
"alpha_frac": 0.7917521242,
"autogenerated": false,
"ratio": 1.5693757903207266,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f'
apiAttachNotAvailable = u'\u7121\u52b9'
apiAttachPendingAuthorization = u'\u8a8d\u8a3c\u5f85\u3061'
apiAttachRefused = u'\u62d2\u5426\u3055\u308c\u307e\u3057\u305f'
apiAttachSuccess = u'\u6210\u529f'
apiAttachUnknown = u'\u4e0d\u660e'
budDeletedFriend = u'\u53cb\u4eba\u30ea\u30b9\u30c8\u304b\u3089\u524a\u9664\u3055\u308c\u307e\u3057\u305f'
budFriend = u'\u53cb\u4eba'
budNeverBeenFriend = u'\u53cb\u4eba\u30ea\u30b9\u30c8\u306b\u672a\u8ffd\u52a0'
budPendingAuthorization = u'\u8a8d\u8a3c\u5f85\u3061'
budUnknown = u'\u4e0d\u660e'
cfrBlockedByRecipient = u'\u76f8\u624b\u306b\u901a\u8a71\u304c\u30d6\u30ed\u30c3\u30af\u3055\u308c\u307e\u3057\u305f'
cfrMiscError = u'\u305d\u306e\u4ed6\u30a8\u30e9\u30fc'
cfrNoCommonCodec = u'\u4e00\u822c\u7684\u306a\u30b3\u30fc\u30c7\u30c3\u30af\u3067\u306f\u3042\u308a\u307e\u305b\u3093'
cfrNoProxyFound = u'\u30d7\u30ed\u30ad\u30b7\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093'
cfrNotAuthorizedByRecipient = u'\u30e6\u30fc\u30b6\u304c\u53d7\u4fe1\u8005\u306b\u8a8d\u8a3c\u3055\u308c\u3066\u3044\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059\u3002'
cfrRecipientNotFriend = u'\u53d7\u4fe1\u8005\u306f\u53cb\u4eba\u3068\u3057\u3066\u767b\u9332\u3055\u308c\u3066\u3044\u307e\u305b\u3093'
cfrRemoteDeviceError = u'\u30ea\u30e2\u30fc\u30c8\u30aa\u30fc\u30c7\u30a3\u30aa\u30c7\u30d0\u30a4\u30b9\u306b\u554f\u984c\u304c\u3042\u308a\u307e\u3059'
cfrSessionTerminated = u'\u30bb\u30c3\u30b7\u30e7\u30f3\u7d42\u4e86'
cfrSoundIOError = u'\u97f3\u58f0\u51fa\u5165\u529b\u30a8\u30e9\u30fc'
cfrSoundRecordingError = u'\u97f3\u58f0\u9332\u97f3\u30a8\u30e9\u30fc'
cfrUnknown = u'\u4e0d\u660e'
cfrUserDoesNotExist = u'\u30e6\u30fc\u30b6\u30fb\u96fb\u8a71\u756a\u53f7\u304c\u5b58\u5728\u3057\u307e\u305b\u3093'
cfrUserIsOffline = u'\u30aa\u30d5\u30e9\u30a4\u30f3\u3067\u3059'
chsAllCalls = u'\u30ec\u30ac\u30b7\u30fc\u30c0\u30a4\u30a2\u30ed\u30b0'
chsDialog = u'\u30c0\u30a4\u30a2\u30ed\u30b0'
chsIncomingCalls = u'\u8907\u6570\u53d7\u4fe1\u8a31\u53ef\u5f85\u3061\u3042\u308a'
chsLegacyDialog = u'\u30ec\u30ac\u30b7\u30fc\u30c0\u30a4\u30a2\u30ed\u30b0'
chsMissedCalls = u'\u30c0\u30a4\u30a2\u30ed\u30b0'
chsMultiNeedAccept = u'\u8907\u6570\u53d7\u4fe1\u8a31\u53ef\u5f85\u3061\u3042\u308a'
chsMultiSubscribed = u'\u8907\u6570\u5951\u7d04\u3042\u308a'
chsOutgoingCalls = u'\u8907\u6570\u5951\u7d04\u3042\u308a'
chsUnknown = u'\u4e0d\u660e'
chsUnsubscribed = u'\u5951\u7d04\u306a\u3057'
clsBusy = u'\u53d6\u308a\u8fbc\u307f\u4e2d'
clsCancelled = u'\u30ad\u30e3\u30f3\u30bb\u30eb\u3055\u308c\u307e\u3057\u305f'
clsEarlyMedia = u'\u65e9\u671f\u30e1\u30c7\u30a3\u30a2\u518d\u751f\u4e2d'
clsFailed = u'\u901a\u8a71\u63a5\u7d9a\u306b\u5931\u6557\u3057\u307e\u3057\u305f\u3002'
clsFinished = u'\u7d42\u4e86'
clsInProgress = u'\u901a\u8a71\u4e2d'
clsLocalHold = u'\u81ea\u8eab\u306b\u3088\u308b\u4e00\u6642\u505c\u6b62\u4e2d'
clsMissed = u'\u4ef6\u306e\u4e0d\u5728\u7740\u4fe1'
clsOnHold = u'\u4fdd\u7559\u4e2d'
clsRefused = u'\u62d2\u5426\u3055\u308c\u307e\u3057\u305f'
clsRemoteHold = u'\u76f8\u624b\u304c'
clsRinging = u'\u901a\u8a71\u4e2d'
clsRouting = u'\u30eb\u30fc\u30c6\u30a3\u30f3\u30b0\u4e2d'
clsTransferred = u'\u4e0d\u660e'
clsTransferring = u'\u4e0d\u660e'
clsUnknown = u'\u4e0d\u660e'
clsUnplaced = u'\u901a\u8a71\u306f\u767a\u4fe1\u3055\u308c\u307e\u305b\u3093\u3067\u3057\u305f'
clsVoicemailBufferingGreeting = u'\u5fdc\u7b54\u30e1\u30c3\u30bb\u30fc\u30b8\u306e\u30d0\u30c3\u30d5\u30a1\u4e2d'
clsVoicemailCancelled = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u304c\u30ad\u30e3\u30f3\u30bb\u30eb\u3055\u308c\u307e\u3057\u305f'
clsVoicemailFailed = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u9001\u4fe1\u5931\u6557'
clsVoicemailPlayingGreeting = u'\u5fdc\u7b54\u30e1\u30c3\u30bb\u30fc\u30b8\u306e\u518d\u751f\u4e2d'
clsVoicemailRecording = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u3092\u9332\u97f3\u4e2d'
clsVoicemailSent = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u304c\u9001\u4fe1\u3055\u308c\u307e\u3057\u305f'
clsVoicemailUploading = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u306e\u30a2\u30c3\u30d7\u30ed\u30fc\u30c9\u4e2d'
cltIncomingP2P = u'P2P\u901a\u8a71\u7740\u4fe1'
cltIncomingPSTN = u'\u96fb\u8a71\u7740\u4fe1'
cltOutgoingP2P = u'P2P\u901a\u8a71\u9001\u4fe1'
cltOutgoingPSTN = u'\u96fb\u8a71\u9001\u4fe1'
cltUnknown = u'\u4e0d\u660e'
cmeAddedMembers = u'\u30e1\u30f3\u30d0\u30fc\u3092\u8ffd\u52a0\u3057\u307e\u3057\u305f'
cmeCreatedChatWith = u'\u30c1\u30e3\u30c3\u30c8\u3092\u4f5c\u6210\uff1a'
cmeEmoted = u'\u4e0d\u660e'
cmeLeft = u'\u6b8b\u3057\u307e\u3057\u305f'
cmeSaid = u'\u8a00\u3044\u307e\u3057\u305f'
cmeSawMembers = u'\u30e1\u30f3\u30d0\u30fc\u3092\u8868\u793a\u3057\u307e\u3057\u305f'
cmeSetTopic = u'\u30bf\u30a4\u30c8\u30eb\u3092\u8868\u793a'
cmeUnknown = u'\u4e0d\u660e'
cmsRead = u'\u65e2\u8aad'
cmsReceived = u'\u53d7\u4fe1\u5b8c\u4e86'
cmsSending = u'\u9001\u4fe1\u4e2d...'
cmsSent = u'\u9001\u4fe1\u6e08'
cmsUnknown = u'\u4e0d\u660e'
conConnecting = u'\u63a5\u7d9a\u4e2d'
conOffline = u'\u30aa\u30d5\u30e9\u30a4\u30f3'
conOnline = u'\u30aa\u30f3\u30e9\u30a4\u30f3'
conPausing = u'\u4e00\u6642\u505c\u6b62\u4e2d'
conUnknown = u'\u4e0d\u660e'
cusAway = u'\u4e00\u6642\u9000\u5e2d\u4e2d'
cusDoNotDisturb = u'\u53d6\u308a\u8fbc\u307f\u4e2d'
cusInvisible = u'\u30ed\u30b0\u30a4\u30f3\u72b6\u614b\u3092\u96a0\u3059'
cusLoggedOut = u'\u30aa\u30d5\u30e9\u30a4\u30f3'
cusNotAvailable = u'\u7121\u52b9'
cusOffline = u'\u30aa\u30d5\u30e9\u30a4\u30f3'
cusOnline = u'\u30aa\u30f3\u30e9\u30a4\u30f3'
cusSkypeMe = u'Skype Me'
cusUnknown = u'\u4e0d\u660e'
cvsBothEnabled = u'\u30d3\u30c7\u30aa\u9001\u53d7\u4fe1'
cvsNone = u'\u30d3\u30c7\u30aa\u306a\u3057'
cvsReceiveEnabled = u'\u30d3\u30c7\u30aa\u53d7\u4fe1'
cvsSendEnabled = u'\u30d3\u30c7\u30aa\u9001\u4fe1'
cvsUnknown = u''
grpAllFriends = u'\u3059\u3079\u3066\u306e\u53cb\u4eba'
grpAllUsers = u'\u3059\u3079\u3066\u306e\u30e6\u30fc\u30b6'
grpCustomGroup = u'\u30aa\u30ea\u30b8\u30ca\u30eb'
grpOnlineFriends = u'\u30aa\u30f3\u30e9\u30a4\u30f3\u30d5\u30ec\u30f3\u30ba'
grpPendingAuthorizationFriends = u'\u8a8d\u8a3c\u5f85\u3061'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\u6700\u8fd1\u30b3\u30f3\u30bf\u30af\u30c8\u3057\u305f\u30e6\u30fc\u30b6'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype\u30d5\u30ec\u30f3\u30ba'
grpSkypeOutFriends = u'SkypeOut\u30d5\u30ec\u30f3\u30ba'
grpUngroupedFriends = u'\u30b0\u30eb\u30fc\u30d7\u306b\u5165\u3063\u3066\u3044\u306a\u3044\u30b3\u30f3\u30bf\u30af\u30c8'
grpUnknown = u'\u4e0d\u660e'
grpUsersAuthorizedByMe = u'\u8a8d\u8a3c\u3057\u305f\u30b0\u30eb\u30fc\u30d7'
grpUsersBlockedByMe = u'\u30d6\u30ed\u30c3\u30af\u3057\u305f\u30b0\u30eb\u30fc\u30d7'
grpUsersWaitingMyAuthorization = u'\u8a8d\u8a3c\u5f85\u3061'
leaAddDeclined = u'\u8ffd\u52a0\u62d2\u5426'
leaAddedNotAuthorized = u'\u8ffd\u52a0\u8005\u306f\u8a8d\u8a3c\u3055\u308c\u3066\u3044\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059'
leaAdderNotFriend = u'\u8ffd\u52a0\u8005\u306f\u53cb\u4eba\u306e\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059'
leaUnknown = u'\u4e0d\u660e'
leaUnsubscribe = u'\u5951\u7d04\u306a\u3057'
leaUserIncapable = u'\u30e6\u30fc\u30b6'
leaUserNotFound = u'\u30e6\u30fc\u30b6\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093'
olsAway = u'\u4e00\u6642\u9000\u5e2d\u4e2d'
olsDoNotDisturb = u'\u53d6\u308a\u8fbc\u307f\u4e2d'
olsNotAvailable = u'\u7121\u52b9'
olsOffline = u'\u30aa\u30d5\u30e9\u30a4\u30f3'
olsOnline = u'\u30aa\u30f3\u30e9\u30a4\u30f3'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'\u4e0d\u660e'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\u5973\u6027'
usexMale = u'\u7537\u6027'
usexUnknown = u'\u4e0d\u660e'
vmrConnectError = u'\u63a5\u7d9a\u30a8\u30e9\u30fc'
vmrFileReadError = u'\u30d5\u30a1\u30a4\u30eb\u8aad\u307f\u8fbc\u307f\u30a8\u30e9\u30fc'
vmrFileWriteError = u'\u30d5\u30a1\u30a4\u30eb\u66f8\u304d\u8fbc\u307f\u30a8\u30e9\u30fc'
vmrMiscError = u'\u305d\u306e\u4ed6\u30a8\u30e9\u30fc'
vmrNoError = u'\u30a8\u30e9\u30fc\u306a\u3057'
vmrNoPrivilege = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u5951\u7d04\u306a\u3057'
vmrNoVoicemail = u'\u8a72\u5f53\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093'
vmrPlaybackError = u'\u518d\u751f\u30a8\u30e9\u30fc'
vmrRecordingError = u'\u9332\u97f3\u30a8\u30e9\u30fc'
vmrUnknown = u'\u4e0d\u660e'
vmsBlank = u'\u7a7a\u6b04'
vmsBuffering = u'\u30d0\u30c3\u30d5\u30a1\u4e2d'
vmsDeleting = u'\u524a\u9664\u4e2d'
vmsDownloading = u'\u30c0\u30a6\u30f3\u30ed\u30fc\u30c9\u4e2d'
vmsFailed = u'\u5931\u6557'
vmsNotDownloaded = u'\u672a\u30c0\u30a6\u30f3\u30ed\u30fc\u30c9'
vmsPlayed = u'\u518d\u751f\u6e08'
vmsPlaying = u'\u518d\u751f\u4e2d'
vmsRecorded = u'\u9332\u97f3\u5b8c\u4e86'
vmsRecording = u'\u30dc\u30a4\u30b9\u30e1\u30fc\u30eb\u3092\u9332\u97f3\u4e2d'
vmsUnknown = u'\u4e0d\u660e'
vmsUnplayed = u'\u672a\u518d\u751f'
vmsUploaded = u'\u30a2\u30c3\u30d7\u30ed\u30fc\u30c9\u5b8c\u4e86'
vmsUploading = u'\u30a2\u30c3\u30d7\u30ed\u30fc\u30c9\u4e2d'
vmtCustomGreeting = u'\u30aa\u30ea\u30b8\u30ca\u30eb\u5fdc\u7b54\u30e1\u30c3\u30bb\u30fc\u30b8'
vmtDefaultGreeting = u'\u6a19\u6e96\u5fdc\u7b54\u30e1\u30c3\u30bb\u30fc\u30b8'
vmtIncoming = u'voicemail\u3092\u7740\u4fe1\u3057\u305f\u6642'
vmtOutgoing = u'\u9001\u4fe1'
vmtUnknown = u'\u4e0d\u660e'
vssAvailable = u'\u5229\u7528\u53ef\u80fd'
vssNotAvailable = u'\u7121\u52b9'
vssPaused = u'\u4e00\u6642\u505c\u6b62\u4e2d'
vssRejected = u'\u62d2\u5426\u3055\u308c\u307e\u3057\u305f'
vssRunning = u'\u518d\u751f\u4e2d'
vssStarting = u'\u8d77\u52d5\u4e2d'
vssStopping = u'\u505c\u6b62\u4e2d'
vssUnknown = u'\u4e0d\u660e'
| {
"repo_name": "sorenmalling/skype4py",
"path": "Skype4Py/lang/ja.py",
"copies": "23",
"size": "10544",
"license": "bsd-3-clause",
"hash": -4623542917846343000,
"line_mean": 55.385026738,
"line_max": 171,
"alpha_frac": 0.7959028832,
"autogenerated": false,
"ratio": 1.7130787977254265,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0016722434364565655,
"num_lines": 187
} |
apiAttachAvailable = u'API\u53ef\u4f9b\u4f7f\u7528'
apiAttachNotAvailable = u'\u4e0d\u4f9b\u4f7f\u7528'
apiAttachPendingAuthorization = u'\u5f85\u6388\u6743'
apiAttachRefused = u'\u62d2\u7edd'
apiAttachSuccess = u'\u6210\u529f'
apiAttachUnknown = u'\u4e0d\u8be6'
budDeletedFriend = u'\u5df2\u4ece\u670b\u53cb\u540d\u5355\u4e2d\u5220\u9664'
budFriend = u'\u670b\u53cb'
budNeverBeenFriend = u'\u4ece\u672a\u52a0\u5165\u670b\u53cb\u540d\u5355'
budPendingAuthorization = u'\u5f85\u6388\u6743'
budUnknown = u'\u4e0d\u8be6'
cfrBlockedByRecipient = u'\u901a\u8bdd\u88ab\u63a5\u6536\u65b9\u5c01\u9501'
cfrMiscError = u'\u5176\u5b83\u7c7b\u9519\u8bef'
cfrNoCommonCodec = u'\u65e0\u5e38\u89c1\u7f16\u89e3\u7801\u5668'
cfrNoProxyFound = u'\u627e\u4e0d\u5230\u4ee3\u7406\u670d\u52a1\u5668'
cfrNotAuthorizedByRecipient = u'\u5f53\u524d\u7528\u6237\u672a\u7ecf\u63a5\u6536\u65b9\u6388\u6743'
cfrRecipientNotFriend = u'\u63a5\u6536\u65b9\u4e0d\u662f\u670b\u53cb\u3002'
cfrRemoteDeviceError = u'\u8fdc\u7a0b\u58f0\u97f3\u8bbe\u5907\u9519\u8bef'
cfrSessionTerminated = u'\u4f1a\u8bdd\u7ed3\u675f'
cfrSoundIOError = u'\u97f3\u54cd\u8f93\u5165/\u8f93\u51fa\u9519\u8bef'
cfrSoundRecordingError = u'\u97f3\u54cd\u5f55\u97f3\u9519\u8bef'
cfrUnknown = u'\u4e0d\u8be6'
cfrUserDoesNotExist = u'\u7528\u6237/\u7535\u8bdd\u53f7\u7801\u4e0d\u5b58\u5728'
cfrUserIsOffline = u'\u5979\u6216\u4ed6\u5904\u4e8e\u8131\u673a\u72b6\u6001'
chsAllCalls = u'\u65e7\u7248\u5bf9\u8bdd'
chsDialog = u'\u5bf9\u8bdd'
chsIncomingCalls = u'\u591a\u4eba\u5bf9\u8bdd\u5f85\u63a5\u53d7'
chsLegacyDialog = u'\u65e7\u7248\u5bf9\u8bdd'
chsMissedCalls = u'\u5bf9\u8bdd'
chsMultiNeedAccept = u'\u591a\u4eba\u5bf9\u8bdd\u5f85\u63a5\u53d7'
chsMultiSubscribed = u'\u591a\u4eba\u52a0\u5165'
chsOutgoingCalls = u'\u591a\u4eba\u52a0\u5165'
chsUnknown = u'\u4e0d\u8be6'
chsUnsubscribed = u'\u5df2\u9000\u51fa'
clsBusy = u'\u5fd9'
clsCancelled = u'\u5df2\u53d6\u6d88'
clsEarlyMedia = u'\u6b63\u5728\u64ad\u653e\u65e9\u671f\u4fe1\u53f7\uff08Early Media\uff09'
clsFailed = u'\u5bf9\u4e0d\u8d77\uff0c\u547c\u53eb\u5931\u8d25\uff01'
clsFinished = u'\u5b8c\u6bd5'
clsInProgress = u'\u6b63\u5728\u8fdb\u884c\u901a\u8bdd'
clsLocalHold = u'\u672c\u65b9\u6682\u5019'
clsMissed = u'\u4e2a\u672a\u5e94\u7b54\u547c\u53eb'
clsOnHold = u'\u4fdd\u6301'
clsRefused = u'\u62d2\u7edd'
clsRemoteHold = u'\u5bf9\u65b9\u6682\u5019'
clsRinging = u'\u547c\u53eb'
clsRouting = u'\u6b63\u5728\u63a5\u901a'
clsTransferred = u'\u4e0d\u8be6'
clsTransferring = u'\u4e0d\u8be6'
clsUnknown = u'\u4e0d\u8be6'
clsUnplaced = u'\u4ece\u672a\u62e8\u6253'
clsVoicemailBufferingGreeting = u'\u6b63\u5728\u51c6\u5907\u95ee\u5019\u8bed'
clsVoicemailCancelled = u'\u8bed\u97f3\u7559\u8a00\u5df2\u53d6\u6d88'
clsVoicemailFailed = u'\u8bed\u97f3\u90ae\u4ef6\u5931\u8d25'
clsVoicemailPlayingGreeting = u'\u6b63\u5728\u64ad\u653e\u95ee\u5019\u8bed'
clsVoicemailRecording = u'\u5f55\u5236\u8bed\u97f3\u90ae\u4ef6'
clsVoicemailSent = u'\u8bed\u97f3\u7559\u8a00\u5df2\u53d1\u9001'
clsVoicemailUploading = u'\u6b63\u5728\u4e0a\u8f7d\u8bed\u97f3\u7559\u8a00'
cltIncomingP2P = u'\u62e8\u5165\u5bf9\u7b49\u7535\u8bdd'
cltIncomingPSTN = u'\u62e8\u5165\u7535\u8bdd'
cltOutgoingP2P = u'\u62e8\u51fa\u5bf9\u7b49\u7535\u8bdd'
cltOutgoingPSTN = u'\u62e8\u51fa\u7535\u8bdd'
cltUnknown = u'\u4e0d\u8be6'
cmeAddedMembers = u'\u6240\u6dfb\u6210\u5458'
cmeCreatedChatWith = u'\u66fe\u4e0e\u6b64\u4eba\u804a\u5929'
cmeEmoted = u'\u4e0d\u8be6'
cmeLeft = u'\u79bb\u5f00'
cmeSaid = u'\u5df2\u8bf4\u8fc7'
cmeSawMembers = u'\u770b\u5230\u6210\u5458'
cmeSetTopic = u'\u8bbe\u5b9a\u4e3b\u9898'
cmeUnknown = u'\u4e0d\u8be6'
cmsRead = u'\u5df2\u8bfb\u53d6'
cmsReceived = u'\u5df2\u63a5\u6536'
cmsSending = u'\u6b63\u5728\u53d1\u9001...'
cmsSent = u'\u5df2\u53d1\u9001'
cmsUnknown = u'\u4e0d\u8be6'
conConnecting = u'\u6b63\u5728\u8fde\u63a5'
conOffline = u'\u8131\u673a'
conOnline = u'\u8054\u673a'
conPausing = u'\u6682\u505c\u4e2d'
conUnknown = u'\u4e0d\u8be6'
cusAway = u'\u79bb\u5f00'
cusDoNotDisturb = u'\u8bf7\u52ff\u6253\u6270'
cusInvisible = u'\u9690\u8eab'
cusLoggedOut = u'\u8131\u673a'
cusNotAvailable = u'\u4e0d\u4f9b\u4f7f\u7528'
cusOffline = u'\u8131\u673a'
cusOnline = u'\u8054\u673a'
cusSkypeMe = u'Skype Me'
cusUnknown = u'\u4e0d\u8be6'
cvsBothEnabled = u'\u89c6\u9891\u53d1\u9001\u548c\u63a5\u6536'
cvsNone = u'\u65e0\u89c6\u9891'
cvsReceiveEnabled = u'\u89c6\u9891\u63a5\u6536'
cvsSendEnabled = u'\u89c6\u9891\u53d1\u9001'
cvsUnknown = u''
grpAllFriends = u'\u6240\u6709\u670b\u53cb'
grpAllUsers = u'\u6240\u6709\u7528\u6237'
grpCustomGroup = u'\u81ea\u5b9a\u4e49'
grpOnlineFriends = u'\u8054\u673a\u670b\u53cb'
grpPendingAuthorizationFriends = u'\u5f85\u6388\u6743'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\u6700\u8fd1\u8054\u7cfb\u8fc7\u7684\u7528\u6237'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype\u670b\u53cb'
grpSkypeOutFriends = u'SkypeOut\u670b\u53cb'
grpUngroupedFriends = u'\u672a\u5206\u7ec4\u7684\u670b\u53cb'
grpUnknown = u'\u4e0d\u8be6'
grpUsersAuthorizedByMe = u'\u7ecf\u6211\u6388\u6743'
grpUsersBlockedByMe = u'\u88ab\u6211\u5c01\u9501'
grpUsersWaitingMyAuthorization = u'\u6b63\u7b49\u5f85\u6211\u7684\u6388\u6743'
leaAddDeclined = u'\u6dfb\u52a0\u906d\u62d2'
leaAddedNotAuthorized = u'\u88ab\u6dfb\u52a0\u4eba\u987b\u7ecf\u6388\u6743'
leaAdderNotFriend = u'\u6dfb\u52a0\u4eba\u987b\u4e3a\u670b\u53cb'
leaUnknown = u'\u4e0d\u8be6'
leaUnsubscribe = u'\u5df2\u9000\u51fa'
leaUserIncapable = u'\u7528\u6237\u4e0d\u80fd\u4f7f\u7528'
leaUserNotFound = u'\u7528\u6237\u672a\u627e\u5230'
olsAway = u'\u79bb\u5f00'
olsDoNotDisturb = u'\u8bf7\u52ff\u6253\u6270'
olsNotAvailable = u'\u4e0d\u4f9b\u4f7f\u7528'
olsOffline = u'\u8131\u673a'
olsOnline = u'\u8054\u673a'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'\u4e0d\u8be6'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\u5973'
usexMale = u'\u7537'
usexUnknown = u'\u4e0d\u8be6'
vmrConnectError = u'\u8fde\u63a5\u9519\u8bef'
vmrFileReadError = u'\u6587\u4ef6\u8bfb\u53d6\u9519\u8bef'
vmrFileWriteError = u'\u6587\u4ef6\u5199\u5165\u9519\u8bef'
vmrMiscError = u'\u5176\u5b83\u7c7b\u9519\u8bef'
vmrNoError = u'\u65e0\u9519\u8bef'
vmrNoPrivilege = u'\u65e0\u4f7f\u7528\u8bed\u97f3\u7559\u8a00\u6743\u9650'
vmrNoVoicemail = u'\u4e0d\u5b58\u5728\u8be5\u8bed\u97f3\u7559\u8a00'
vmrPlaybackError = u'\u64ad\u653e\u9519\u8bef'
vmrRecordingError = u'\u5f55\u97f3\u9519\u8bef'
vmrUnknown = u'\u4e0d\u8be6'
vmsBlank = u'\u7a7a\u767d\u7559\u8a00'
vmsBuffering = u'\u6b63\u5728\u7f13\u51b2'
vmsDeleting = u'\u6b63\u5728\u5220\u9664'
vmsDownloading = u'\u6b63\u5728\u4e0b\u8f7d'
vmsFailed = u'\u5931\u8d25'
vmsNotDownloaded = u'\u672a\u4e0b\u8f7d'
vmsPlayed = u'\u5df2\u64ad\u653e\u7559\u8a00'
vmsPlaying = u'\u6b63\u5728\u64ad\u653e'
vmsRecorded = u'\u5df2\u5f55\u97f3\u7559\u8a00'
vmsRecording = u'\u5f55\u5236\u8bed\u97f3\u90ae\u4ef6'
vmsUnknown = u'\u4e0d\u8be6'
vmsUnplayed = u'\u672a\u64ad\u653e\u7684\u7559\u8a00'
vmsUploaded = u'\u4e0a\u8f7d\u5b8c\u6bd5'
vmsUploading = u'\u6b63\u5728\u4e0a\u8f7d'
vmtCustomGreeting = u'\u81ea\u5b9a\u4e49\u95ee\u5019\u8bed'
vmtDefaultGreeting = u'\u9ed8\u8ba4\u95ee\u5019\u8bed'
vmtIncoming = u'\u63a5\u6536\u8bed\u97f3\u90ae\u4ef6'
vmtOutgoing = u'\u5916\u51fa'
vmtUnknown = u'\u4e0d\u8be6'
vssAvailable = u'\u53ef\u4f9b\u4f7f\u7528'
vssNotAvailable = u'\u4e0d\u4f9b\u4f7f\u7528'
vssPaused = u'\u6682\u505c'
vssRejected = u'\u62d2\u7edd\u53d7\u8bdd'
vssRunning = u'\u8fd0\u884c\u4e2d'
vssStarting = u'\u5f00\u59cb'
vssStopping = u'\u505c\u6b62\u4e2d'
vssUnknown = u'\u4e0d\u8be6'
| {
"repo_name": "gastounage/skype4py3",
"path": "Skype4Py3/lang/x1.py",
"copies": "23",
"size": "8466",
"license": "bsd-3-clause",
"hash": 4331082215040959500,
"line_mean": 44.2727272727,
"line_max": 99,
"alpha_frac": 0.7863217576,
"autogenerated": false,
"ratio": 1.834850455136541,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
apiAttachAvailable = u'API \uc0ac\uc6a9\uac00\ub2a5'
apiAttachNotAvailable = u'\uc678\ucd9c \uc911'
apiAttachPendingAuthorization = u'\uc2b9\uc778 \ubcf4\ub958 \uc911'
apiAttachRefused = u'\ud1b5\ud654 \uac70\ubd80'
apiAttachSuccess = u'\uc131\uacf5'
apiAttachUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
budDeletedFriend = u'\uce5c\uad6c\ubaa9\ub85d\uc5d0\uc11c \uc0ad\uc81c\ub428'
budFriend = u'\uce5c\uad6c'
budNeverBeenFriend = u'\uce5c\uad6c\ubaa9\ub85d\uc5d0 \uc785\ub825\ud55c \uc801\uc774 \uc5c6\uc74c'
budPendingAuthorization = u'\uc2b9\uc778 \ubcf4\ub958 \uc911'
budUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cfrBlockedByRecipient = u'\uc218\uc2e0\uc790\uc5d0 \uc758\ud574 \ud1b5\ud654 \ucc28\ub2e8'
cfrMiscError = u'\uae30\ud0c0 \uc624\ub958'
cfrNoCommonCodec = u'\uc77c\ubc18 \ucf54\ub371 \uc5c6\uc74c'
cfrNoProxyFound = u'\ubc1c\uacac\ub41c \ud504\ub85d\uc2dc \uc5c6\uc74c'
cfrNotAuthorizedByRecipient = u'\ud604 \uc0ac\uc6a9\uc790\ub97c \uc218\uc2e0\uc790\uac00 \uc2b9\uc778\ud558\uc9c0 \uc54a\uc558\uc2b5\ub2c8\ub2e4.'
cfrRecipientNotFriend = u'\uc218\uc2e0\uc790\uac00 \uce5c\uad6c\uac00 \uc544\ub2d8'
cfrRemoteDeviceError = u'\uc6d0\uaca9 \uc0ac\uc6b4\ub4dc IO \uc624\ub958'
cfrSessionTerminated = u'\uc138\uc158 \uc885\ub8cc'
cfrSoundIOError = u'\uc0ac\uc6b4\ub4dc I/O \uc624\ub958'
cfrSoundRecordingError = u'\uc0ac\uc6b4\ub4dc \ub179\uc74c \uc624\ub958'
cfrUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cfrUserDoesNotExist = u'\uc0ac\uc6a9\uc790/\uc804\ud654\ubc88\ud638\uac00 \uc874\uc7ac\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4'
cfrUserIsOffline = u'\uc0c1\ub300\ubc29\uc774 \uc624\ud504\ub77c\uc778 \uc0c1\ud0dc\uc785\ub2c8\ub2e4'
chsAllCalls = u'\ub808\uac70\uc2dc \ub2e4\uc774\uc5bc\ub85c\uadf8'
chsDialog = u'\ub2e4\uc774\uc5bc\ub85c\uadf8'
chsIncomingCalls = u'\ub2e4\uc218\uac00 \uc218\ub77d\uc744 \uc694\ud568'
chsLegacyDialog = u'\ub808\uac70\uc2dc \ub2e4\uc774\uc5bc\ub85c\uadf8'
chsMissedCalls = u'\ub2e4\uc774\uc5bc\ub85c\uadf8'
chsMultiNeedAccept = u'\ub2e4\uc218\uac00 \uc218\ub77d\uc744 \uc694\ud568'
chsMultiSubscribed = u'\ub2e4\uc218\uac00 \uac00\uc785\ud568'
chsOutgoingCalls = u'\ub2e4\uc218\uac00 \uac00\uc785\ud568'
chsUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
chsUnsubscribed = u'\ubbf8\uac00\uc785'
clsBusy = u'\ud1b5\ud654 \uc911'
clsCancelled = u'\ucde8\uc18c\ub418\uc5c8\uc74c'
clsEarlyMedia = u'\ucd08\uae30 \ubbf8\ub514\uc5b4(Early Media) \uc7ac\uc0dd\uc911'
clsFailed = u'\uc8c4\uc1a1\ud569\ub2c8\ub2e4. \ud1b5\ud654\uac00 \uc2e4\ud328\ud588\uc2b5\ub2c8\ub2e4!'
clsFinished = u'\uc885\ub8cc'
clsInProgress = u'\ud1b5\ud654 \uc9c4\ud589 \uc911'
clsLocalHold = u'\ud604 \uc0ac\uc6a9\uc790\uac00 \ud1b5\ud654\ubcf4\ub958\ud568'
clsMissed = u'\ud1b5\ud654 \ubabb\ubc1b\uc74c'
clsOnHold = u'\ubcf4\ub958'
clsRefused = u'\ud1b5\ud654 \uac70\ubd80'
clsRemoteHold = u'\uc6d0\uaca9 \ubcf4\ub958\ud568'
clsRinging = u'\uc804\ud654\uac78\uae30'
clsRouting = u'\ub77c\uc6b0\ud305'
clsTransferred = u'\uc54c \uc218 \uc5c6\uc74c'
clsTransferring = u'\uc54c \uc218 \uc5c6\uc74c'
clsUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
clsUnplaced = u'\uc804\ud654\uac00 \uac78\ub9ac\uc9c0 \uc54a\uc74c'
clsVoicemailBufferingGreeting = u'\uc778\uc0ac\ub9d0 \ubc84\ud37c\ub9c1 \uc911'
clsVoicemailCancelled = u'\ubcf4\uc774\uc2a4\uba54\uc77c\uc774 \ucde8\uc18c\ub418\uc5c8\uc2b5\ub2c8\ub2e4'
clsVoicemailFailed = u'\ubcf4\uc774\uc2a4\uba54\uc77c \uc2e4\ud328'
clsVoicemailPlayingGreeting = u'\uc778\uc0ac\ub9d0 \ud50c\ub808\uc774 \uc911'
clsVoicemailRecording = u'\ubcf4\uc774\uc2a4\uba54\uc77c \ub179\uc74c\uc911'
clsVoicemailSent = u'\ubcf4\uc774\uc2a4\uba54\uc77c\uc774 \uc804\uc1a1\ub418\uc5c8\uc2b5\ub2c8\ub2e4'
clsVoicemailUploading = u'\ubcf4\uc774\uc2a4\uba54\uc77c \uc5c5\ub85c\ub4dc \uc911'
cltIncomingP2P = u'\uc218\uc2e0 \ud53c\uc5b4-\ud22c-\ud53c\uc5b4 \ud1b5\ud654'
cltIncomingPSTN = u'\uc218\uc2e0 \uc804\ud654\ud1b5\ud654'
cltOutgoingP2P = u'\ubc1c\uc2e0 \ud53c\uc5b4-\ud22c-\ud53c\uc5b4 \ud1b5\ud654'
cltOutgoingPSTN = u'\ubc1c\uc2e0 \uc804\ud654\ud1b5\ud654'
cltUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cmeAddedMembers = u'\ud68c\uc6d0\uc744 \ucd94\uac00\ud588\uc74c'
cmeCreatedChatWith = u'\ub2e4\uc74c \uc0c1\ub300\uc640 \ucc44\ud305 \ud615\uc131'
cmeEmoted = u'\uc54c \uc218 \uc5c6\uc74c'
cmeLeft = u'\ub5a0\ub0a8'
cmeSaid = u'\ub9d0\ud55c \ub0b4\uc6a9'
cmeSawMembers = u'\ud68c\uc6d0\uc744 \ubcf4\uc558\uc74c'
cmeSetTopic = u'\uc8fc\uc81c \uc124\uc815'
cmeUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cmsRead = u'\uc77d\uc74c'
cmsReceived = u'\uc218\uc2e0'
cmsSending = u'\ubcf4\ub0b4\ub294 \uc911...'
cmsSent = u'\uc804\uc1a1\uc644\ub8cc'
cmsUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
conConnecting = u'\uc5f0\uacb0 \uc911'
conOffline = u'\uc624\ud504\ub77c\uc778'
conOnline = u'\uc628\ub77c\uc778'
conPausing = u'\uc77c\uc2dc \uc911\uc9c0'
conUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cusAway = u'\uc790\ub9ac \ube44\uc6c0'
cusDoNotDisturb = u'\ub2e4\ub978 \uc6a9\ubb34\uc911'
cusInvisible = u'\ud22c\uba85\uc778\uac04'
cusLoggedOut = u'\uc624\ud504\ub77c\uc778'
cusNotAvailable = u'\uc678\ucd9c \uc911'
cusOffline = u'\uc624\ud504\ub77c\uc778'
cusOnline = u'\uc628\ub77c\uc778'
cusSkypeMe = u'Skype Me'
cusUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
cvsBothEnabled = u'\ube44\ub514\uc624 \uc804\uc1a1 \ubc0f \uc218\uc2e0'
cvsNone = u'\ube44\ub514\uc624 \uc5c6\uc74c'
cvsReceiveEnabled = u'\ube44\ub514\uc624 \uc218\uc2e0'
cvsSendEnabled = u'\ube44\ub514\uc624 \uc804\uc1a1'
cvsUnknown = u''
grpAllFriends = u'\ubaa8\ub4e0 \uce5c\uad6c'
grpAllUsers = u'\ubaa8\ub4e0 \uc0ac\uc6a9\uc790'
grpCustomGroup = u'\ub9de\ucda4'
grpOnlineFriends = u'\uc628\ub77c\uc778 \uce5c\uad6c\ub4e4'
grpPendingAuthorizationFriends = u'\uc2b9\uc778 \ubcf4\ub958 \uc911'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\ucd5c\uadfc\uc5d0 \uc5f0\ub77d\ud55c \uc0ac\uc6a9\uc790'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype \uce5c\uad6c\ub4e4'
grpSkypeOutFriends = u'SkypeOut \uce5c\uad6c\ub4e4'
grpUngroupedFriends = u'\uadf8\ub8f9\uc5d0 \uc18d\ud558\uc9c0 \uc54a\uc740 \uce5c\uad6c\ub4e4'
grpUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
grpUsersAuthorizedByMe = u'\ub0b4\uac00 \uc2b9\uc778\ud55c \uc0ac\uc6a9\uc790'
grpUsersBlockedByMe = u'\ub0b4\uac00 \ucc28\ub2e8\ud55c \uc0ac\uc6a9\uc790'
grpUsersWaitingMyAuthorization = u'\ub0b4 \uc2b9\uc778\uc744 \uae30\ub2e4\ub9ac\ub294 \uc0ac\uc6a9\uc790'
leaAddDeclined = u'\ucd94\uac00\uac00 \uac70\ubd80\ub428'
leaAddedNotAuthorized = u'\ucd94\uac00\ub418\ub294 \ub300\uc0c1\uc774 \ubc18\ub4dc\uc2dc \uc2b9\uc778\ub418\uc5b4\uc57c \ud568'
leaAdderNotFriend = u'\ucd94\uac00\ud558\ub294 \uc0ac\ub78c\uc774 \ubc18\ub4dc\uc2dc \uce5c\uad6c\uc5ec\uc57c \ud568'
leaUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
leaUnsubscribe = u'\ubbf8\uac00\uc785'
leaUserIncapable = u'\uc0ac\uc6a9\uc790 \uc0ac\uc6a9\ubd88\ub2a5'
leaUserNotFound = u'\uc0ac\uc6a9\uc790\ub97c \ucc3e\uc9c0 \ubabb\ud568'
olsAway = u'\uc790\ub9ac \ube44\uc6c0'
olsDoNotDisturb = u'\ub2e4\ub978 \uc6a9\ubb34\uc911'
olsNotAvailable = u'\uc678\ucd9c \uc911'
olsOffline = u'\uc624\ud504\ub77c\uc778'
olsOnline = u'\uc628\ub77c\uc778'
olsSkypeMe = u'Skype Me'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\uc5ec'
usexMale = u'\ub0a8'
usexUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
vmrConnectError = u'\uc5f0\uacb0 \uc624\ub958'
vmrFileReadError = u'\ud30c\uc77c \uc77d\uae30 \uc624\ub958'
vmrFileWriteError = u'\ud30c\uc77c \uc4f0\uae30 \uc624\ub958'
vmrMiscError = u'\uae30\ud0c0 \uc624\ub958'
vmrNoError = u'\uc624\ub958 \uc5c6\uc74c'
vmrNoPrivilege = u'\ubcf4\uc774\uc2a4\uba54\uc77c \uc6b0\uc120\uad8c \uc5c6\uc74c'
vmrNoVoicemail = u'\uadf8\ub7ec\ud55c \ubcf4\uc774\uc2a4\uba54\uc77c\uc774 \uc5c6\uc74c'
vmrPlaybackError = u'\uc7ac\uc0dd \uc624\ub958'
vmrRecordingError = u'\ub179\uc74c \uc624\ub958'
vmrUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
vmsBlank = u'\uba54\uc2dc\uc9c0 \uc5c6\uc74c'
vmsBuffering = u'\ubc84\ud37c\ub9c1'
vmsDeleting = u'\uc0ad\uc81c \uc911'
vmsDownloading = u'\ub2e4\uc6b4\ub85c\ub4dc \uc911'
vmsFailed = u'\uc2e4\ud328\ud568'
vmsNotDownloaded = u'\ub2e4\uc6b4\ub85c\ub4dc \ub418\uc9c0 \uc54a\uc74c'
vmsPlayed = u'\ud50c\ub808\uc774 \ud568'
vmsPlaying = u'\ud50c\ub808\uc774 \uc911'
vmsRecorded = u'\ub179\uc74c\ub428'
vmsRecording = u'\ubcf4\uc774\uc2a4\uba54\uc77c \ub179\uc74c\uc911'
vmsUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
vmsUnplayed = u'\ud50c\ub808\uc774 \uc548\ub428'
vmsUploaded = u'\uc5c5\ub85c\ub4dc\ub428'
vmsUploading = u'\uc5c5\ub85c\ub4dc\uc911'
vmtCustomGreeting = u'\ub9de\ucda4 \uc778\uc0ac\ub9d0'
vmtDefaultGreeting = u'\uc9c0\uc815 \uc778\uc0ac\ub9d0'
vmtIncoming = u'\ubc1b\uc740 \ubcf4\uc774\uc2a4\uba54\uc77c'
vmtOutgoing = u'\ubc1c\uc2e0'
vmtUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
vssAvailable = u'\uc0ac\uc6a9\uac00\ub2a5'
vssNotAvailable = u'\uc678\ucd9c \uc911'
vssPaused = u'\uc77c\uc2dc\uc815\uc9c0'
vssRejected = u'\uac70\ubd80\ub428'
vssRunning = u'\uc791\ub3d9 \uc911'
vssStarting = u'\uc2dc\uc791'
vssStopping = u'\uc815\uc9c0 \uc911'
vssUnknown = u'\uc54c \uc218 \uc5c6\uc74c'
| {
"repo_name": "aodag/skype4py",
"path": "Skype4Py/lang/ko.py",
"copies": "23",
"size": "9973",
"license": "bsd-3-clause",
"hash": -8338516115995871000,
"line_mean": 52.3315508021,
"line_max": 146,
"alpha_frac": 0.7761957285,
"autogenerated": false,
"ratio": 2.0042202572347265,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001099247200951574,
"num_lines": 187
} |
apiAttachAvailable = u'\u0414\u043e\u0441\u0442\u044a\u043f\u0435\u043d \u0447\u0440\u0435\u0437 API'
apiAttachNotAvailable = u'\u041d\u0435\u0434\u043e\u0441\u0442\u044a\u043f\u0435\u043d'
apiAttachPendingAuthorization = u'\u0427\u0430\u043a\u0430 \u0441\u0435 \u043e\u0442\u043e\u0440\u0438\u0437\u0430\u0446\u0438\u044f'
apiAttachRefused = u'\u041e\u0442\u043a\u0430\u0437\u0430\u043d\u0430'
apiAttachSuccess = u'\u0423\u0441\u043f\u0435\u0445'
apiAttachUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
budDeletedFriend = u'\u0418\u0437\u0442\u0440\u0438\u0442 \u043e\u0442 \u0421\u043f\u0438\u0441\u044a\u043a\u0430 \u0441 \u043f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
budFriend = u'\u041f\u0440\u0438\u044f\u0442\u0435\u043b'
budNeverBeenFriend = u'\u041d\u0438\u043a\u043e\u0433\u0430 \u043d\u0435 \u0435 \u0431\u0438\u043b \u0432 \u0421\u043f\u0438\u0441\u044a\u043a\u0430 \u0441 \u043f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
budPendingAuthorization = u'\u0427\u0430\u043a\u0430 \u0441\u0435 \u043e\u0442\u043e\u0440\u0438\u0437\u0430\u0446\u0438\u044f'
budUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cfrBlockedByRecipient = u'\u041e\u0431\u0430\u0436\u0434\u0430\u043d\u0435\u0442\u043e \u0435 \u0431\u043b\u043e\u043a\u0438\u0440\u0430\u043d\u043e \u043e\u0442 \u043f\u0440\u0438\u0435\u043c\u0430\u0449\u0438\u044f'
cfrMiscError = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430 \u0433\u0440\u0435\u0448\u043a\u0430'
cfrNoCommonCodec = u'\u041d\u044f\u043c\u0430 \u043f\u043e\u0434\u0445\u043e\u0434\u044f\u0449 \u043a\u043e\u0434\u0435\u043a'
cfrNoProxyFound = u'\u041d\u044f\u043c\u0430 \u043d\u0430\u043c\u0435\u0440\u0435\u043d\u0438 \u043f\u0440\u043e\u043a\u0441\u0438 \u0441\u044a\u0440\u0432\u044a\u0440\u0438'
cfrNotAuthorizedByRecipient = u'\u0422\u043e\u0437\u0438 \u043f\u043e\u0442\u0440\u0435\u0431\u0438\u0442\u0435\u043b \u043d\u0435 \u0435 \u043e\u0442\u043e\u0440\u0438\u0437\u0438\u0440\u0430\u043d \u043e\u0442 \u043f\u0440\u0438\u0435\u043c\u0430\u0449\u0438\u044f'
cfrRecipientNotFriend = u'\u041f\u0440\u0438\u0435\u043c\u0430\u0449\u0438\u044f\u0442 \u043d\u0435 \u0435 \u043f\u0440\u0438\u044f\u0442\u0435\u043b'
cfrRemoteDeviceError = u'\u041f\u0440\u043e\u0431\u043b\u0435\u043c \u0441 \u043e\u0442\u0434\u0430\u043b\u0435\u0447\u0435\u043d\u043e \u0437\u0432\u0443\u043a\u043e\u0432\u043e \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u043e'
cfrSessionTerminated = u'\u041f\u0440\u0435\u043a\u0440\u0430\u0442\u0435\u043d\u0430 \u0441\u0435\u0441\u0438\u044f'
cfrSoundIOError = u'\u0412\u0445\u043e\u0434\u043d\u043e/\u0438\u0437\u0445\u043e\u0434\u043d\u0430 \u0433\u0440\u0435\u0448\u043a\u0430 \u0441\u044a\u0441 \u0437\u0432\u0443\u043a\u0430'
cfrSoundRecordingError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u0437\u0430\u043f\u0438\u0441\u0430 \u043d\u0430 \u0437\u0432\u0443\u043a'
cfrUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cfrUserDoesNotExist = u'\u0410\u0431\u043e\u043d\u0430\u0442\u044a\u0442/\u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u0438\u044f\u0442 \u043d\u043e\u043c\u0435\u0440 \u043d\u0435 \u0441\u044a\u0449\u0435\u0441\u0442\u0432\u0443\u0432\u0430'
cfrUserIsOffline = u'\u0422\u043e\u0439/\u0442\u044f \u0435 \u0438\u0437\u0432\u044a\u043d \u043b\u0438\u043d\u0438\u044f.'
chsAllCalls = u'\u0421\u0442\u0430\u0440 \u0434\u0438\u0430\u043b\u043e\u0433'
chsDialog = u'\u0414\u0438\u0430\u043b\u043e\u0433'
chsIncomingCalls = u'\u041c\u043d\u043e\u0437\u0438\u043d\u0430 \u0442\u0440\u044f\u0431\u0432\u0430 \u0434\u0430 \u043f\u0440\u0438\u0435\u043c\u0430\u0442'
chsLegacyDialog = u'\u0421\u0442\u0430\u0440 \u0434\u0438\u0430\u043b\u043e\u0433'
chsMissedCalls = u'\u0414\u0438\u0430\u043b\u043e\u0433'
chsMultiNeedAccept = u'\u041c\u043d\u043e\u0437\u0438\u043d\u0430 \u0442\u0440\u044f\u0431\u0432\u0430 \u0434\u0430 \u043f\u0440\u0438\u0435\u043c\u0430\u0442'
chsMultiSubscribed = u'\u041c\u043d\u043e\u0437\u0438\u043d\u0430 \u0441\u0430 \u0430\u0431\u043e\u043d\u0430\u0442\u0438'
chsOutgoingCalls = u'\u041c\u043d\u043e\u0437\u0438\u043d\u0430 \u0441\u0430 \u0430\u0431\u043e\u043d\u0430\u0442\u0438'
chsUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
chsUnsubscribed = u'\u041d\u0435 \u0435 \u0430\u0431\u043e\u043d\u0430\u0442'
clsBusy = u'\u0417\u0430\u0435\u0442\u043e'
clsCancelled = u'\u041f\u0440\u0435\u043a\u0440\u0430\u0442\u0435\u043d'
clsEarlyMedia = u'\u0412\u044a\u0437\u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0436\u0434\u0430\u043d\u0435 \u043d\u0430 \u043f\u0440\u0435\u0434\u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u0435\u043d \u0448\u0443\u043c (Early Media)'
clsFailed = u'\u0417\u0430 \u0441\u044a\u0436\u0430\u043b\u0435\u043d\u0438\u0435, \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440\u044a\u0442 \u0441\u0435 \u0440\u0430\u0437\u043f\u0430\u0434\u043d\u0430!'
clsFinished = u'\u041f\u0440\u0438\u043a\u043b\u044e\u0447\u0435\u043d'
clsInProgress = u'\u0412 \u043f\u0440\u043e\u0446\u0435\u0441 \u043d\u0430 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440'
clsLocalHold = u'\u041d\u0430 \u0438\u0437\u0447\u0430\u043a\u0432\u0430\u043d\u0435 \u043e\u0442 \u0432\u0430\u0448\u0430 \u0441\u0442\u0440\u0430\u043d\u0430'
clsMissed = u'\u043f\u0440\u043e\u043f\u0443\u0441\u043d\u0430\u0442 \u0440\u0430\u0437\u0433\u043e\u0432\u043e\u0440'
clsOnHold = u'\u0417\u0430\u0434\u044a\u0440\u0436\u0430\u043d\u0435'
clsRefused = u'\u041e\u0442\u043a\u0430\u0437\u0430\u043d\u0430'
clsRemoteHold = u'\u041d\u0430 \u0438\u0437\u0447\u0430\u043a\u0432\u0430\u043d\u0435 \u043e\u0442 \u043e\u0442\u0441\u0440\u0435\u0449\u043d\u0430\u0442\u0430 \u0441\u0442\u0440\u0430\u043d\u0430'
clsRinging = u'\u0433\u043e\u0432\u043e\u0440\u0438\u0442\u0435'
clsRouting = u'\u041f\u0440\u0435\u043d\u0430\u0441\u043e\u0447\u0432\u0430\u043d\u0435'
clsTransferred = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
clsTransferring = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
clsUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
clsUnplaced = u'\u041d\u0438\u043a\u043e\u0433\u0430 \u043d\u0435 \u0435 \u043f\u0440\u043e\u0432\u0435\u0436\u0434\u0430\u043d'
clsVoicemailBufferingGreeting = u'\u0411\u0443\u0444\u0435\u0440\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 \u043f\u043e\u0437\u0434\u0440\u0430\u0432\u0430'
clsVoicemailCancelled = u'\u0413\u043b\u0430\u0441\u043e\u0432\u0430\u0442\u0430 \u043f\u043e\u0449\u0430 \u043e\u0442\u043c\u0435\u043d\u0435\u043d\u0430'
clsVoicemailFailed = u'\u041f\u0440\u043e\u0432\u0430\u043b\u0435\u043d\u043e \u0433\u043b\u0430\u0441\u043e\u0432\u043e \u0441\u044a\u043e\u0431\u0449\u0435\u043d\u0438\u0435'
clsVoicemailPlayingGreeting = u'\u0412\u044a\u0437\u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0436\u0434\u0430\u043d\u0435 \u043d\u0430 \u043f\u043e\u0437\u0434\u0440\u0430\u0432\u0430'
clsVoicemailRecording = u'\u0417\u0430\u043f\u0438\u0441 \u043d\u0430 \u0433\u043b\u0430\u0441\u043e\u0432\u043e \u0441\u044a\u043e\u0431\u0449\u0435\u043d\u0438\u0435'
clsVoicemailSent = u'\u0413\u043b\u0430\u0441\u043e\u0432\u0430\u0442\u0430 \u043f\u043e\u0449\u0430 \u0438\u0437\u043f\u0440\u0430\u0442\u0435\u043d\u0430'
clsVoicemailUploading = u'\u0413\u043b\u0430\u0441\u043e\u0432\u0430\u0442\u0430 \u043f\u043e\u0449\u0430 \u0441\u0435 \u043a\u0430\u0447\u0432\u0430'
cltIncomingP2P = u'\u0412\u0445\u043e\u0434\u044f\u0449\u043e Peer-to-Peer \u043e\u0431\u0430\u0436\u0434\u0430\u043d\u0435'
cltIncomingPSTN = u'\u0412\u0445\u043e\u0434\u044f\u0449\u043e \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u043e \u043e\u0431\u0430\u0436\u0434\u0430\u043d\u0435'
cltOutgoingP2P = u'\u0418\u0437\u0445\u043e\u0434\u044f\u0449\u043e Peer-to-Peer \u043e\u0431\u0430\u0436\u0434\u0430\u043d\u0435'
cltOutgoingPSTN = u'\u0418\u0437\u0445\u043e\u0434\u044f\u0449\u043e \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u043d\u043e \u043e\u0431\u0430\u0436\u0434\u0430\u043d\u0435'
cltUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cmeAddedMembers = u'\u0414\u043e\u0431\u0430\u0432\u0438 \u0447\u043b\u0435\u043d\u043e\u0432\u0435'
cmeCreatedChatWith = u'\u0421\u044a\u0437\u0434\u0430\u0434\u0435 \u0447\u0430\u0442 \u0441\u044a\u0441'
cmeEmoted = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cmeLeft = u'\u041d\u0430\u043f\u0443\u0441\u043d\u0430'
cmeSaid = u'\u041a\u0430\u0437\u0430'
cmeSawMembers = u'\u0412\u0438\u0434\u044f \u0447\u043b\u0435\u043d\u043e\u0432\u0435'
cmeSetTopic = u'\u0417\u0430\u0434\u0430\u0439 \u0442\u0435\u043c\u0430'
cmeUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cmsRead = u'\u041f\u0440\u043e\u0447\u0435\u0442\u0435\u043d\u043e'
cmsReceived = u'\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043e'
cmsSending = u'\u0418\u0437\u043f\u0440\u0430\u0449\u0430\u043d\u0435...'
cmsSent = u'\u041f\u0440\u0430\u0442\u0435\u043d\u0430'
cmsUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
conConnecting = u'\u0412 \u043f\u0440\u043e\u0446\u0435\u0441 \u043d\u0430 \u0441\u0432\u044a\u0440\u0437\u0432\u0430\u043d\u0435'
conOffline = u'\u0418\u0437\u0432\u044a\u043d \u043b\u0438\u043d\u0438\u044f'
conOnline = u'\u041d\u0430 \u043b\u0438\u043d\u0438\u044f'
conPausing = u'\u041f\u0430\u0443\u0437\u0430'
conUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cusAway = u'\u041e\u0442\u0441\u044a\u0441\u0442\u0432\u0430\u0449'
cusDoNotDisturb = u'\u041e\u0442\u043f\u043e\u0447\u0438\u0432\u0430\u0449'
cusInvisible = u'\u0418\u043d\u043a\u043e\u0433\u043d\u0438\u0442\u043e'
cusLoggedOut = u'\u0418\u0437\u0432\u044a\u043d \u043b\u0438\u043d\u0438\u044f'
cusNotAvailable = u'\u041d\u0435\u0434\u043e\u0441\u0442\u044a\u043f\u0435\u043d'
cusOffline = u'\u0418\u0437\u0432\u044a\u043d \u043b\u0438\u043d\u0438\u044f'
cusOnline = u'\u041d\u0430 \u043b\u0438\u043d\u0438\u044f'
cusSkypeMe = u'\u0421\u043a\u0430\u0439\u043f\u0432\u0430\u0449'
cusUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
cvsBothEnabled = u'\u0418\u0437\u043f\u0440\u0430\u0449\u0430\u043d\u0435 \u0438 \u043f\u043e\u043b\u0443\u0447\u0430\u0432\u0430\u043d\u0435 \u043d\u0430 \u0432\u0438\u0434\u0435\u043e'
cvsNone = u'\u041d\u044f\u043c\u0430 \u0432\u0438\u0434\u0435\u043e'
cvsReceiveEnabled = u'\u041f\u043e\u043b\u0443\u0447\u0430\u0432\u0430\u043d\u0435 \u043d\u0430 \u0432\u0438\u0434\u0435\u043e'
cvsSendEnabled = u'\u0418\u0437\u043f\u0440\u0430\u0449\u0430\u043d\u0435 \u043d\u0430 \u0432\u0438\u0434\u0435\u043e'
cvsUnknown = u''
grpAllFriends = u'\u0412\u0441\u0438\u0447\u043a\u0438 \u041f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
grpAllUsers = u'\u0412\u0441\u0438\u0447\u043a\u0438 \u0430\u0431\u043e\u043d\u0430\u0442\u0438'
grpCustomGroup = u'\u041f\u043e\u0442\u0440\u0435\u0431\u0438\u0442\u0435\u043b\u0441\u043a\u0430'
grpOnlineFriends = u'\u041f\u0440\u0438\u044f\u0442\u0435\u043b\u0438 \u043e\u043d\u043b\u0430\u0439\u043d'
grpPendingAuthorizationFriends = u'\u0427\u0430\u043a\u0430 \u0441\u0435 \u043e\u0442\u043e\u0440\u0438\u0437\u0430\u0446\u0438\u044f'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'\u0410\u0431\u043e\u043d\u0430\u0442\u0438, \u0441 \u043a\u043e\u0438\u0442\u043e \u0441\u043a\u043e\u0440\u043e \u0435 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0435\u043d\u0430 \u0432\u0440\u044a\u0437\u043a\u0430'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Skype \u041f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
grpSkypeOutFriends = u'SkypeOut \u041f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
grpUngroupedFriends = u'\u041d\u0435\u0433\u0440\u0443\u043f\u0438\u0440\u0430\u043d\u0438 \u041f\u0440\u0438\u044f\u0442\u0435\u043b\u0438'
grpUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
grpUsersAuthorizedByMe = u'\u041e\u0442\u043e\u0440\u0438\u0437\u0438\u0440\u0430\u043d\u0438 \u043e\u0442 \u043c\u0435\u043d'
grpUsersBlockedByMe = u'\u0411\u043b\u043e\u043a\u0438\u0440\u0430\u043d\u0438 \u043e\u0442 \u043c\u0435\u043d'
grpUsersWaitingMyAuthorization = u'\u0427\u0430\u043a\u0430\u0449\u0438 \u043c\u043e\u044f\u0442\u0430 \u043e\u0442\u043e\u0440\u0438\u0437\u0430\u0446\u0438\u044f'
leaAddDeclined = u'\u0414\u043e\u0431\u0430\u0432\u044f\u043d\u0435\u0442\u043e \u043e\u0442\u043a\u0430\u0437\u0430\u043d\u043e'
leaAddedNotAuthorized = u'\u0414\u043e\u0431\u044f\u0432\u0430\u043d\u0438\u044f\u0442 \u0442\u0440\u044f\u0431\u0432\u0430 \u0434\u0430 \u0435 \u043e\u0442\u043e\u0440\u0438\u0437\u0438\u0440\u0430\u043d'
leaAdderNotFriend = u'\u0414\u043e\u0431\u0430\u0432\u044f\u0449\u0438\u044f\u0442 \u0442\u0440\u044f\u0431\u0432\u0430 \u0434\u0430 \u0435 \u041f\u0440\u0438\u044f\u0442\u0435\u043b'
leaUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
leaUnsubscribe = u'\u041d\u0435 \u0435 \u0430\u0431\u043e\u043d\u0430\u0442'
leaUserIncapable = u'\u0410\u0431\u043e\u043d\u0430\u0442\u044a\u0442 \u043d\u044f\u043c\u0430 \u0432\u044a\u0437\u043c\u043e\u0436\u043d\u043e\u0441\u0442 \u0437\u0430 \u0432\u0440\u044a\u0437\u043a\u0430'
leaUserNotFound = u'\u0410\u0431\u043e\u043d\u0430\u0442\u044a\u0442 \u043d\u0435 \u0435 \u043d\u0430\u043c\u0435\u0440\u0435\u043d'
olsAway = u'\u041e\u0442\u0441\u044a\u0441\u0442\u0432\u0430\u0449'
olsDoNotDisturb = u'\u041e\u0442\u043f\u043e\u0447\u0438\u0432\u0430\u0449'
olsNotAvailable = u'\u041d\u0435\u0434\u043e\u0441\u0442\u044a\u043f\u0435\u043d'
olsOffline = u'\u0418\u0437\u0432\u044a\u043d \u043b\u0438\u043d\u0438\u044f'
olsOnline = u'\u041d\u0430 \u043b\u0438\u043d\u0438\u044f'
olsSkypeMe = u'\u0421\u043a\u0430\u0439\u043f\u0432\u0430\u0449'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'\u0436\u0435\u043d\u0441\u043a\u0438'
usexMale = u'\u043c\u044a\u0436\u043a\u0438'
usexUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
vmrConnectError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u0441\u0432\u044a\u0440\u0437\u0432\u0430\u043d\u0435\u0442\u043e'
vmrFileReadError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u0447\u0435\u0442\u0435\u043d\u0435 \u043d\u0430 \u0444\u0430\u0439\u043b\u0430'
vmrFileWriteError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u0437\u0430\u043f\u0438\u0441 \u043d\u0430 \u0444\u0430\u0439\u043b\u0430'
vmrMiscError = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430 \u0433\u0440\u0435\u0448\u043a\u0430'
vmrNoError = u'\u041d\u044f\u043c\u0430 \u0433\u0440\u0435\u0448\u043a\u0430'
vmrNoPrivilege = u'\u041d\u044f\u043c\u0430 \u043f\u0440\u0438\u0432\u0438\u043b\u0435\u0433\u0438\u044f \u0437\u0430 \u0433\u043b\u0430\u0441\u043e\u0432\u0430 \u043f\u043e\u0449\u0430'
vmrNoVoicemail = u'\u041d\u044f\u043c\u0430 \u0442\u0430\u043a\u0430\u0432\u0430 \u0433\u043b\u0430\u0441\u043e\u0432\u0430 \u043f\u043e\u0449\u0430'
vmrPlaybackError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u043f\u0440\u043e\u0441\u043b\u0443\u0448\u0432\u0430\u043d\u0435'
vmrRecordingError = u'\u0413\u0440\u0435\u0448\u043a\u0430 \u043f\u0440\u0438 \u0437\u0430\u043f\u0438\u0441'
vmrUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
vmsBlank = u'\u041f\u0440\u0430\u0437\u043d\u0430'
vmsBuffering = u'\u0411\u0443\u0444\u0435\u0440\u0438\u0440\u0430\u043d\u0435'
vmsDeleting = u'\u0418\u0437\u0442\u0440\u0438\u0432\u0430\u043d\u0435'
vmsDownloading = u'\u0421\u0432\u0430\u043b\u044f\u043d\u0435'
vmsFailed = u'\u041d\u0435\u0443\u0441\u043f\u0435\u0448\u043d\u0430'
vmsNotDownloaded = u'\u041d\u0435 \u0435 \u0441\u0432\u0430\u043b\u0435\u043d\u0430'
vmsPlayed = u'\u041f\u0440\u043e\u0441\u043b\u0443\u0448\u0430\u043d\u0430'
vmsPlaying = u'\u041f\u0440\u043e\u0441\u043b\u0443\u0448\u0432\u0430\u043d\u0435'
vmsRecorded = u'\u0417\u0430\u043f\u0438\u0441\u0430\u043d\u0430'
vmsRecording = u'\u0417\u0430\u043f\u0438\u0441 \u043d\u0430 \u0433\u043b\u0430\u0441\u043e\u0432\u043e \u0441\u044a\u043e\u0431\u0449\u0435\u043d\u0438\u0435'
vmsUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
vmsUnplayed = u'\u041d\u0435 \u0435 \u043f\u0440\u043e\u0441\u043b\u0443\u0448\u0430\u043d\u0430'
vmsUploaded = u'\u041a\u0430\u0447\u0435\u043d\u0430'
vmsUploading = u'\u041a\u0430\u0447\u0432\u0430\u043d\u0435'
vmtCustomGreeting = u'\u041f\u0435\u0440\u0441\u043e\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u0430\u043d \u043f\u043e\u0437\u0434\u0440\u0430\u0432'
vmtDefaultGreeting = u'\u041f\u043e\u0437\u0434\u0440\u0430\u0432 \u043f\u043e \u043f\u043e\u0434\u0440\u0430\u0437\u0431\u0438\u0440\u0430\u043d\u0435'
vmtIncoming = u'\u0432\u0445\u043e\u0434\u044f\u0449\u043e \u0433\u043b\u0430\u0441\u043e\u0432\u043e \u0441\u044a\u043e\u0431\u0449\u0435\u043d\u0438\u0435'
vmtOutgoing = u'\u0418\u0437\u0445\u043e\u0434\u044f\u0449\u0430'
vmtUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
vssAvailable = u'\u0414\u043e\u0441\u0442\u044a\u043f\u0435\u043d'
vssNotAvailable = u'\u041d\u0435\u0434\u043e\u0441\u0442\u044a\u043f\u0435\u043d'
vssPaused = u'\u0412 \u043f\u0430\u0443\u0437\u0430'
vssRejected = u'\u041e\u0442\u0445\u0432\u044a\u0440\u043b\u0435\u043d\u043e'
vssRunning = u'\u041f\u0440\u043e\u0442\u0438\u0447\u0430'
vssStarting = u'\u0417\u0430\u043f\u043e\u0447\u0432\u0430'
vssStopping = u'\u041f\u0440\u0438\u043a\u043b\u044e\u0447\u0432\u0430'
vssUnknown = u'\u041d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u0430'
| {
"repo_name": "neurodebian/htcondor",
"path": "src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/Languages/bg.py",
"copies": "10",
"size": "18721",
"license": "apache-2.0",
"hash": 7167740046204979000,
"line_mean": 98.1122994652,
"line_max": 267,
"alpha_frac": 0.7939212649,
"autogenerated": false,
"ratio": 1.9505105230256303,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.7744431787925631,
"avg_score": null,
"num_lines": null
} |
"""API Blueprint
This is a subclass of Flask's Blueprint
It provides added features:
- Decorators to specify Marshmallow schema for view functions I/O
- API documentation registration
Documentation process works in several steps:
- At import time
- When a MethodView or a view function is decorated, relevant information
is automatically added to the object's ``_apidoc`` attribute.
- The ``Blueprint.doc`` decorator stores additional information in a separate
``_api_manual_doc``. It allows the user to specify documentation
information that flask-rest-api can not - or does not yet - infer from the
code.
- The ``Blueprint.route`` decorator registers the endpoint in the Blueprint
and gathers all information about the endpoint in
``Blueprint._auto_docs[endpoint]`` and
``Blueprint._manual_docs[endpoint]``.
- At initialization time
- Schema instances are replaced either by their reference in the `schemas`
section of the spec if applicable, otherwise by their json representation.
- Automatic documentation is adapted to OpenAPI version and deep-merged with
manual documentation.
- Endpoints documentation is registered in the APISpec object.
"""
from collections import OrderedDict
from functools import wraps
from copy import deepcopy
from flask import Blueprint as FlaskBlueprint
from flask.views import MethodViewType
from .utils import deepupdate, load_info_from_docstring
from .arguments import ArgumentsMixin
from .response import ResponseMixin
from .pagination import PaginationMixin
from .etag import EtagMixin
from .spec import (
DEFAULT_REQUEST_BODY_CONTENT_TYPE, DEFAULT_RESPONSE_CONTENT_TYPE)
class Blueprint(
FlaskBlueprint,
ArgumentsMixin, ResponseMixin, PaginationMixin, EtagMixin):
"""Blueprint that registers info in API documentation"""
# Order in which the methods are presented in the spec
HTTP_METHODS = ['OPTIONS', 'HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE']
DEFAULT_LOCATION_CONTENT_TYPE_MAPPING = {
"json": "application/json",
"form": "application/x-www-form-urlencoded",
"files": "multipart/form-data",
}
DOCSTRING_INFO_DELIMITER = "---"
def __init__(self, *args, **kwargs):
self.description = kwargs.pop('description', '')
super().__init__(*args, **kwargs)
# _[manual|auto]_docs are ordered dicts storing endpoints documentation
# {
# endpoint: {
# 'get': documentation,
# 'post': documentation,
# ...
# },
# ...
# }
self._auto_docs = OrderedDict()
self._manual_docs = OrderedDict()
self._endpoints = []
def route(self, rule, *, parameters=None, **options):
"""Decorator to register url rule in application
Also stores doc info for later registration
Use this to decorate a :class:`MethodView <flask.views.MethodView>` or
a resource function.
:param str rule: URL rule as string.
:param str endpoint: Endpoint for the registered URL rule (defaults
to function name).
:param list parameters: List of parameters relevant to all operations
in this path, only used to document the resource.
:param dict options: Options to be forwarded to the underlying
:class:`werkzeug.routing.Rule <Rule>` object.
"""
def decorator(func):
# By default, endpoint name is function name
endpoint = options.pop('endpoint', func.__name__)
# Prevent registering several times the same endpoint
# by silently renaming the endpoint in case of collision
if endpoint in self._endpoints:
endpoint = '{}_{}'.format(endpoint, len(self._endpoints))
self._endpoints.append(endpoint)
if isinstance(func, MethodViewType):
view_func = func.as_view(endpoint)
else:
view_func = func
# Add URL rule in Flask and store endpoint documentation
self.add_url_rule(rule, endpoint, view_func, **options)
self._store_endpoint_docs(endpoint, func, parameters, **options)
return func
return decorator
def _store_endpoint_docs(self, endpoint, obj, parameters, **options):
"""Store view or function doc info"""
endpoint_auto_doc = self._auto_docs.setdefault(
endpoint, OrderedDict())
endpoint_manual_doc = self._manual_docs.setdefault(
endpoint, OrderedDict())
def store_method_docs(method, function):
"""Add auto and manual doc to table for later registration"""
# Get auto documentation from decorators
# and summary/description from docstring
# Get manual documentation from @doc decorator
auto_doc = getattr(function, '_apidoc', {})
auto_doc.update(
load_info_from_docstring(
function.__doc__,
delimiter=self.DOCSTRING_INFO_DELIMITER
)
)
manual_doc = getattr(function, '_api_manual_doc', {})
# Store function auto and manual docs for later registration
method_l = method.lower()
endpoint_auto_doc[method_l] = auto_doc
endpoint_manual_doc[method_l] = manual_doc
# MethodView (class)
if isinstance(obj, MethodViewType):
for method in self.HTTP_METHODS:
if method in obj.methods:
func = getattr(obj, method.lower())
store_method_docs(method, func)
# Function
else:
methods = options.pop('methods', None) or ['GET']
for method in methods:
store_method_docs(method, obj)
endpoint_auto_doc['parameters'] = parameters
def register_views_in_doc(self, app, spec):
"""Register views information in documentation
If a schema in a parameter or a response appears in the spec
`schemas` section, it is replaced by a reference in the parameter or
response documentation:
"schema":{"$ref": "#/components/schemas/MySchema"}
"""
# This method uses the documentation information associated with each
# endpoint in self._[auto|manual]_docs to provide documentation for
# corresponding route to the spec object.
# Deepcopy to avoid mutating the source
# Allows registering blueprint multiple times (e.g. when creating
# multiple apps during tests)
auto_docs = deepcopy(self._auto_docs)
for endpoint, endpoint_auto_doc in auto_docs.items():
parameters = endpoint_auto_doc.pop('parameters')
doc = OrderedDict()
for method_l, endpoint_doc in endpoint_auto_doc.items():
# Format operations documentation in OpenAPI structure
self._prepare_doc(endpoint_doc, spec.openapi_version)
# Tag all operations with Blueprint name
endpoint_doc['tags'] = [self.name]
# Merge auto_doc and manual_doc into doc
manual_doc = self._manual_docs[endpoint][method_l]
doc[method_l] = deepupdate(endpoint_doc, manual_doc)
# Thanks to self.route, there can only be one rule per endpoint
full_endpoint = '.'.join((self.name, endpoint))
rule = next(app.url_map.iter_rules(full_endpoint))
spec.path(rule=rule, operations=doc, parameters=parameters)
def _prepare_doc(self, operation, openapi_version):
"""Format operation documentation in OpenAPI structure
The decorators store all documentation information in a dict structure
that is close to OpenAPI doc structure, so this information could
_almost_ be copied as is. Yet, some adjustemnts may have to be
performed, especially if the spec structure differs between OpenAPI
versions: the OpenAPI version is not known when the decorators are
applied but only at registration time when this method is called.
"""
# OAS 2
if openapi_version.major < 3:
if 'responses' in operation:
for resp in operation['responses'].values():
if 'example' in resp:
resp['examples'] = {
DEFAULT_RESPONSE_CONTENT_TYPE: resp.pop('example')}
if 'parameters' in operation:
for param in operation['parameters']:
if param['in'] in (
self.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING
):
content_type = (
param.pop('content_type', None) or
self.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING[
param['in']]
)
if content_type != DEFAULT_REQUEST_BODY_CONTENT_TYPE:
operation['consumes'] = [content_type, ]
# body and formData are mutually exclusive
break
# OAS 3
else:
if 'responses' in operation:
for resp in operation['responses'].values():
for field in ('schema', 'example', 'examples'):
if field in resp:
(
resp
.setdefault('content', {})
.setdefault(DEFAULT_RESPONSE_CONTENT_TYPE, {})
[field]
) = resp.pop(field)
if 'parameters' in operation:
for param in operation['parameters']:
if param['in'] in (
self.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING
):
request_body = {
x: param[x]
for x in ('description', 'required')
if x in param
}
fields = {
x: param.pop(x)
for x in ('schema', 'example', 'examples')
if x in param
}
content_type = (
param.pop('content_type', None) or
self.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING[
param['in']]
)
request_body['content'] = {content_type: fields}
operation['requestBody'] = request_body
# There can be only one requestBody
operation['parameters'].remove(param)
if not operation['parameters']:
del operation['parameters']
break
@staticmethod
def doc(**kwargs):
"""Decorator adding description attributes to a view function
Values passed as kwargs are copied verbatim in the docs
Example: ::
@blp.doc(description="Return pets based on ID",
summary="Find pets by ID"
)
def get(...):
...
"""
def decorator(func):
@wraps(func)
def wrapper(*f_args, **f_kwargs):
return func(*f_args, **f_kwargs)
# Don't merge manual doc with auto-documentation right now.
# Store it in a separate attribute to merge it later.
# The deepcopy avoids modifying the wrapped function doc
wrapper._api_manual_doc = deepupdate(
deepcopy(getattr(wrapper, '_api_manual_doc', {})), kwargs)
return wrapper
return decorator
| {
"repo_name": "Nobatek/flask-rest-api",
"path": "flask_rest_api/blueprint.py",
"copies": "1",
"size": "12064",
"license": "mit",
"hash": -5977737212997988000,
"line_mean": 39.0797342193,
"line_max": 79,
"alpha_frac": 0.5640749337,
"autogenerated": false,
"ratio": 5.0120481927710845,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6076123126471085,
"avg_score": null,
"num_lines": null
} |
# API call for all players in Premier League
import pandas as pd
import numpy as np
import json, requests
from time import sleep
################################################################################
# Will start by pulling data for each player from 1 through 543 (see range below)
df = pd.DataFrame()
type(df)
for i in range (1, 544):
r = requests.get('https://fantasy.premierleague.com/drf/element-summary/'+str(i))
data = r.json()['history_past']
if not data:
data = [{'assists': 'NaN_',
'bonus': 'NaN',
'bps': 'NaN',
'clean_sheets': 'NaN',
'creativity': 'NaN',
'ea_index': 'NaN',
'element_code': 'NaN_'+str(i),
'end_cost': 'NaN',
'goals_conceded': 'NaN',
'goals_scored': 'NaN',
'ict_index': 'NaN',
'id': 'NaN',
'influence': 'NaN',
'minutes': 'NaN',
'own_goals': 'NaN',
'penalties_missed': 'NaN',
'penalties_saved': 'NaN',
'red_cards': 'NaN',
'saves': 'NaN',
'season': 'NaN',
'season_name': 'NaN',
'start_cost': 'NaN',
'threat': 'NaN',
'total_points': 'NaN',
'yellow_cards': 'NaN'}]
df1 = pd.DataFrame(data)
else:
df1 = pd.DataFrame(data)
df = df.append(df1, ignore_index=True)
sleep(.005)
#print(df)
df.shape
df.head(100)
df['unique_element_code'] = pd.factorize(df['element_code'])[0]
df['unique_element_code'] = df['unique_element_code'] + 1
# Running a quick test on firmino historical data (url ending 235)
df[df['unique_element_code']==235]
################################################################################
# This section will pull the player name from https://fantasy.premierleague.com/drf/elements/
e = requests.get('https://fantasy.premierleague.com/drf/elements/')
# checking the keys
list(e)
# Checking the json
elements = e.json()
elements_df = pd.DataFrame(elements)
elements_df.columns
pd.set_option('display.max_columns', 60)
elements_df[['id', 'web_name', 'element_type']]
elements_df = elements_df[['id', 'web_name', 'element_type']]
# Renaming 'id' Series so it'll match with df
elements_df = elements_df.rename(columns = {'id': 'unique_element_code'})
elements_df.head(30)
################################################################################
# Now that we have all the elements, with names, we can merge the DataFrames
# New DataFrame will be called historic
pd.options.display.max_rows = 1900
historic = pd.merge(df, elements_df, on='unique_element_code', how='outer')
historic
historic.shape
historic.dtypes
# Checking Hazard
historic[historic['web_name']=='Hazard']
# Mapping players by position
historic['position'] = historic.element_type.map({1:'goalkeeper', 2:'defender', 3:'midfielder', 4:'forward'})
list(historic.columns)
# Changing the column order
column_order = ['web_name', 'season_name', 'position', 'total_points', 'minutes', 'goals_scored', 'assists',
'clean_sheets', 'goals_conceded', 'saves', 'bonus', 'bps', 'penalties_missed',
'penalties_saved', 'start_cost', 'end_cost', 'ict_index', 'influence',
'creativity', 'threat', 'id', 'element_code', 'ea_index', 'element_type',
'unique_element_code', 'season', 'red_cards', 'yellow_cards', 'own_goals']
len(column_order)
historic = historic[column_order]
historic.tail(50)
# Saving data to csv
historic.to_csv('historic_data_all_epl_players.csv')
historic['total_points'] = pd.to_numeric(historic['total_points'], errors='coerce')
historic['goals_scored'] = pd.to_numeric(historic['goals_scored'], errors='coerce')
# Quick groupby to see some stats by position
historic.groupby('position').total_points.mean()
historic.groupby('position').goals_scored.mean()
| {
"repo_name": "seamus-mckinsey/fpl",
"path": "historical_api_call.py",
"copies": "1",
"size": "4207",
"license": "mit",
"hash": 1784495480922656500,
"line_mean": 31.3615384615,
"line_max": 109,
"alpha_frac": 0.5398145947,
"autogenerated": false,
"ratio": 3.5087572977481236,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45485718924481233,
"avg_score": null,
"num_lines": null
} |
"""API calls for RingPlus."""
from __future__ import print_function
from ringplus.parsers import ModelParser
from ringplus.binder import bind_api
class API(object):
"""A python wrapper for the RingPlus API.
:reference: https://docs.ringplus.net/
"""
def __init__(self, auth_handler=None,
host='api.ringplus.net', cache=None,
parser=None, version='1', retry_count=0, retry_delay=0,
retry_errors=None, timeout=60,
wait_on_rate_limit=False, wait_on_rate_limit_notify=False,
proxy=''):
"""API instance constructor.
Args:
auth_handler: The OAutherHandler from to use to retreive the
authorization token.
host: url of the server of the rest api.
default:'api.ringplus.net'
cache: Cache to query if a GET method is used.
default:None
parser: ModelParser instance to parse the responses.
default:None
version: Major version number to include in header.
default 1
retry_count: number of allowed retries, default:0
retry_errors: default:None
timeout: delay before to consider the request as timed out in
seconds. default:60
wait_on_rate_limit: If the api wait when it hits the rate limit.
default:False
wait_on_rate_limit_notify: If the api print a notification when
the rate limit is hit. default:False
proxy: Url to use as proxy during the HTTP request. default:''
"""
self.auth = auth_handler
self.host = host
self.cache = cache
self.parser = parser or ModelParser()
self.version = version
self.retry_count = retry_count
self.retry_delay = retry_delay
self.retry_errors = retry_errors
self.timeout = 60
self.wait_on_rate_limit = wait_on_rate_limit
self.wait_on_rate_limit_notify = wait_on_rate_limit_notify
self.proxy = proxy
# Accounts
@property
def user_accounts(self):
"""A list of accounts belonging to a specific user.
scope: public
Args:
user_id: User ID
name (optional): The name of the account to filter by.
Currently does not partial or full text search.
email_address (optional): The email_address of the account to
filter by. Currently does not partial or full text search.
phone_number (optional): The phone_number of the account to
filter by. Currently does not partial or full text search.
device_esn (optional): The active device_esn of the account to
filter by. Currently does not partial or full text search.
device_iccid (optional): The active device_iccid of the account to
filter by. Currently does not partial or full text search.
page (optional): Which page of the paged results to return.
Default to 1.
per_page (optional): How many results to return per page.
Defaults to 25.
Returns
list: List of Account objects
"""
return bind_api(
api=self,
path='/users/{user_id}/accounts',
payload_type='account',
payload_list=True,
allowed_param=['user_id', 'name', 'email_address',
'phone_number', 'device_esn', 'device_iccid',
'page', 'per_page'])
@property
def accounts(self):
"""List all accounts the user has access to.
scope: public
Args:
name (optional): The name of the account to filter by.
Currently does not partial or full text search.
email_address (optional): The email_address of the account to
filter by. Currently does not partial or full text search.
phone_number (optional): The phone_number of the account to
filter by. Currently does not partial or full text search.
ddevice_esn (optional): The active device_esn of the account to
filter by. Currently does not partial or full text search.
device_iccid (optional): The active device_iccid of the account to
filter by. Currently does not partial or full text search.
page (optional): Which page of the paged results to return.
Default to 1.
per_page (optional): How many results to return per page.
Defaults to 25.
Returns
list: List of Account objects
"""
return bind_api(
api=self,
path='/accounts',
payload_type='account',
payload_list=True,
allowed_param=['name', 'email_address', 'phone_number',
'device_esn', 'device_iccid', 'page',
'per_page'])
@property
def get_account(self):
"""Get a specific account.
This returns a more detailed account object than those returned in
API.user_accounts and API.accounts.
scope: public
Args:
account_id: Account ID
Returns:
Detailed Account object.
"""
return bind_api(
api=self,
path='/accounts/{account_id}',
payload_type='account',
allowed_param=['account_id'])
@property
def update_account(self):
"""Update an accounts information.
scope: manage
Args:
account_id: Account ID
name (optional): Update the name of an account.
"""
return bind_api(
api=self,
path='/accounts/{account_id}',
method='PUT',
post_container='account',
allowed_param=['account_id', 'name'])
# Account Registration
@property
def register_account(self):
"""Create a registration request to associate a user with a device.
scope: request
Args:
user_id: User ID
name: A name for this account.
billing_plan_id: The ID of the billing plan to use for this
account.
device_esn: The mobile device's ESN numbers, usually an
alphanumeric string.
credit_card_id: An ID of a credit card already associated with the
User.
device_iccid (optional): The mobile device's ICCID, or SIM card
serial number.
Returns:
Account Registration Request Status object.
"""
return bind_api(
api=self,
path='/users/{user_id}/account_registration_requests',
method='POST',
post_container='account_registration_request',
payload_type='request',
allowed_param=['user_id', 'name', 'billing_plan_id',
'device_esn', 'device_iccid', 'credit_card_id'])
@property
def register_account_status(self):
"""Get the status on an account registration request.
scope: public
Args:
request_id: The ID of the register account request.
Returns:
list: List of Account Registration Status objects.
"""
return bind_api(
api=self,
path='/account_registration_requests/{request_id}',
payload_type='request',
payload_list=True,
allowed_param=['request_id'])
# Change Device
@property
def change_device(self):
"""Create a change device request to change physical device.
Registering new devices can take time depending on the device and
network conditions. The request route provide a non-blocking way of
sending the request. Requests that pass initial validation will return
with with a request ID which can be queried to find out the status of
the request. The status of the request will display whether the
request has been completed and whether it was successful.
scope: request
Args:
account_id: Account ID
device_esn: ESN of new device.
device_iccid (optional): The mobile device's ICCID, or SIM card
serial number. This is optional, only if the device does not
have an ICCID. If the device has an ICCID and it is not
included in the request, the request will likely fail.
Returns:
Change Device Request Status object.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/device_change_requests',
method='POST',
post_container='device_change_request',
payload_type='request',
allowed_param=['account_id', 'device_esn', 'device_iccid'])
@property
def change_device_status(self):
"""Get the status of a device change request.
scope: public
Args:
request_id: The ID of the change device request.
Returns:
list: List of Device Request Status objects.
"""
return bind_api(
api=self,
path='/device_change_requests/{request_id}',
payload_type='request',
payload_list=True,
allowed_param=['request_id'])
# Change Phone Number
@property
def change_phone_number(self):
"""Creates a request to change the phone number of an Account.
Change phone number requsts allow you to change the phone number on an
account. Change Phone Number requests do not allow you choose your new
phone number, you will be assigned an available number.
The request route provide a non-blocking way of sending the request.
Requests that pass initial validation will return with with a request
ID which can be queried to find out the status of the request. The
status of the request will display whether the request has been
completed and whether it was successful.
scope: request
Args:
account_id: Account ID
Returns:
Change Phone Number Request Status object.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/phone_number_change_requests',
method='POST',
payload_type='request',
allowed_param=['account_id'])
@property
def change_phone_number_status(self):
"""Get the status of a phone number change request.
scope: public
Args:
request_id:
Returns:
list: List of Change Phone Number Request Status objects.
"""
return bind_api(
api=self,
path='/phone_number_change_requests/{request_id}',
payload_type='request',
payload_list=True,
allowed_param=['request_id'])
# Enforced Carrier Services
@property
def enforced_carrier_services(self):
"""List the applied enforced carrier services of an Account.
Enforced Carrier Services are services offered at the carrier level
that have been enforced on an account. These are not the only services
that may be active on a given account, but are sure to override any
other policies.
scope: public
Args:
account_id: Account ID
page (optional): Which page of the paged results to return.
Default to 1.
per_page (optional): How many results to return per page.
Defaults to 25.
Returns:
list: List of Carrier Service objects.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/enforced_carrier_services',
payload_type='carrier_service',
payload_list=True,
allowed_param=['account_id', 'page', 'per_page'])
# Fluid Call
@property
def fluid_call_credentials(self):
"""Get the list of FluidCall credentials.
FluidCall allows any VoIP phone to act as an additional handset
attached to an account. Currently, any number of additional FluidCall
connections can be made to a single account. Those connections will be
rung along with the primary handset, and can make calls using standard
SIP/RTP VoIP protocols.
scope: public
Args:
account_id: Account ID
page (optional): Which page of the paged results to return.
Default to 1.
per_page (optional): How many results to return per page.
Defaults to 25.
Returns:
list: List of Fluid Call objects.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/fluidcall_credentials',
payload_type='fluidcall',
payload_list=True,
allowed_param=['account_id', 'page', 'per_page'])
# Phone Calls
@property
def calls(self):
"""Returns an account's paged phone call details.
scope: public
Args:
account_id: Account ID
start_date (datetime, optional): Return only records occurring
after this date.
end_date (datetime, optional): Return only records occurring
before this date.
per_page (optional): How many results to return per page.
Defaults to 25.
page (optional): Which page of the paged results to return.
Default to 1.
Returns:
list: List of Call objects.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/phone_calls',
payload_type='call',
payload_list=True,
allowed_param=['account_id', 'start_date',
'end_date', 'per_page', 'page'])
# Phone Texts
@property
def texts(self):
"""Returns an account's paged phone text details.
scope: public
Args:
account_id: Account ID
start_date (datetime, optional): Return only records occurring
after this date.
end_date (datetime, optional): Return only records occurring
before this date.
per_page (optional): How many results to return per page.
Defaults to 25.
page (optional): Which page of the paged results to return.
Default to 1.
Returns:
list: List of Text objects.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/phone_texts',
payload_type='text',
payload_list=True,
allowed_param=['account_id', 'start_date',
'end_date', 'per_page', 'page'])
# Phone Data
@property
def data(self):
"""Return an account's paged phone data details.
scope: public
Args:
account_id: Account ID
start_date (datetime, optional): Return only records occurring
after this date.
end_date (datetime, optional): Return only records occurring
before this date.
per_page (optional): How many results to return per page.
Defaults to 25.
page (optional): Which page of the paged results to return.
Default to 1.
Returns:
list: List of Data objects.
"""
return bind_api(
api=self,
path='/accounts/{account_id}/phone_data',
payload_type='data',
payload_list=True,
allowed_param=['account_id', 'start_date',
'end_date', 'per_page', 'page'])
# Users
@property
def get_user(self):
"""Return a specific user's details.
scope: public
Args:
user_id: User ID
Returns:
User object.
"""
return bind_api(
api=self,
path='/users/{user_id}',
payload_type='user',
allowed_param=['user_id'])
@property
def users(self):
"""Return all Users you have access to.
scope: public
Args:
email_address (optional): The email_address of the account to
filter by. Currently does not partial or full text search.
per_page (optional): How many results to return per page.
Defaults to 25.
page (optional): Which page of the paged results to return.
Default to 1.
Returns:
list: List of User objects.
"""
return bind_api(
api=self,
path='/users',
payload_type='user',
payload_list=True,
allowed_param=['email_address', 'per_page', 'page'])
@property
def update_user(self):
"""Update a User's account.
scope: manage
Args:
user_id: User ID
email (optional): New email.
password (optional): New password.
"""
return bind_api(
api=self,
path='/users/{user_id}',
method='PUT',
post_container='user',
allowed_param=['user_id', 'email', 'password'])
# Voicemail Messages
@property
def voicemail(self):
"""Return an Account's paged voicemail messages.
scope: voicemail
Args:
voicemail_box_id: ID of the voicemail box.
only_new (optional):
per_page (optional): How many results to return per page.
Defaults to 25.
page (optional): Which page of the paged results to return.
Default to 1.
Returns:
list: Paged list of voicemail message objects.
"""
return bind_api(
api=self,
path='/voicemail_boxes/{voicemail_box_id}/voicemail_messages',
payload_type='voicemail',
payload_list=True,
allowed_param=['voicemail_box_id', 'only_new', 'per_page', 'page'])
@property
def delete_voicemail(self):
"""Deletes a voicemail message.
scope: voicemail
Args:
voicemail_message_id:
"""
return bind_api(
api=self,
path='/voicemail_messages/{voicemail_message_id}',
allowed_param=['voicemail_message_id'],
method='DELETE')
| {
"repo_name": "Shatnerz/ringplus",
"path": "ringplus/api.py",
"copies": "1",
"size": "18878",
"license": "mit",
"hash": -2782194268749250000,
"line_mean": 32.590747331,
"line_max": 79,
"alpha_frac": 0.5595402055,
"autogenerated": false,
"ratio": 4.768375852488002,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 562
} |
"""API calls for the Flask application"""
import os
import gevent
from flask import Response, request, render_template, send_from_directory, jsonify
from gevent.queue import Queue
from bcbio_monitor import app
from bcbio_monitor import parser as ps
#############################################
# controllers and static path configuration #
#############################################
# SSE "protocol" is described here: http://mzl.la/UPFyxY
subscriptions = []
class ServerSentEvent(object):
def __init__(self, data):
self.data = data
self.event = None
self.id = None
self.desc_map = {
self.data : "data",
self.event : "event",
self.id : "id"
}
def encode(self):
if not self.data:
return ""
lines = ["%s: %s" % (v, k)
for k, v in self.desc_map.iteritems() if k]
return "%s\n\n" % "\n".join(lines)
@app.route("/publish", methods=['POST'])
def publish():
data = request.data
def notify():
for sub in subscriptions[:]:
sub.put(data)
gevent.spawn(notify)
return "OK"
@app.route("/subscribe")
def subscribe():
def gen():
q = Queue()
subscriptions.append(q)
try:
while True:
result = q.get()
ev = ServerSentEvent(str(result))
yield ev.encode()
except GeneratorExit: # Or maybe use flask signals
subscriptions.remove(q)
return Response(gen(), mimetype="text/event-stream")
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'ico/favicon.ico')
@app.route('/js/<path:path>')
def static_proxy(path):
mime = 'application/javascript'
return Response(app.send_static_file(os.path.join('js', path)), mime)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route("/")
def index():
return render_template('index.html', **app.config)
###################
# API #
###################
@app.route('/runs_info', methods=['GET'])
def get_runs_info():
"""Return all runs info in a single API call"""
return jsonify(data=app.analysis.get_runs_info())
@app.route('/graph_source', methods=['GET'])
def graph_source_for_run():
run_id = request.args.get('run', 1)
return jsonify(graph_source=app.analysis.graph_source_for_run(int(run_id) - 1))
@app.route('/steps', methods=['GET'])
def table_data_for_run():
run_id = request.args.get('run', 0)
return jsonify(steps=app.analysis.table_data_for_run(int(run_id) - 1))
@app.route('/status', methods=['GET'])
def get_status():
return jsonify(app.analysis.get_status(run_id=request.args.get('run', None)))
@app.route('/last_message', methods=['GET'])
def get_last_message():
"""Returns last message read by the monitor"""
return jsonify(app.analysis.get_last_message())
@app.route('/summary', methods=['GET'])
def summary():
"""Get summary of a finished analysis"""
return jsonify(app.analysis.get_summary())
| {
"repo_name": "guillermo-carrasco/bcbio-nextgen-monitor",
"path": "bcbio_monitor/api/__init__.py",
"copies": "1",
"size": "3121",
"license": "mit",
"hash": -5017185750685911000,
"line_mean": 24.1693548387,
"line_max": 88,
"alpha_frac": 0.5892342198,
"autogenerated": false,
"ratio": 3.595622119815668,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9674781920017272,
"avg_score": 0.002014883919679213,
"num_lines": 124
} |
import requests # pip install requests if you don't have it
import json
def grade_request(f):
# makes the request to the theia interface and returns the grade of that image.
# if there is something wrong, it returns -1
# argument - file object
# Get the key from external file
try:
keyfile = open('/home/pi/openDR/key')
key = keyfile.readline()
except IOError:
print "CANNOT FIND KEY FOR THEIA. PLEASE CHECK."
return -1
image_file = open(f)
uri = 'https://theia.media.mit.edu/api/v1/uploadImage?key=' + key
response = requests.post(uri, files={'file': image_file})
if (response.status_code == 200):
# TODO: check for BAD API KEY
# print "response OK"
# convert response.text to json and parse as dictionary
data = json.loads(response.text)
grade = float(str(data['grade'])[1:-1])
return grade
else:
return -1
## BEGIN THE REQUEST:
# print grade_request(open('normal1.jpg', 'rb'))
| {
"repo_name": "derbedhruv/openDR",
"path": "modules/theia.py",
"copies": "1",
"size": "1160",
"license": "mit",
"hash": -5563606920903026000,
"line_mean": 31.1428571429,
"line_max": 83,
"alpha_frac": 0.6327586207,
"autogenerated": false,
"ratio": 3.504531722054381,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9414276781046875,
"avg_score": 0.044602712341501156,
"num_lines": 35
} |
"""api_cats URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.authtoken import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include('cats.urls', namespace='cats')),
url(r'^api/v1/', include('users.urls', namespace='users')),
# REST Framework URL's
url(r'^api-auth/', include(
'rest_framework.urls',
namespace='rest_framework'
))
]
# URL to obtain user Auth Token
urlpatterns += [
url(r'^api/v1/token-auth/', views.obtain_auth_token)
]
| {
"repo_name": "OscaRoa/api-cats",
"path": "api_cats/urls.py",
"copies": "1",
"size": "1184",
"license": "mit",
"hash": -164974865076207940,
"line_mean": 32.8285714286,
"line_max": 79,
"alpha_frac": 0.6765202703,
"autogenerated": false,
"ratio": 3.441860465116279,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46183807354162787,
"avg_score": null,
"num_lines": null
} |
"""API checking module.
This module serves as a library of API checks used as assertions during
constructing the computational graph.
"""
from typing import List, Optional
import tensorflow as tf
class CheckingException(Exception):
pass
def assert_shape(tensor: tf.Tensor,
expected_shape: List[Optional[int]]) -> None:
"""Check shape of a tensor.
Args:
tensor: Tensor to be chcecked.
expected_shape: Expected shape where `None` means the same as in TF and
`-1` means not checking the dimension.
"""
shape_list = tensor.get_shape().as_list()
if len(shape_list) != len(expected_shape):
raise CheckingException(
"Tensor '{}' with shape {} should have {} dimensions.".format(
tensor.name, shape_list, len(expected_shape)))
mismatching_dims = []
for i, (real, expected) in enumerate(zip(shape_list, expected_shape)):
if expected not in (real, -1):
mismatching_dims.append(i)
if mismatching_dims:
expected_str = ", ".join(
"?" if x == -1 else str(x) for x in expected_shape)
raise CheckingException(
("Shape mismatch of {} in dimensions: {}. "
"Shape was {}, but should be [{}]").format(
tensor.name,
", ".join(str(d) for d in mismatching_dims),
shape_list, expected_str))
def assert_same_shape(tensor_a: tf.Tensor, tensor_b: tf.Tensor) -> None:
"""Check if two tensors have the same shape."""
shape_a = tensor_a.get_shape().as_list()
shape_b = tensor_b.get_shape().as_list()
if len(shape_a) != len(shape_b):
raise CheckingException(
("Tensor '{}' has {} dimensions and tensor '{}' has {} "
"dimension, but should have the same shape.").format(
tensor_a.name, len(shape_a), tensor_b.name, len(shape_b)))
mismatching_dims = []
for i, (size_a, size_b) in enumerate(zip(shape_a, shape_b)):
if size_a != size_b:
mismatching_dims.append(i)
if mismatching_dims:
raise CheckingException(
("Shape mismatch of '{}' and '{}' in dimensions: {}. "
"Shapes were {} and {}").format(
tensor_a.name, tensor_b.name,
", ".join(str(d) for d in mismatching_dims),
shape_a, shape_b))
| {
"repo_name": "ufal/neuralmonkey",
"path": "neuralmonkey/checking.py",
"copies": "1",
"size": "2397",
"license": "bsd-3-clause",
"hash": -6101260454197517000,
"line_mean": 32.7605633803,
"line_max": 79,
"alpha_frac": 0.5748852733,
"autogenerated": false,
"ratio": 3.8912337662337664,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9966119039533766,
"avg_score": 0,
"num_lines": 71
} |
"""API checking module.
This module serves as a library of API checks used as assertions during
constructing the computational graph.
"""
from typing import List, Optional, Iterable
import tensorflow as tf
from neuralmonkey.logging import log, debug
from neuralmonkey.dataset import Dataset
from neuralmonkey.runners.base_runner import BaseRunner
class CheckingException(Exception):
pass
def check_dataset_and_coders(dataset: Dataset,
runners: Iterable[BaseRunner]) -> None:
# pylint: disable=protected-access
data_list = []
for runner in runners:
for c in runner.all_coders:
if hasattr(c, "data_id"):
data_list.append((getattr(c, "data_id"), c))
elif hasattr(c, "data_ids"):
data_list.extend([(d, c) for d in getattr(c, "data_ids")])
elif hasattr(c, "input_sequence"):
inpseq = getattr(c, "input_sequence")
if hasattr(inpseq, "data_id"):
data_list.append((getattr(inpseq, "data_id"), c))
elif hasattr(inpseq, "data_ids"):
data_list.extend(
[(d, c) for d in getattr(inpseq, "data_ids")])
else:
log("Input sequence: {} does not have a data attribute"
.format(str(inpseq)))
else:
log(("Coder: {} has neither an input sequence attribute nor a "
"a data attribute.").format(c))
debug("Found series: {}".format(str(data_list)), "checking")
missing = []
for (serie, coder) in data_list:
if not dataset.has_series(serie):
log("dataset {} does not have serie {}".format(
dataset.name, serie))
missing.append((coder, serie))
if missing:
formated = ["{} ({}, {}.{})" .format(serie, cod.name,
cod.__class__.__module__,
cod.__class__.__name__)
for cod, serie in missing]
raise CheckingException("Dataset '{}' is mising series {}:"
.format(dataset.name, ", ".join(formated)))
def assert_shape(tensor: tf.Tensor,
expected_shape: List[Optional[int]]) -> None:
"""Check shape of a tensor.
Args:
tensor: Tensor to be chcecked.
expected_shape: Expected shape where `None` means the same as in TF and
`-1` means not checking the dimension.
"""
shape_list = tensor.get_shape().as_list()
if len(shape_list) != len(expected_shape):
raise CheckingException(
"Tensor '{}' with shape {} should have {} dimensions.".format(
tensor.name, shape_list, len(expected_shape)))
mismatching_dims = []
for i, (real, expected) in enumerate(zip(shape_list, expected_shape)):
if expected != -1 and real != expected:
mismatching_dims.append(i)
if mismatching_dims:
expected_str = ", ".join(
"?" if x == -1 else str(x) for x in expected_shape)
raise CheckingException(
("Shape mismatch of {} in dimensions: {}. "
"Shape was {}, but should be [{}]").format(
tensor.name,
", ".join(str(d) for d in mismatching_dims),
shape_list, expected_str))
def assert_same_shape(tensor_a: tf.Tensor, tensor_b: tf.Tensor) -> None:
"""Check if two tensors have the same shape."""
shape_a = tensor_a.get_shape().as_list()
shape_b = tensor_b.get_shape().as_list()
if len(shape_a) != len(shape_b):
raise CheckingException(
("Tensor '{}' has {} dimensions and tensor '{}' has {} "
"dimension, but should have the same shape.").format(
tensor_a.name, len(shape_a), tensor_b.name, len(shape_b)))
mismatching_dims = []
for i, (size_a, size_b) in enumerate(zip(shape_a, shape_b)):
if size_a != size_b:
mismatching_dims.append(i)
if mismatching_dims:
raise CheckingException(
("Shape mismatch of '{}' and '{}' in dimensions: {}. "
"Shapes were {} and {}").format(
tensor_a.name, tensor_b.name,
", ".join(str(d) for d in mismatching_dims),
shape_a, shape_b))
| {
"repo_name": "juliakreutzer/bandit-neuralmonkey",
"path": "neuralmonkey/checking.py",
"copies": "1",
"size": "4402",
"license": "bsd-3-clause",
"hash": 4435057747071704000,
"line_mean": 35.3801652893,
"line_max": 79,
"alpha_frac": 0.5411176738,
"autogenerated": false,
"ratio": 4.049678012879485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 121
} |
"""A pickleable wrapper for sharing NumPy ndarrays between processes using POSIX shared memory."""
import mmap
import sys
import numpy as np
import shared_memory
MINIMUMSHMSIZE = sys.getsizeof(np.array([]))
class SharedNDArray:
"""Creates a new SharedNDArray, a pickleable wrapper for sharing NumPy ndarrays between
processes using POSIX shared memory.
SharedNDArrays are designed to be sent over multiprocessing.Pipe and Queue without serializing
or transmitting the underlying ndarray or buffer. While the associated file descriptor is
closed when the SharedNDArray is garbage collected, the underlying buffer is not released when
the process ends: you must manually call the unlink() method from the last process to use it.
Attributes:
array: The wrapped NumPy ndarray, backed by POSIX shared memory.
"""
def __init__(self, shape, dtype=np.float64, name=None):
"""Creates a new SharedNDArray.
If name is left blank, a new POSIX shared memory segment is created using a random name.
Args:
shape: Shape of the wrapped ndarray.
dtype: Data type of the wrapped ndarray.
name: Optional; the filesystem path of the underlying POSIX shared memory.
Returns:
A new SharedNDArray of the given shape and dtype and backed by the given optional name.
Raises:
SharedNDArrayError: if an error occurs.
"""
size = MINIMUMSHMSIZE + int(np.prod(shape)) * np.dtype(dtype).itemsize
if name:
try:
self._shm = shared_memory.SharedMemory(name, size=size)
except shared_memory.ExistentialError as ee:
raise ee.__class__(f"{ee.args[0]}; requested name: {name}")
else:
self._shm = shared_memory.SharedMemory(None, flags=shared_memory.O_CREX, size=size)
self.array = np.ndarray(shape, dtype, self._shm.buf, order='C')
def flush(self):
# Why is this necessary, if at all?!?
# TODO: Should this use np.memmap() instead? What would impact to performance be?
#self._shm.buf.seek(0)
#self._shm.buf.write(self.array.tobytes())
import warnings
warnings.warn("flush() called but should be going away")
def __getattr__(self, name):
return getattr(self.array, name)
@classmethod
def copy(cls, arr):
"""Creates a new SharedNDArray that is a copy of the given ndarray.
Args:
arr: The ndarray to copy.
Returns:
A new SharedNDArray object with the given ndarray's shape and data type and a copy of
its data.
Raises:
SharedNDArrayError: if an error occurs.
"""
new_shm = cls.zeros_like(arr)
new_shm.array[:] = arr
#new_shm.flush()
return new_shm
@classmethod
def zeros_like(cls, arr):
"""Creates a new zero-filled SharedNDArray with the shape and dtype of the given ndarray.
Raises:
SharedNDArrayError: if an error occurs.
"""
return cls(arr.shape, arr.dtype)
def unlink(self):
"""Marks the underlying shared for deletion.
This method should be called exactly once from one process. Failure to call it before all
processes exit will result in a memory leak! It will raise SharedNDArrayError if the
underlying shared memory was already marked for deletion from any process.
Raises:
SharedNDArrayError: if an error occurs.
"""
self._shm.unlink()
def __del__(self):
self._shm.close()
def __getstate__(self):
return self.array.shape, self.array.dtype, self._shm.name
def __setstate__(self, state):
self.__init__(*state)
| {
"repo_name": "applio/proto_shmem",
"path": "shared_ndarray/shared_ndarray/shared_ndarray.py",
"copies": "1",
"size": "3808",
"license": "mit",
"hash": -1492378960571723800,
"line_mean": 33.6181818182,
"line_max": 99,
"alpha_frac": 0.6394432773,
"autogenerated": false,
"ratio": 4.283464566929134,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5422907844229135,
"avg_score": null,
"num_lines": null
} |
"""A pickleable wrapper for sharing NumPy ndarrays between processes using POSIX shared memory."""
import mmap
import numpy as np
import posix_ipc
class SharedNDArray:
"""Creates a new SharedNDArray, a pickleable wrapper for sharing NumPy ndarrays between
processes using POSIX shared memory.
SharedNDArrays are designed to be sent over multiprocessing.Pipe and Queue without serializing
or transmitting the underlying ndarray or buffer. While the associated file descriptor is
closed when the SharedNDArray is garbage collected, the underlying buffer is not released when
the process ends: you must manually call the unlink() method from the last process to use it.
Attributes:
array: The wrapped NumPy ndarray, backed by POSIX shared memory.
"""
def __init__(self, shape, dtype=np.float64, name=None):
"""Creates a new SharedNDArray.
If name is left blank, a new POSIX shared memory segment is created using a random name.
Args:
shape: Shape of the wrapped ndarray.
dtype: Data type of the wrapped ndarray.
name: Optional; the filesystem path of the underlying POSIX shared memory.
Returns:
A new SharedNDArray of the given shape and dtype and backed by the given optional name.
Raises:
SharedNDArrayError: if an error occurs.
"""
size = int(np.prod(shape)) * np.dtype(dtype).itemsize
if name:
self._shm = posix_ipc.SharedMemory(name)
else:
self._shm = posix_ipc.SharedMemory(None, posix_ipc.O_CREX, size=size)
self._buf = mmap.mmap(self._shm.fd, size)
self.array = np.ndarray(shape, dtype, self._buf, order='C')
@classmethod
def copy(cls, arr):
"""Creates a new SharedNDArray that is a copy of the given ndarray.
Args:
arr: The ndarray to copy.
Returns:
A new SharedNDArray object with the given ndarray's shape and data type and a copy of
its data.
Raises:
SharedNDArrayError: if an error occurs.
"""
new_shm = cls.zeros_like(arr)
new_shm.array[:] = arr
return new_shm
@classmethod
def zeros_like(cls, arr):
"""Creates a new zero-filled SharedNDArray with the shape and dtype of the given ndarray.
Raises:
SharedNDArrayError: if an error occurs.
"""
return cls(arr.shape, arr.dtype)
def unlink(self):
"""Marks the underlying shared for deletion.
This method should be called exactly once from one process. Failure to call it before all
processes exit will result in a memory leak! It will raise SharedNDArrayError if the
underlying shared memory was already marked for deletion from any process.
Raises:
SharedNDArrayError: if an error occurs.
"""
self._shm.unlink()
def __del__(self):
self._buf.close()
self._shm.close_fd()
def __getstate__(self):
return self.array.shape, self.array.dtype, self._shm.name
def __setstate__(self, state):
self.__init__(*state)
| {
"repo_name": "crowsonkb/shared_ndarray",
"path": "shared_ndarray/shared_ndarray.py",
"copies": "1",
"size": "3191",
"license": "mit",
"hash": 336968430974514050,
"line_mean": 33.311827957,
"line_max": 99,
"alpha_frac": 0.6436853651,
"autogenerated": false,
"ratio": 4.395316804407713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5539002169507713,
"avg_score": null,
"num_lines": null
} |
"""A pickle-based caching core for cachier."""
# This file is part of Cachier.
# https://github.com/shaypal5/cachier
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2016, Shay Palachy <shaypal5@gmail.com>
import os
import pickle # for local caching
from datetime import datetime
import threading
import portalocker # to lock on pickle cache IO
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
# Altenative: https://github.com/WoLpH/portalocker
from .base_core import _BaseCore
DEF_CACHIER_DIR = '~/.cachier/'
class _PickleCore(_BaseCore):
"""The pickle core class for cachier.
Parameters
----------
stale_after : datetime.timedelta, optional
See _BaseCore documentation.
next_time : bool, optional
See _BaseCore documentation.
pickle_reload : bool, optional
See core.cachier() documentation.
cache_dir : str, optional.
See core.cachier() documentation.
"""
class CacheChangeHandler(PatternMatchingEventHandler):
"""Handles cache-file modification events."""
def __init__(self, filename, core, key):
PatternMatchingEventHandler.__init__(
self,
patterns=["*" + filename],
ignore_patterns=None,
ignore_directories=True,
case_sensitive=False,
)
self.core = core
self.key = key
self.observer = None
self.value = None
def inject_observer(self, observer):
"""Inject the observer running this handler."""
self.observer = observer
def _check_calculation(self):
# print('checking calc')
entry = self.core.get_entry_by_key(self.key, True)[1]
# print(self.key)
# print(entry)
try:
if not entry['being_calculated']:
# print('stoping observer!')
self.value = entry['value']
self.observer.stop()
# else:
# print('NOT stoping observer... :(')
except TypeError:
self.value = None
self.observer.stop()
def on_created(self, event): # skipcq: PYL-W0613
self._check_calculation() # pragma: no cover
def on_modified(self, event): # skipcq: PYL-W0613
self._check_calculation()
def __init__(self, stale_after, next_time, reload, cache_dir):
_BaseCore.__init__(self, stale_after, next_time)
self.cache = None
self.reload = reload
self.cache_dir = DEF_CACHIER_DIR
if cache_dir is not None:
self.cache_dir = cache_dir
self.expended_cache_dir = os.path.expanduser(self.cache_dir)
self.lock = threading.RLock()
self.cache_fname = None
self.cache_fpath = None
def _cache_fname(self):
if self.cache_fname is None:
self.cache_fname = '.{}.{}'.format(
self.func.__module__, self.func.__name__
)
return self.cache_fname
def _cache_fpath(self):
if self.cache_fpath is None:
# print(EXPANDED_CACHIER_DIR)
if not os.path.exists(self.expended_cache_dir):
os.makedirs(self.expended_cache_dir)
self.cache_fpath = os.path.abspath(
os.path.join(
os.path.realpath(self.expended_cache_dir),
self._cache_fname(),
)
)
return self.cache_fpath
def _reload_cache(self):
with self.lock:
fpath = self._cache_fpath()
try:
with portalocker.Lock(fpath, mode='rb') as cache_file:
try:
self.cache = pickle.load(cache_file)
except EOFError:
self.cache = {}
except FileNotFoundError:
self.cache = {}
def _get_cache(self):
with self.lock:
if not self.cache:
self._reload_cache()
return self.cache
def _save_cache(self, cache):
with self.lock:
self.cache = cache
fpath = self._cache_fpath()
with portalocker.Lock(fpath, mode='wb') as cache_file:
pickle.dump(cache, cache_file, protocol=4)
self._reload_cache()
def get_entry_by_key(self, key, reload=False): # pylint: disable=W0221
with self.lock:
# print('{}, {}'.format(self.reload, reload))
if self.reload or reload:
self._reload_cache()
return key, self._get_cache().get(key, None)
def get_entry(self, args, kwds, hash_params):
key = args + tuple(sorted(kwds.items())) if hash_params is None else hash_params(args, kwds)
# print('key type={}, key={}'.format(type(key), key))
return self.get_entry_by_key(key)
def set_entry(self, key, func_res):
with self.lock:
cache = self._get_cache()
cache[key] = {
'value': func_res,
'time': datetime.now(),
'stale': False,
'being_calculated': False,
}
self._save_cache(cache)
def mark_entry_being_calculated(self, key):
with self.lock:
cache = self._get_cache()
try:
cache[key]['being_calculated'] = True
except KeyError:
cache[key] = {
'value': None,
'time': datetime.now(),
'stale': False,
'being_calculated': True,
}
self._save_cache(cache)
def mark_entry_not_calculated(self, key):
with self.lock:
cache = self._get_cache()
try:
cache[key]['being_calculated'] = False
self._save_cache(cache)
except KeyError:
pass # that's ok, we don't need an entry in that case
def wait_on_entry_calc(self, key):
with self.lock:
self._reload_cache()
entry = self._get_cache()[key]
if not entry['being_calculated']:
return entry['value']
event_handler = _PickleCore.CacheChangeHandler(
filename=self._cache_fname(), core=self, key=key
)
observer = Observer()
event_handler.inject_observer(observer)
observer.schedule(
event_handler, path=self.expended_cache_dir, recursive=True
)
observer.start()
observer.join(timeout=1.0)
if observer.is_alive():
# print('Timedout waiting. Starting again...')
return self.wait_on_entry_calc(key)
# print("Returned value: {}".format(event_handler.value))
return event_handler.value
def clear_cache(self):
self._save_cache({})
def clear_being_calculated(self):
with self.lock:
cache = self._get_cache()
for key in cache:
cache[key]['being_calculated'] = False
self._save_cache(cache)
| {
"repo_name": "shaypal5/cachier",
"path": "cachier/pickle_core.py",
"copies": "1",
"size": "7277",
"license": "mit",
"hash": 2973518793015874600,
"line_mean": 32.380733945,
"line_max": 100,
"alpha_frac": 0.5375841693,
"autogenerated": false,
"ratio": 4.1323111868256674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00004541738577527478,
"num_lines": 218
} |
"""API client classes"""
import logging
import requests
from collections import namedtuple
from urllib import parse
from ticketpy.query import (
AttractionQuery,
ClassificationQuery,
EventQuery,
VenueQuery
)
from ticketpy.model import Page
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
sf = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
sh.setFormatter(sf)
log.addHandler(sh)
class ApiClient:
"""ApiClient is the main wrapper for the Discovery API.
**Example**:
Get the first page result for venues matching keyword '*Tabernacle*':
.. code-block:: python
import ticketpy
client = ticketpy.ApiClient("your_api_key")
resp = client.venues.find(keyword="Tabernacle").one()
for venue in resp:
print(venue.name)
Output::
Tabernacle
The Tabernacle
Tabernacle, Notting Hill
Bethel Tabernacle
Revivaltime Tabernacle
...
Request URLs end up looking like:
http://app.ticketmaster.com/discovery/v2/events.json?apikey={api_key}
"""
root_url = 'https://app.ticketmaster.com'
url = 'https://app.ticketmaster.com/discovery/v2'
def __init__(self, api_key):
self.__api_key = None
self.api_key = api_key
self.events = EventQuery(api_client=self)
self.venues = VenueQuery(api_client=self)
self.attractions = AttractionQuery(api_client=self)
self.classifications = ClassificationQuery(api_client=self)
self.segment_by_id = self.classifications.segment_by_id
self.genre_by_id = self.classifications.genre_by_id
self.subgenre_by_id = self.classifications.subgenre_by_id
log.debug("Root URL: {}".format(self.url))
def search(self, method, **kwargs):
"""Generic API request
:param method: Search type (*events*, *venues*...)
:param kwargs: Search parameters (*venueId*, *eventId*,
*latlong*, etc...)
:return: ``PagedResponse``
"""
# Remove unfilled parameters, add apikey header.
# Clean up values that might be passed in multiple ways.
# Ex: 'includeTBA' might be passed as bool(True) instead of 'yes'
# and 'radius' might be passed as int(2) instead of '2'
kwargs = {k: v for (k, v) in kwargs.items() if v is not None}
updates = self.api_key
for k, v in kwargs.items():
if k in ['includeTBA', 'includeTBD', 'includeTest']:
updates[k] = self.__yes_no_only(v)
elif k in ['size', 'radius', 'marketId']:
updates[k] = str(v)
kwargs.update(updates)
log.debug(kwargs)
urls = {
'events': self.__method_url('events'),
'venues': self.__method_url('venues'),
'attractions': self.__method_url('attractions'),
'classifications': self.__method_url('classifications')
}
resp = requests.get(urls[method], params=kwargs)
return PagedResponse(self, self._handle_response(resp))
def _handle_response(self, response):
"""Raises ``ApiException`` if needed, or returns response JSON obj
Status codes
* 401 = Invalid API key or rate limit quota violation
* 400 = Invalid URL parameter
"""
if response.status_code == 200:
return self.__success(response)
elif response.status_code == 401:
self.__fault(response)
elif response.status_code == 400:
self.__error(response)
else:
self.__unknown_error(response)
@staticmethod
def __success(response):
"""Successful response, just return JSON"""
return response.json()
@staticmethod
def __error(response):
"""HTTP status code 400, or something with 'errors' object"""
rj = response.json()
error = namedtuple('error', ['code', 'detail', 'href'])
errors = [
error(err['code'], err['detail'], err['_links']['about']['href'])
for err in rj['errors']
]
log.error('URL: {}\nErrors: {}'.format(response.url, errors))
raise ApiException(response.status_code, errors, response.url)
@staticmethod
def __fault(response):
"""HTTP status code 401, or something with 'faults' object"""
rj = response.json()
fault_str = rj['fault']['faultstring']
detail = rj['fault']['detail']
log.error('URL: {}, Faultstr: {}'.format(response.url, fault_str))
raise ApiException(
response.status_code,
fault_str,
detail,
response.url
)
def __unknown_error(self, response):
"""Unexpected HTTP status code (not 200, 400, or 401)"""
rj = response.json()
if 'fault' in rj:
self.__fault(response)
elif 'errors' in rj:
self.__error(response)
else:
raise ApiException(response.status_code, response.text)
def get_url(self, link):
"""Gets a specific href from '_links' object in a response"""
# API sometimes return incorrectly-formatted strings, need
# to parse out parameters and pass them into a new request
# rather than implicitly trusting the href in _links
link = self._parse_link(link)
resp = requests.get(link.url, link.params)
return Page.from_json(self._handle_response(resp))
def _parse_link(self, link):
"""Parses link into base URL and dict of parameters"""
parsed_link = namedtuple('link', ['url', 'params'])
link_url, link_params = link.split('?')
params = self._link_params(link_params)
return parsed_link(link_url, params)
def _link_params(self, param_str):
"""Parse URL parameters from href split on '?' character"""
search_params = {}
params = parse.parse_qs(param_str)
for k, v in params.items():
search_params[k] = v[0]
search_params.update(self.api_key)
return search_params
@property
def api_key(self):
return self.__api_key
@api_key.setter
def api_key(self, api_key):
# Set this way by default to pass in request params
self.__api_key = {'apikey': api_key}
@staticmethod
def __method_url(method):
"""Formats a search method URL"""
return "{}/{}.json".format(ApiClient.url, method)
@staticmethod
def __yes_no_only(s):
"""Helper for parameters expecting ['yes', 'no', 'only']"""
s = str(s).lower()
if s in ['true', 'yes']:
s = 'yes'
elif s in ['false', 'no']:
s = 'no'
return s
class ApiException(Exception):
"""Exception thrown for API-related error messages"""
def __init__(self, *args):
super().__init__(*args)
class PagedResponse:
"""Iterates through API response pages"""
def __init__(self, api_client, response):
self.api_client = api_client
self.page = None
self.page = Page.from_json(response)
def limit(self, max_pages=5):
"""Retrieve X number of pages, returning a ``list`` of all entities.
Rather than iterating through ``PagedResponse`` to retrieve
each page (and its events/venues/etc), ``limit()`` will
automatically iterate up to ``max_pages`` and return
a flat/joined list of items in each ``Page``
:param max_pages: Max page requests to make before returning list
:return: Flat list of results from pages
"""
all_items = []
counter = 0
for pg in self:
if counter >= max_pages:
break
counter += 1
all_items += pg
return all_items
def one(self):
"""Get items from first page result"""
return [i for i in self.page]
def all(self):
"""Retrieves **all** pages in a result, returning a flat list.
Use ``limit()`` to restrict the number of page requests being made.
**WARNING**: Generic searches may involve *a lot* of pages...
:return: Flat list of results
"""
# TODO Rename this since all() is a built-in function...
return [i for item_list in self for i in item_list]
def __iter__(self):
yield self.page
next_url = self.page.links.get('next')
while next_url:
log.debug("Requesting page: {}".format(next_url))
pg = self.api_client.get_url(next_url)
next_url = pg.links.get('next')
yield pg
return
| {
"repo_name": "arcward/ticketpy",
"path": "ticketpy/client.py",
"copies": "1",
"size": "8797",
"license": "mit",
"hash": -1518361176928971000,
"line_mean": 32.8346153846,
"line_max": 78,
"alpha_frac": 0.581448221,
"autogenerated": false,
"ratio": 4.031622364802933,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0066037080713052115,
"num_lines": 260
} |
"API Client Tests"
import unittest
import fmapi
import logging
def enable_logging():
"Turn on debug logging"
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
class BasicTestSuite(unittest.TestCase):
"""Basic test cases."""
def test_gets(self): #pylint:disable=R0915
"Test everything"
#local_url = "http://127.0.0.1:5000/api"
#test_url = "http://fm.linzeb/api"
#client = fmapi.Client(url_base=local_url)
#client = fmapi.Client(url_base=test_url)
client = fmapi.Client()
# States
states = client.get_states()
assert states
state = states[0]
print(state.__dict__)
# Counties
counties = client.get_counties(state.state_code)
assert counties
county = counties[0]
print(county.__dict__)
# Tracts
tracts = client.get_tracts("12", "001")
assert tracts
tract = tracts[0]
print(tract.__dict__)
# Blocks
blocks = client.get_blocks("12", "001", "000200")
assert blocks
block = blocks[0]
print(block.__dict__)
# Tract Demographic Profile
dp = client.get_tract_profile("12", "001", "000200")
assert dp
print(dp.__dict__)
# Basic Demographics by County
bd = client.get_basic_county("12", "097")
assert bd
print(bd.__dict__)
# Zip Code Tabulation Areas
zctas = client.get_zctas("12")
assert zctas
z = zctas[0]
print(z.__dict__)
# Basic Demographics by Tract
bd = client.get_basic_tract("12", "001", "000301")
assert bd
print(bd.__dict__)
# Basic Demographics by Block
bd = client.get_basic_block("12", "001", "000200", "1001")
assert bd
print(bd.__dict__)
# Cities
cities = client.get_cities("FL")
assert cities
print(cities[0].__dict__)
# SF1 File 01 (Total Population)
sf = client.get_sf101("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 File 03
sf = client.get_sf103("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 File 04
sf = client.get_sf104("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 File 05
sf = client.get_sf105("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 File 06
sf = client.get_sf106("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 File 07
sf = client.get_sf107("12", "001", "000200", "1001")
assert sf
print(sf.__dict__)
# SF1 Docs
docs = client.get_sf1_docs("03")
assert docs
print(docs[0].__dict__)
# Geocode
latlon = client.geocode("1415 W Oak St, Kissimmee, FL 34741")
assert latlon
print(latlon.__dict__)
# Reverse Geocode
addr = client.revgeocode("28.30139130", "-81.41856570")
assert addr
print(addr.__dict__)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "FoundationMercury/fmpyapi",
"path": "fmapi/test.py",
"copies": "1",
"size": "3620",
"license": "mit",
"hash": 2416524580785028600,
"line_mean": 25.231884058,
"line_max": 73,
"alpha_frac": 0.5439226519,
"autogenerated": false,
"ratio": 3.6863543788187374,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47302770307187375,
"avg_score": null,
"num_lines": null
} |
"""API client wrapper.
"""
from functools import partial
from .urlpath import URLPath
class API(URLPath):
"""Add URL generation to an HTTP request client. Requires that the `client`
support HTTP verbs as lowercase methods. An example client would be the one
from Requests package.
"""
__attrs__ = [
'__client__',
'__pathway__',
'__params__',
'__append_slash__',
'__upper_methods__'
]
__http_methods__ = [
'head',
'options',
'get',
'post',
'put',
'patch',
'delete'
]
def __init__(self, client, pathway='', params=None,
append_slash=False, upper_methods=True):
super(API, self).__init__(pathway, params, append_slash)
self.__client__ = client
self.__upper_methods__ = upper_methods
# Dynamically set client proxy methods accessed during the getattr
# call.
self.__methods__ = [
method.upper() if self.__upper_methods__ else method
for method in self.__http_methods__
]
def __getattr__(self, attr):
if attr in self.__methods__:
# Proxy call to client method with url bound to first argument.
return partial(getattr(self.__client__, attr.lower()),
self.__getpathway__())
else:
return super(API, self).__getattr__(attr)
| {
"repo_name": "dgilland/ladder",
"path": "ladder/api.py",
"copies": "1",
"size": "1435",
"license": "mit",
"hash": 2467282833135233000,
"line_mean": 27.137254902,
"line_max": 79,
"alpha_frac": 0.5358885017,
"autogenerated": false,
"ratio": 4.442724458204334,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5478612959904334,
"avg_score": null,
"num_lines": null
} |
# api code for the reviewboard extension, inspired/copied from reviewboard
# post-review code.
import cookielib
import getpass
import mimetools
import os
import urllib2
import simplejson
import mercurial.ui
from urlparse import urljoin, urlparse
class APIError(Exception):
pass
class ReviewBoardError(Exception):
def __init__(self, json=None):
self.msg = None
self.code = None
self.tags = {}
if isinstance(json, str) or isinstance(json, unicode):
try:
json = simplejson.loads(json)
except:
self.msg = "Unknown error - non-JSON response"
return
if json:
if json.has_key('err'):
self.msg = json['err']['msg']
self.code = json['err']['code']
for key, value in json.items():
if isinstance(value,unicode) or isinstance(value,str) or \
key == 'fields':
self.tags[key] = value
def __str__(self):
if self.msg:
return ("%s (%s)" % (self.msg, self.code)) + \
''.join([("\n%s: %s" % (k, v)) for k,v in self.tags.items()])
else:
return Exception.__str__(self)
class Repository:
"""
Represents a ReviewBoard repository
"""
def __init__(self, id, name, tool, path):
self.id = id
self.name = name
self.tool = tool
self.path = path
class ReviewBoardHTTPPasswordMgr(urllib2.HTTPPasswordMgr):
"""
Adds HTTP authentication support for URLs.
Python 2.4's password manager has a bug in http authentication when the
target server uses a non-standard port. This works around that bug on
Python 2.4 installs. This also allows post-review to prompt for passwords
in a consistent way.
See: http://bugs.python.org/issue974757
"""
def __init__(self, reviewboard_url):
self.passwd = {}
self.rb_url = reviewboard_url
self.rb_user = None
self.rb_pass = None
def set_credentials(self, username, password):
self.rb_user = username
self.rb_pass = password
def find_user_password(self, realm, uri):
if uri.startswith(self.rb_url):
if self.rb_user is None or self.rb_pass is None:
print "==> HTTP Authentication Required"
print 'Enter username and password for "%s" at %s' % \
(realm, urlparse(uri)[1])
self.rb_user = mercurial.ui.ui().prompt('Username: ')
self.rb_pass = getpass.getpass('Password: ')
return self.rb_user, self.rb_pass
else:
# If this is an auth request for some other domain (since HTTP
# handlers are global), fall back to standard password management.
return urllib2.HTTPPasswordMgr.find_user_password(self, realm, uri)
class ApiRequest(urllib2.Request):
"""
Allows HTTP methods other than GET and POST to be used
"""
def __init__(self, method, *args, **kwargs):
self._method = method
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method
class HttpErrorHandler(urllib2.HTTPDefaultErrorHandler):
"""
Error handler that doesn't throw an exception for any code below 400.
This is necessary because RB returns 2xx codes other than 200 to indicate
success.
"""
def http_error_default(self, req, fp, code, msg, hdrs):
if code >= 400:
return urllib2.HTTPDefaultErrorHandler.http_error_default(self,
req, fp, code, msg, hdrs)
else:
result = urllib2.HTTPError( req.get_full_url(), code, msg, hdrs, fp)
result.status = code
return result
class HttpClient:
def __init__(self, url, proxy=None):
if not url.endswith('/'):
url = url + '/'
self.url = url
if 'APPDATA' in os.environ:
homepath = os.environ["APPDATA"]
elif 'USERPROFILE' in os.environ:
homepath = os.path.join(os.environ["USERPROFILE"], "Local Settings",
"Application Data")
elif 'HOME' in os.environ:
homepath = os.environ["HOME"]
else:
homepath = ''
self.cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
self._cj = cookielib.MozillaCookieJar(self.cookie_file)
self._password_mgr = ReviewBoardHTTPPasswordMgr(self.url)
self._opener = opener = urllib2.build_opener(
urllib2.ProxyHandler(proxy),
urllib2.UnknownHandler(),
urllib2.HTTPHandler(),
HttpErrorHandler(),
urllib2.HTTPErrorProcessor(),
urllib2.HTTPCookieProcessor(self._cj),
urllib2.HTTPBasicAuthHandler(self._password_mgr),
urllib2.HTTPDigestAuthHandler(self._password_mgr)
)
urllib2.install_opener(self._opener)
def set_credentials(self, username, password):
self._password_mgr.set_credentials(username, password)
def api_request(self, method, url, fields=None, files=None):
"""
Performs an API call using an HTTP request at the specified path.
"""
try:
rsp = self._http_request(method, url, fields, files)
if rsp:
return self._process_json(rsp)
else:
return None
except APIError, e:
rsp, = e.args
raise ReviewBoardError(rsp)
def has_valid_cookie(self):
"""
Load the user's cookie file and see if they have a valid
'rbsessionid' cookie for the current Review Board server. Returns
true if so and false otherwise.
"""
try:
parsed_url = urlparse(self.url)
host = parsed_url[1]
path = parsed_url[2] or '/'
# Cookie files don't store port numbers, unfortunately, so
# get rid of the port number if it's present.
host = host.split(":")[0]
print("Looking for '%s %s' cookie in %s" % \
(host, path, self.cookie_file))
self._cj.load(self.cookie_file, ignore_expires=True)
try:
cookie = self._cj._cookies[host][path]['rbsessionid']
if not cookie.is_expired():
print("Loaded valid cookie -- no login required")
return True
print("Cookie file loaded, but cookie has expired")
except KeyError:
print("Cookie file loaded, but no cookie for this server")
except IOError, error:
print("Couldn't load cookie file: %s" % error)
return False
def _http_request(self, method, path, fields, files):
"""
Performs an HTTP request on the specified path.
"""
if path.startswith('/'):
path = path[1:]
url = urljoin(self.url, path)
body = None
headers = {}
if fields or files:
content_type, body = self._encode_multipart_formdata(fields, files)
headers = {
'Content-Type': content_type,
'Content-Length': str(len(body))
}
try:
r = ApiRequest(method, url, body, headers)
data = urllib2.urlopen(r).read()
self._cj.save(self.cookie_file)
return data
except urllib2.URLError, e:
if not hasattr(e, 'code'):
raise
if e.code >= 400:
raise
else:
return ""
except urllib2.HTTPError, e:
raise ReviewBoardError(e.read())
def _process_json(self, data):
"""
Loads in a JSON file and returns the data if successful. On failure,
APIError is raised.
"""
rsp = simplejson.loads(data)
if rsp['stat'] == 'fail':
raise APIError, rsp
return rsp
def _encode_multipart_formdata(self, fields, files):
"""
Encodes data for use in an HTTP POST.
"""
BOUNDARY = mimetools.choose_boundary()
content = ""
fields = fields or {}
files = files or {}
for key in fields:
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key
content += "\r\n"
content += str(fields[key]) + "\r\n"
for key in files:
filename = files[key]['filename']
value = files[key]['content']
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"; " % key
content += "filename=\"%s\"\r\n" % filename
content += "\r\n"
content += value + "\r\n"
content += "--" + BOUNDARY + "--\r\n"
content += "\r\n"
content_type = "multipart/form-data; boundary=%s" % BOUNDARY
return content_type, content
class ApiClient:
def __init__(self, httpclient):
self._httpclient = httpclient
def _api_request(self, method, url, fields=None, files=None):
return self._httpclient.api_request(method, url, fields, files)
class Api20Client(ApiClient):
"""
Implements the 2.0 version of the API
"""
def __init__(self, httpclient):
ApiClient.__init__(self, httpclient)
self._repositories = None
self._requestcache = {}
def login(self, username=None, password=None):
self._httpclient.set_credentials(username, password)
return
def repositories(self):
if not self._repositories:
rsp = self._api_request('GET', '/api/repositories/?max-results=500')
self._repositories = [Repository(r['id'], r['name'], r['tool'],
r['path'])
for r in rsp['repositories']]
return self._repositories
def new_request(self, repo_id, fields={}, diff='', parentdiff=''):
req = self._create_request(repo_id)
self._set_request_details(req, fields, diff, parentdiff)
self._requestcache[req['id']] = req
return req['id']
def update_request(self, id, fields={}, diff='', parentdiff='', publish=True):
req = self._get_request(id)
self._set_request_details(req, fields, diff, parentdiff)
if publish:
self.publish(id)
def publish(self, id):
req = self._get_request(id)
drafturl = req['links']['draft']['href']
self._api_request('PUT', drafturl, {'public':'1'})
def _create_request(self, repo_id):
data = { 'repository': repo_id }
result = self._api_request('POST', '/api/review-requests/', data)
return result['review_request']
def _get_request(self, id):
if self._requestcache.has_key(id):
return self._requestcache[id]
else:
result = self._api_request('GET', '/api/review-requests/%s/' % id)
self._requestcache[id] = result['review_request']
return result['review_request']
def _set_request_details(self, req, fields, diff, parentdiff):
if fields:
drafturl = req['links']['draft']['href']
self._api_request('PUT', drafturl, fields)
if diff:
diffurl = req['links']['diffs']['href']
data = {'path': {'filename': 'diff', 'content': diff}}
if parentdiff:
data['parent_diff_path'] = \
{'filename': 'parent_diff', 'content': parentdiff}
self._api_request('POST', diffurl, {}, data)
class Api10Client(ApiClient):
"""
Implements the 1.0 version of the API
"""
def __init__(self, httpclient):
ApiClient.__init__(self, httpclient)
self._repositories = None
self._requests = None
def _api_post(self, url, fields=None, files=None):
return self._api_request('POST', url, fields, files)
def login(self, username=None, password=None):
if not username and not password and self._httpclient.has_valid_cookie():
return
if not username:
username = mercurial.ui.ui().prompt('Username: ')
if not password:
password = getpass.getpass('Password: ')
self._api_post('/api/json/accounts/login/', {
'username': username,
'password': password,
})
def repositories(self):
if not self._repositories:
rsp = self._api_post('/api/json/repositories/')
self._repositories = [Repository(r['id'], r['name'], r['tool'],
r['path'])
for r in rsp['repositories']]
return self._repositories
def requests(self):
if not self._requests:
rsp = self._api_post('/api/json/reviewrequests/all/')
self._requests = rsp['review_requests']
return self._requests
def new_request(self, repo_id, fields={}, diff='', parentdiff=''):
repository_path = None
for r in self.repositories():
if r.id == int(repo_id):
repository_path = r.path
break
if not repository_path:
raise ReviewBoardError, ("can't find repository with id: %s" % \
repo_id)
id = self._create_request(repository_path)
self._set_request_details(id, fields, diff, parentdiff)
return id
def update_request(self, id, fields={}, diff='', parentdiff='', publish=True):
request_id = None
for r in self.requests():
if r['id'] == int(id):
request_id = int(id)
break
if not request_id:
raise ReviewBoardError, ("can't find request with id: %s" % id)
self._set_request_details(request_id, fields, diff, parentdiff)
return request_id
def publish(self, id):
self._api_post('api/json/reviewrequests/%s/publish/' % id)
def _create_request(self, repository_path):
data = { 'repository_path': repository_path }
rsp = self._api_post('/api/json/reviewrequests/new/', data)
return rsp['review_request']['id']
def _set_request_field(self, id, field, value):
self._api_post('/api/json/reviewrequests/%s/draft/set/' %
id, { field: value })
def _upload_diff(self, id, diff, parentdiff=""):
data = {'path': {'filename': 'diff', 'content': diff}}
if parentdiff:
data['parent_diff_path'] = \
{'filename': 'parent_diff', 'content': parentdiff}
rsp = self._api_post('/api/json/reviewrequests/%s/diff/new/' % \
id, {}, data)
def _set_fields(self, id, fields={}):
for field in fields:
self._set_request_field(id, field, fields[field])
def _set_request_details(self, id, fields, diff, parentdiff):
self._set_fields(id, fields)
if diff:
self._upload_diff(id, diff, parentdiff)
if fields or diff:
self._save_draft(id)
def _save_draft(self, id):
self._api_post("/api/json/reviewrequests/%s/draft/save/" % id )
def make_rbclient(url, username, password, proxy=None, apiver=''):
httpclient = HttpClient(url, proxy)
if not httpclient.has_valid_cookie():
if not username:
username = mercurial.ui.ui().prompt('Username: ')
if not password:
password = getpass.getpass('Password: ')
httpclient.set_credentials(username, password)
if not apiver:
# Figure out whether the server supports API version 2.0
try:
httpclient.api_request('GET', '/api/')
apiver = '2.0'
except:
apiver = '1.0'
if apiver == '2.0':
return Api20Client(httpclient)
elif apiver == '1.0':
cli = Api10Client(httpclient)
cli.login(username, password)
return cli
else:
raise Exception("Unknown API version: %s" % apiver)
| {
"repo_name": "windix/mercurial-reviewboard",
"path": "reviewboard.py",
"copies": "1",
"size": "16400",
"license": "mit",
"hash": -5573626314460165000,
"line_mean": 33.6723044397,
"line_max": 82,
"alpha_frac": 0.5474390244,
"autogenerated": false,
"ratio": 4.170905391658189,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5218344416058189,
"avg_score": null,
"num_lines": null
} |
"""API creation module."""
from flask_restful import Api
from backend import resources
root_resources = set([resources.EditionResource,
resources.MetacardResource,
resources.PrintingResource,
resources.PartyResource,
resources.TransactionResource,
resources.CardResource,
resources.ListingResource,
resources.ShippingCostResource])
relational_resources = set([resources.PrintingResource,
resources.PriceTrendResource,
resources.PopularityResource,
resources.ExpectedTurnoverResource,
resources.PersonResource,
resources.CompanyResource,
resources.MCMUserResource,
resources.AddressResource,
resources.EvaluationResource,
resources.DeviationResource,
resources.ListingResource,
resources.ListingCardResource,
resources.PriceCheckResource,
resources.SalesResource,
resources.PurchasesResource])
resources_set = root_resources.union(relational_resources)
def init_api(app):
"""Init the API and add resources.
Args:
app (obj): A Flask application
Returns:
obj: A Flask-RESTful API
"""
api = Api(app)
for res in resources_set:
# Remove 'Resource' (8 letters) from class name and lowercase it
endpoint = res.__name__[:-8].lower()
urls = []
if res in root_resources:
urls.append('/{}'.format(endpoint))
urls.append('/{}/<string:id>'.format(endpoint))
if res in relational_resources:
urls.append('/<string:parent>/<string:id>/{}'.format(endpoint))
api.add_resource(res, *urls, endpoint=endpoint)
return api
| {
"repo_name": "mkarppan/RESTful-MtG",
"path": "backend/restful.py",
"copies": "1",
"size": "2082",
"license": "mit",
"hash": 6205232764023187000,
"line_mean": 36.8545454545,
"line_max": 75,
"alpha_frac": 0.5408261287,
"autogenerated": false,
"ratio": 5.507936507936508,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 55
} |
"""API data feature
Generates JSON for available information.
"""
import flask
import json
from database_setup import Category
from database_setup import Item
from flask import abort
from flask import jsonify
from sqlalchemy import asc, desc
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
# get database session
_DBSession = sessionmaker()
_DBH = _DBSession()
api_v1 = flask.Blueprint('api_v1', __name__)
@api_v1.route('/category-master-detail.json')
def api_v1_showCategoryMasterDetailJSON():
"""Return a list of categories and associated items.
Returns:
A list of set of tuples, each of which contains (id, label, items)
id: category's unique id
label: the category label
items: a dictionary of tuples, each of which contains (
id, label, date, description, iamge_url, category_id)
id: item's unique id
label: item label
date: creation date
description: item's description
iamge_url: URL to the item image
category_id: the associated category id
"""
categories = _DBH.query(Category).all()
return jsonify(Categories=[category.serializeExpanded for category in categories])
@api_v1.route('/category.json')
def api_v1_listCategoryJSON():
"""Return a list of categories.
Returns:
A list of set of tuples, each of which contains (id, label, items)
id: category's unique id
label: the category label
"""
categories = _DBH.query(Category).all()
return jsonify(Categories=[category.serialize for category in categories])
@api_v1.route('/category/<string:category_label>.json')
def api_v1_showCategoryJSON(category_label):
"""Return respective category and associated items.
Returns:
A tuple containing (id, label, items)
id: category's unique id
label: the category label
items: a dictionary of tuples, each of which contains (
id, label, date, description, iamge_url, category_id)
id: item's unique id
label: item label
date: creation date
description: item's description
iamge_url: URL to the item image
category_id: the associated category id
"""
try:
category = _DBH.query(Category).filter_by(label=category_label).one()
except NoResultFound:
return abort(404)
return jsonify(Category=category.serializeExpanded)
@api_v1.route('/category/<string:category_label>/<string:item_label>.json')
def api_v1_showCategoryItemJSON(category_label, item_label):
"""Return category item information.
Returns:
A dictionary of tuples, each of which contains (
id, label, date, description, iamge_url, category_id)
id: item's unique id
label: item label
date: creation date
description: item's description
iamge_url: URL to the item image
category_id: the associated category id
"""
try:
category = _DBH.query(Category).filter_by(label=category_label).one()
except NoResultFound:
return abort(404)
try:
item = _DBH.query(Item).filter_by(label=item_label, category_id=category.id).one()
except NoResultFound:
return abort(404)
return jsonify(Item=item.serialize)
| {
"repo_name": "novastorm/udacity-item-catalog",
"path": "vagrant/catalog/routes/api_v1.py",
"copies": "1",
"size": "3362",
"license": "bsd-2-clause",
"hash": 5428661264353907000,
"line_mean": 29.5636363636,
"line_max": 90,
"alpha_frac": 0.6653777513,
"autogenerated": false,
"ratio": 4.120098039215686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5285475790515686,
"avg_score": null,
"num_lines": null
} |
'''API Definition for HART Manager XML API'''
import ApiDefinition
import xmlutils
import re
# Add a log handler for the HART Manager
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('HartManager')
log.setLevel(logging.INFO)
log.addHandler(NullHandler())
##
# \ingroup ApiDefinition
#
class HartMgrDefinition(ApiDefinition.ApiDefinition):
'''
\brief API definition for the HART manager.
\note This class inherits from ApiDefinition. It redefines the attributes of
its parent class, but inherits the methods.
'''
FIELDS = 'unnamed'
STRING = ApiDefinition.FieldFormats.STRING
BOOL = ApiDefinition.FieldFormats.BOOL
INT = ApiDefinition.FieldFormats.INT
INTS = ApiDefinition.FieldFormats.INTS
FLOAT = ApiDefinition.FieldFormats.FLOAT
HEXDATA = ApiDefinition.FieldFormats.HEXDATA
RC = ApiDefinition.ApiDefinition.RC
SUBID1 = ApiDefinition.ApiDefinition.SUBID1
LIST = 'list'
# Enumerations
# fieldOptions is a list of [ value, description, ?? ]
fieldOptions = {
RC : [
[0x0, 'OK', ''],
# ...
],
'bool' : [
['true', 'true', ''],
['false', 'false', ''],
],
'appDomain' : [
['maintenance', 'maintenance', ''],
],
'packetPriority' : [
['low', 'low', ''],
['high', 'high', ''],
],
'pipeDirection' : [
['UniUp', 'upstream', ''],
['UniDown', 'downstream', ''],
['Bi', 'bidirectional', ''],
],
'moteState' : [
['Idle', 'idle', ''],
['Lost', 'lost', ''],
['Joining', 'joining', ''],
['Operational', 'operational', ''],
['Disconnecting', 'disconnecting', ''],
],
'pathDirection' : [
['all', 'all', ''],
['upstream', 'upstream', ''],
['downstream', 'downstream', ''],
['unused', 'unused', ''],
],
'bandwidthProfile' : [
['Manual', 'manual profile', ''],
['P1', 'normal profile', ''],
['P2', 'low-power profile', ''],
],
'securityMode' : [
['acceptACL', 'Accept ACL', ''],
['acceptCommonJoinKey', 'Accept common join key', '']
],
'userPrivilege' : [
['viewer', 'viewer', ''],
['user', 'user', ''],
['superuser', 'superuser', ''],
],
'onOff' : [
['on', 'on', ''],
['off', 'off', ''],
],
'resetObject' : [
['network', 'network', ''],
['system', 'system', ''],
['stat', 'statistics', ''],
['eventLog', 'eventLog', ''],
],
'resetMote' : [
['mote', 'mote', ''],
],
'statPeriod': [
['current', 'current', ''],
['lifetime', 'lifetime', ''],
['short', 'short', ''],
['long', 'long', ''],
],
'advertisingStatus': [
['on', 'on', ''],
['off', 'off', ''],
['pending', 'pending', ''],
],
'pipeStatus': [
['off', 'off', ''],
['pending', 'Pipe activation pending', ''],
['on_bi', 'Bidirection pipe on', ''],
['on_up', 'Upstream pipe on', ''],
['on_down', 'Downstream pipe on', ''],
],
'locationTag': [
['supported', 'supported', ''],
['not supported', 'not supported', ''],
],
'redundancyMode': [
['standalone', 'standalone', ''],
['transToMaster', 'Transitioning to master', ''],
['transToSlave', 'Transitioning to slave', ''],
['master', 'master', ''],
['slave', 'slave', ''],
['failed', 'Manager failed', ''],
],
'redundancyPeerStatus': [
['unknown', 'unknown', ''],
['connected', 'connected', ''],
['synchronized', 'synchronized', ''],
],
'channelType': [
['cli', 'Manager CLI', ''],
['config', 'API control', ''],
['notif', 'API notifications', ''],
],
}
# ----------------------------------------------------------------------
# Notifications
eventNotifications = [
{
'id' : 'sysConnect',
'name' : 'UserConnect',
'description': '',
'response' : {
'FIELDS': [
['channel', STRING, 16, 'channelType'],
['ipAddr', STRING, 16, None],
['userName', STRING, 32, None],
],
},
},
{
'id' : 'sysDisconnect',
'name' : 'UserDisconnect',
'description': '',
'response' : {
'FIELDS': [
['channel', STRING, 16, 'channelType'],
['ipAddr', STRING, 16, None],
['userName', STRING, 32, None],
],
},
},
{
'id' : 'sysManualMoteReset',
'name' : 'ManualMoteReset',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'sysManualMoteDelete',
'name' : 'ManualMoteDelete',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'sysManualMoteDecommission',
'name' : 'ManualMoteDecommission',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'sysManualNetReset',
'name' : 'ManualNetReset',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
],
},
},
{
'id' : 'sysManualDccReset',
'name' : 'ManualDccReset',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
],
},
},
{
'id' : 'sysManualStatReset',
'name' : 'ManualStatReset',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
],
},
},
{
'id' : 'sysConfigChange',
'name' : 'ConfigChange',
'description': '',
'response' : {
'FIELDS': [
['userName', STRING, 32, None],
['objectType', STRING, 32, None], # TODO: enum
['objectId', STRING, 32, None],
],
},
},
{
'id' : 'sysBootUp',
'name' : 'BootUp',
'description': '',
'response' : {
'FIELDS': [
# None
],
},
},
{
'id' : 'netReset',
'name' : 'NetworkReset',
'description': '',
'response' : {
'FIELDS': [
# None
],
},
},
{
'id' : 'sysCmdFinish',
'name' : 'CommandFinished',
'description': '',
'response' : {
'FIELDS': [
['callbackId', INT, 4, None],
['objectType', STRING, 32, None], # TODO: enum
['macAddr', STRING, 32, None],
['resultCode', INT, 4, None],
],
},
},
{
'id' : 'netPacketSent',
'name' : 'PacketSent',
'description': '',
'response' : {
'FIELDS': [
['callbackId', INT, 4, None],
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'netMoteJoin',
'name' : 'MoteJoin',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
['userData', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteLive',
'name' : 'MoteLive',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteQuarantine',
'name' : 'MoteQuarantine',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteJoinQuarantine',
'name' : 'MoteJoinQuarantine',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
['userData', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteUnknown',
'name' : 'MoteUnknown',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteDisconnect',
'name' : 'MoteDisconnect',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteJoinFailure',
'name' : 'MoteJoinFailure',
'description': '',
'response' : {
'FIELDS': [
['macAddr', STRING, 32, None],
['reason', STRING, 64, None], # TODO: length
],
},
},
{
'id' : 'netMoteInvalidMIC',
'name' : 'InvalidMIC',
'description': '',
'response' : {
'FIELDS': [
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'netPathCreate',
'name' : 'PathCreate',
'description': '',
'response' : {
'FIELDS': [
['pathId', INT, 4, None],
['moteAMac', STRING, 32, None],
['moteBMac', STRING, 32, None],
],
},
},
{
'id' : 'netPathDelete',
'name' : 'PathDelete',
'description': '',
'response' : {
'FIELDS': [
['pathId', INT, 4, None],
['moteAMac', STRING, 32, None],
['moteBMac', STRING, 32, None],
],
},
},
{
'id' : 'netPathActivate',
'name' : 'PathActivate',
'description': '',
'response' : {
'FIELDS': [
['pathId', INT, 4, None],
['moteAMac', STRING, 32, None],
['moteBMac', STRING, 32, None],
],
},
},
{
'id' : 'netPathDeactivate',
'name' : 'PathDeactivate',
'description': '',
'response' : {
'FIELDS': [
['pathId', INT, 4, None],
['moteAMac', STRING, 32, None],
['moteBMac', STRING, 32, None],
],
},
},
{
'id' : 'netPathAlert',
'name' : 'PathAlert',
'description': '',
'response' : {
'FIELDS': [
['pathId', INT, 4, None],
['moteAMac', STRING, 32, None],
['moteBMac', STRING, 32, None],
],
},
},
{
'id' : 'netPipeOn',
'name' : 'PipeOn',
'description': '',
'response' : {
'FIELDS': [
['macAddr', STRING, 32, None],
['allocatedPipePkPeriod', INT, 4, None],
],
},
},
{
'id' : 'netPipeOff',
'name' : 'PipeOff',
'description': '',
'response' : {
'FIELDS': [
['macAddr', STRING, 32, None],
],
},
},
{
'id' : 'netServiceDenied',
'name' : 'ServiceDenied',
'description': '',
'response' : {
'FIELDS': [
['serviceId', INT, 4, None],
['requestingMacAddr', STRING, 32, None],
['peerMacAddr', STRING, 32, None],
['appDomain', STRING, 32, 'appDomain'],
['isSource', BOOL, 1, None],
['isSink', BOOL, 1, None],
['isIntermittent', BOOL, 1, None],
['period', INT, 4, None],
],
},
},
{
'id' : 'netPingReply',
'name' : 'PingReply',
'description': '',
'response' : {
'FIELDS': [
['macAddr', STRING, 32, None],
['callbackId', INT, 4, None],
['latency', INT, 4, None],
['temperature', FLOAT, 8, None],
['voltage', FLOAT, 8, None],
['hopCount', INT, 4, None],
],
},
},
{
'id' : 'netTransportTimeout',
'name' : 'TransportTimeout',
'description': '',
'response' : {
'FIELDS': [
['srcMacAddr', STRING, 32, None],
['destMacAddr', STRING, 32, None],
['timeoutType', STRING, 32, None], # TODO: timeout type
['callbackId', INT, 4, None],
],
},
},
# TODO: redundancy events: sysRdntModeChange, sysRdntPeerStatusChange
# TODO: alarm open and close have sub-events
]
measurementNotifications = [
{
'id' : 'location',
'name' : 'Location',
'description': '',
'response' : {
'FIELDS': [
['ver', INT, 1, None],
['asn', INT, 8, None],
['src', STRING, 32, None],
['dest', STRING, 32, None],
['payload', HEXDATA, None, None],
],
},
},
]
notifications = [
{
'id' : 'event',
'name' : 'event',
'description': '',
'response' : {
'FIELDS': [
['timeStamp', INT, 8, None],
['eventId', INT, 4, None],
[SUBID1, INT, 1, None],
]
},
'subCommands': eventNotifications,
'deserializer': 'parse_eventNotif',
},
{
'id' : 'data',
'name' : 'data',
'description': '',
'response' : {
'FIELDS': [
['moteId', INT, 4, None],
['macAddr', STRING, 32, None],
['time', INT, 8, None],
['payload', HEXDATA, None, None],
['payloadType', INT, 1, None],
['isReliable', BOOL, 1, None],
['isRequest', BOOL, 1, None],
['isBroadcast', BOOL, 1, None],
['callbackId', INT, 4, None],
# counter field added in 4.1.0.2
['counter', INT, 4, None],
]
},
'deserializer': 'parse_dataNotif',
},
{
'id' : 'measurement',
'name' : 'measurement',
'description': '',
'response' : {
'FIELDS': [
[SUBID1, INT, 1, None],
]
},
'subCommands': measurementNotifications,
},
{
'id' : 'cli',
'name' : 'cli',
'description': '',
'response' : {
'FIELDS': [
['time', INT, 8, None],
['message', STRING, 128, None],
]
},
},
{
'id' : 'log',
'name' : 'log',
'description': '',
'response' : {
'FIELDS': [
['time', INT, 8, None],
['severity', STRING, 16, None],
['message', STRING, 128, None],
]
},
},
{
'id' : 'stdMoteReport',
'name' : 'stdMoteReport',
'description': '',
'response' : {
'FIELDS': [
['time', INT, 8, None],
['macAddr', STRING, 16, None],
['payload', HEXDATA, None, None],
]
},
},
{
'id' : 'vendorMoteReport',
'name' : 'vendorMoteReport',
'description': '',
'response' : {
'FIELDS': [
['time', INT, 8, None],
['macAddr', STRING, 16, None],
['payload', HEXDATA, None, None],
]
},
},
]
# Notification parsing
def parse_dataNotif(self, notif_str, notif_fields):
data_dict = self._parse_xmlobj(notif_str, 'data', notif_fields)
log.debug('DATA: %s' % str(data_dict))
# reconvert payload type as a hex value
data_dict['payloadType'] = int(str(data_dict['payloadType']), 16)
# set default values for any fields that aren't present
DEFAULTS = (('isRequest', False),
('isReliable', False),
('isBroadcast', False),
('callbackId', 0))
for f, v in DEFAULTS:
if not data_dict[f]:
data_dict[f] = v
return (['data'], data_dict)
def parse_eventNotif(self, notif_str, notif_fields):
obj_dict = self._parse_xmlobj(notif_str, 'event', None)
log.debug('EVENT: %s' % str(obj_dict))
event_name = ['event']
event_dict = {}
for event_attr, val in obj_dict.items():
if type(val) is dict:
event_name += [self.subcommandIdToName(self.NOTIFICATION, event_name, event_attr)]
subevent_fields = self.getResponseFields(self.NOTIFICATION, event_name)
event_dict.update(self._xml_parse_fieldset(val, subevent_fields))
else:
# we assume that all event fields are defined
field = [f for f in notif_fields if f.name == event_attr][0]
event_dict[event_attr] = self._xml_parse_field(val, field)
return (event_name, event_dict)
def parse_notif(self, notif_name, notif_str):
notif_metadata = self.getDefinition(self.NOTIFICATION, notif_name)
notif_fields = self.getResponseFields(self.NOTIFICATION, notif_name)
if notif_metadata.has_key('deserializer'):
deserialize_func = getattr(self, notif_metadata['deserializer'])
notif_name, notif_dict = deserialize_func(notif_str, notif_fields)
else:
notif_dict = self._parse_xmlobj(notif_str, notif_name[0], notif_fields)
return (notif_name, notif_dict)
# XML-RPC Serializer
def _xmlrpc_format_field(self, field_value, field_metadata):
if field_metadata[1] == self.HEXDATA:
return ''.join(['%02X' % b for b in field_value])
else:
return field_value
def default_serializer(self, commandArray, fields):
cmd_metadata = self.getDefinition(self.COMMAND, commandArray)
param_list = []
# for each field in the input parameters, look up the value in cmd_params
for p in cmd_metadata['request']:
param_name = p[0]
# format the parameter by type
param_list.append(self._xmlrpc_format_field(fields[param_name], p))
# param_list = [self.format_field(fields[f[0]], f) for f in cmd_metadata['request']]
return param_list
# XML-RPC Deserializer
def _xml_parse_field(self, str_value, field_metadata):
if field_metadata.format in [self.INT, self.INTS]:
return int(str_value)
elif field_metadata.format == self.FLOAT:
return float(str_value)
elif field_metadata.format == self.BOOL:
if str_value.lower() == 'true':
return True
else:
return False
elif field_metadata.format == self.HEXDATA:
returnVal = [int(str_value[i:i+2], 16) for i in range(0, len(str_value), 2)]
return returnVal
else:
return str_value
def _xml_parse_fieldset(self, obj_dict, fields_metadata):
'Filter and parse fields in obj_dict'
filtered_dict = {}
for field in fields_metadata:
try:
field_str = obj_dict[field.name]
filtered_dict[field.name] = self._xml_parse_field(field_str, field)
except KeyError:
# some fields are not always present (especially in Statistics)
filtered_dict[field.name] = ''
return filtered_dict
def _parse_xmlobj(self, xml_doc, base_element, fields_metadata, isArray = False):
log.debug('Parsing XML: %s %s', base_element, xml_doc)
aFull_resp = xmlutils.parse_xml_obj(xml_doc, base_element, fields_metadata)
aRes = []
for full_resp in aFull_resp :
if fields_metadata:
# parse each field listed in the fields_metadata
res = self._xml_parse_fieldset(full_resp, fields_metadata)
else:
res = full_resp
if not isArray :
return res
aRes.append(res)
return aRes
def default_deserializer(self, cmd_metadata, xmlrpc_resp):
resp = {}
#resp = {'_raw_': xmlrpc_resp}
resp_fields = self.getResponseFields(self.COMMAND, [cmd_metadata['name']])
if cmd_metadata['response'].has_key(self.FIELDS):
# unnamed fields are processed in order
# note: special case the single return value
if len(resp_fields) is 1:
resp[resp_fields[0].name] = self._xml_parse_field(xmlrpc_resp, resp_fields[0])
else:
for i, field in enumerate(resp_fields):
resp[field.name] = self._xml_parse_field(xmlrpc_resp[i], field)
elif cmd_metadata['id'] in ['getConfig', 'setConfig'] :
# default getConfig parser
# TODO: need an ApiDefinition method to get the response object name
resp_obj = cmd_metadata['response'].keys()[0]
isArray = False
if ('isResponseArray' in cmd_metadata) :
isArray = cmd_metadata['isResponseArray']
resp = self._parse_xmlobj(xmlrpc_resp, resp_obj, resp_fields, isArray)
return resp
def deserialize(self, cmd_name, xmlrpc_resp):
'''\brief Returns the XML-RPC response as a dict
\returns A tuple of commandName and the response dictionary,
which contains each of the fields of the response.
'''
cmd_metadata = self.getDefinition(self.COMMAND, cmd_name)
if cmd_metadata.has_key('deserializer'):
deserializer = getattr(self, cmd_metadata['deserializer'])
else:
deserializer = self.default_deserializer
resp = deserializer(cmd_metadata, xmlrpc_resp)
return resp
# ----------------------------------------------------------------------
# Command-specific serialization methods
# (must be defined ahead of commands)
def serialize_getConfig(self, commandArray, cmd_params):
'''\brief Returns an array of parameters for a typical getConfig query
'''
cmd_metadata = self.getDefinition(self.COMMAND, commandArray)
prefix = []
if 'serializerParam' in cmd_metadata:
prefix = cmd_metadata['serializerParam']
config_query = xmlutils.dict_to_xml(cmd_params, prefix)
return ['all', config_query]
def serialize_getNetworkStats(self, commandArray, cmd_params):
stat_query = self._build_stat_set(cmd_params['period'], cmd_params['index'])
return ['all', '<config><Network><Statistics>%s</Statistics></Network></config>' % stat_query]
def serialize_getMote(self, commandArray, cmd_params):
config_doc = '<config><Motes><Mote><macAddr>%s</macAddr></Mote></Motes></config>' % (cmd_params['macAddr'])
return ['all', config_doc]
def serialize_getMoteStats(self, commandArray, cmd_params):
stat_query = self._build_stat_set(cmd_params['period'], cmd_params['index'])
config_doc = '<config><Motes><Mote><macAddr>%s</macAddr><Statistics>%s</Statistics></Mote></Motes></config>' % (cmd_params['macAddr'], stat_query)
return ['all', config_doc]
def serialize_getPath(self, commandArray, cmd_params):
config_doc = '<config><Paths><Path><moteMac>%s</moteMac></Path></Paths></config>' % (cmd_params['moteMac'])
return ['all', config_doc]
def serialize_getPathStats(self, commandArray, cmd_params):
stat_query = self._build_stat_set(cmd_params['period'], cmd_params['index'])
config_doc = '<config><Paths><Path><pathId>%s</pathId><Statistics>%s</Statistics></Path></Paths></config>' % (cmd_params['pathId'], stat_query)
return ['all', config_doc]
def serialize_getUser(self, commandArray, cmd_params):
config_doc = '<config><Users><User><userName>%s</userName></User></Users></config>' % (cmd_params['userName'], )
return ['all', config_doc]
def _configDoc_format_field(self, field_value, field_metadata):
if field_metadata[1] == self.HEXDATA:
return ''.join(['%02X' % b for b in field_value])
elif field_metadata[1] == self.BOOL:
return 'true' if field_value else 'false'
else:
return str(field_value)
def serialize_setConfig(self, commandArray, fields) :
cmd_metadata = self.getDefinition(self.COMMAND, commandArray)
prefix = []
if 'serializerParam' in cmd_metadata :
prefix = cmd_metadata['serializerParam']
param_dict = {}
# for each field in the input parameters, look up the value in cmd_params
for p in cmd_metadata['request']:
param_name = p[0]
# format the parameter by type
param_dict[param_name] = self._configDoc_format_field(fields[param_name], p)
config_doc = xmlutils.dict_to_xml(param_dict, prefix)
return [config_doc]
def _build_stat_set(self, period, index = 0):
STAT_PERIOD_QUERY_TMPL = '<{0}Set><{0}><index>{1}</index></{0}></{0}Set>'
if period in ['current']:
return '<statCur/>'
elif period in ['lifetime']:
return '<lifetime/>'
elif period in ['short']:
return STAT_PERIOD_QUERY_TMPL.format('stat15Min', index)
elif period in ['long']:
return STAT_PERIOD_QUERY_TMPL.format('stat1Day', index)
else:
raise RuntimeError('invalid stat period: %s', period)
# ----------------------------------------------------------------------
# Command-specific deserialization methods
# (must be defined ahead of commands)
def deserialize_getStats(self, cmd_metadata, xmlrpc_resp):
net_stats = {}
fields = self.getResponseFields(self.COMMAND, [cmd_metadata['name']])
# parse the Statistics element
resp_dict = self._parse_xmlobj(xmlrpc_resp, 'Statistics', None)
# detect the statistics period
stat_dict = {}
if 'statCur' in resp_dict:
stat_dict = resp_dict['statCur']
elif 'lifetime' in resp_dict:
stat_dict = resp_dict['lifetime']
elif 'stat15MinSet' in resp_dict:
stat_dict = resp_dict['stat15MinSet']['stat15Min']
elif 'stat1DaySet' in resp_dict:
stat_dict = resp_dict['stat1DaySet']['stat1Day']
# if there are no statistics for the requested period, stat_dict may be a string
if type(stat_dict) != dict:
stat_dict = {}
# fill in the statistics fields
for field in fields:
try:
field_str = stat_dict[field.name]
net_stats[field.name] = self._xml_parse_field(field_str, field)
except KeyError:
# some fields are not always present (especially in Statistics)
net_stats[field.name] = '' # default value
return net_stats
def deserialize_getSourceRoute(self, cmd_metadata, xmlrpc_resp):
net_stats = {}
fields = self.getResponseFields(self.COMMAND, [cmd_metadata['name']])
# parse the Statistics element
resp_dict = self._parse_xmlobj(xmlrpc_resp, 'SourceRoute', None)
# Ug. deserialization for this case is heavily dependant on response structure
for path in ['primaryPath', 'secondaryPath']:
if path in resp_dict and 'macAddr' in resp_dict[path]:
resp_dict[path] = resp_dict[path]['macAddr']
else:
resp_dict[path] = []
return resp_dict
# Commands
commands = [
# Get Config commands
# TODO: use serializer_getConfig instead of command-specific serializers
{
'id' : 'getConfig',
'name' : 'getSystem',
'description': 'Retrieves system-level information',
'request' : [
],
'response' : {
'System': [
['systemName', STRING, 32, None],
['location', STRING, 32, None],
['swRev', STRING, 32, None],
['hwModel', STRING, 32, None],
['hwRev', STRING, 32, None],
['serialNumber', STRING, 32, None],
['time', INT, 8, None],
['startTime', INT, 8, None],
['cliTimeout', INT, 4, None],
['controllerSwRev', STRING, 32, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'System'],
},
{
'id' : 'getConfig',
'name' : 'getNetwork',
'description': 'Retrieves network configuration parameters',
'request' : [
],
'response' : {
'Network': [
['netName', STRING, 16, None],
['networkId', INT, 4, None],
['maxMotes', INT, 4, None],
['numMotes', INT, 4, None],
['optimizationEnable', BOOL, 1, None],
['accessPointPA', BOOL, 1, None],
['ccaEnabled', BOOL, 1, None],
['requestedBasePkPeriod', INT, 4, None],
['minServicesPkPeriod', INT, 4, None],
['minPipePkPeriod', INT, 4, None],
['bandwidthProfile', STRING, 16, 'bandwidthProfile'],
['manualUSFrameSize', INT, 4, None],
['manualDSFrameSize', INT, 4, None],
['manualAdvFrameSize', INT, 4, None],
['netQueueSize', INT, 4, None],
['userQueueSize', INT, 4, None],
['locationMode', STRING, 16, 'onOff'],
# backbone parameters added in 4.1.0.3
['backboneEnabled', BOOL, 1, None],
['backboneSize', INT, 4, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Network'],
},
{
'id' : 'getConfig',
'name' : 'getNetworkStatistics',
'description': 'Get the Network Statistics',
'request' : [
['period', STRING, 32, 'statPeriod'],
['index', INT, 4, None], # TODO: optional
],
'response' : {
'NetworkStatistics': [
['index', INT, 4, None],
['startTime', INT, 8, None], # milliseconds
['netLatency', INT, 4, None], # milliseconds
['netReliability', FLOAT, 0, None], # percentage
['netPathStability', FLOAT, 0, None], # percentage
['lostUpstreamPackets', INT, 4, None], # lifetime only ?
],
},
'serializer' : 'serialize_getNetworkStats',
'deserializer' : 'deserialize_getStats',
},
{
'id' : 'getConfig',
'name' : 'getMote',
'description': '',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
'Mote': [
['moteId', INT, 4, None],
['macAddr', STRING, 25, None],
['name', STRING, 16, None],
['state', STRING, 16, 'moteState'],
['numJoins', INT, 4, None],
['joinTime', INT, 8, None], # TODO: date time
['reason', STRING, 16, None],
['isAccessPoint', BOOL, 1, None],
['powerSource', STRING, 16, None], # TODO: enum
['dischargeCurrent', INT, 4, None],
['dischargeTime', INT, 4, None],
['recoveryTime', INT, 4, None],
['enableRouting', BOOL, 1, None],
['productName', STRING, 16, None],
['hwModel', INT, 1, None],
['hwRev', INT, 1, None],
['swRev', STRING, 16, None],
['voltage', FLOAT, 8, None],
['numNeighbors', INT, 4, None],
['needNeighbor', BOOL, 1, None],
['goodNeighbors', INT, 4, None],
['allocatedPkPeriod', INT, 4, None],
['allocatedPipePkPeriod', INT, 4, None],
['pipeStatus', STRING, 4, 'pipeStatus'],
['advertisingStatus', STRING, 4, 'advertisingStatus'],
['locationTag', STRING, 16, 'locationTag'],
],
},
'serializer' : 'serialize_getMote',
},
{
'id' : 'getConfig',
'name' : 'getMoteStatistics',
'description': 'Get the Mote Statistics',
'request' : [
['macAddr', STRING, 25, None],
['period', STRING, 32, 'statPeriod'],
['index', INT, 4, None], # TODO: optional
],
'response' : {
'MoteStatistics': [
['index', INT, 4, None],
['startTime', INT, 8, None], # milliseconds
['avgLatency', INT, 4, None], # milliseconds
['reliability', FLOAT, 0, None], # percentage
['numJoins', INT, 4, None],
['voltage', FLOAT, 4, None], # volts
['chargeConsumption', INT, 4, None], # mC
['temperature', FLOAT, 4, None], # deg C
# added in Manager 4.1.0.2
['numLostPackets', INT, 4, None],
# added in Manager 4.1.0.11
['latencyToMote', INT, 4, None],
],
},
'serializer' : 'serialize_getMoteStats',
'deserializer' : 'deserialize_getStats',
},
{
'id' : 'getConfig',
'name' : 'getSourceRoute',
'description': 'Get the Source Route for a specific Mote',
'request' : [
['destMacAddr', STRING, 25, None],
],
'response' : {
'SourceRoute': [
['destMacAddr', STRING, 25, None],
['primaryPath', LIST, 16, None],
['secondaryPath', LIST, 16, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'SourceRoutes', 'SourceRoute'],
'deserializer' : 'deserialize_getSourceRoute',
},
# getMotes -- return LIST of motess
{
'id' : 'getConfig',
'name' : 'getMotes',
'description': '''Get the list of Motes''',
'request' : [
],
'response' : {
'Mote': [
['moteId', INT, 4, None],
['macAddr', STRING, 25, None],
['name', STRING, 16, None],
['state', STRING, 16, 'moteState'],
['numJoins', INT, 4, None],
['joinTime', INT, 8, None], # TODO: date time
['reason', STRING, 16, None],
['isAccessPoint', BOOL, 1, None],
['powerSource', STRING, 16, None], # TODO: enum
['dischargeCurrent', INT, 4, None],
['dischargeTime', INT, 4, None],
['recoveryTime', INT, 4, None],
['enableRouting', BOOL, 1, None],
['productName', STRING, 16, None],
['hwModel', INT, 1, None],
['hwRev', INT, 1, None],
['swRev', STRING, 16, None],
['voltage', FLOAT, 8, None],
['numNeighbors', INT, 4, None],
['needNeighbor', BOOL, 1, None],
['goodNeighbors', INT, 4, None],
['allocatedPkPeriod', INT, 4, None],
['allocatedPipePkPeriod', INT, 4, None],
['pipeStatus', STRING, 4, 'pipeStatus'],
['advertisingStatus', STRING, 4, 'advertisingStatus'],
['locationTag', STRING, 16, 'locationTag'],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Motes'],
'isResponseArray': True,
},
# getPaths -- return LIST of paths
{
'id' : 'getConfig',
'name' : 'getPaths',
'description': '''Get the list of Paths to the mote\'s neighbors''',
'request' : [
# the request parameter moteMac matches the XML query for Paths
['moteMac', STRING, 25, None],
],
'response' : {
'Path': [
['pathId', INT, 4, None],
['moteAMac', STRING, 25, None],
['moteBMac', STRING, 25, None],
['numLinks', INT, 4, None],
['pathDirection', STRING, 16, 'pathDirection'],
['pathQuality', FLOAT, 0, None],
],
},
'serializer' : 'serialize_getPath',
'isResponseArray': True,
},
{
'id' : 'getConfig',
'name' : 'getPathStatistics',
'description': 'Get Statistics for a specific Path',
'request' : [
['pathId', INT, 4, None],
['period', STRING, 16, 'statPeriod'],
['index', INT, 4, None],
],
'response' : {
'PathStatistics': [
['index', INT, 4, None],
['startTime', INT, 8, None], # milliseconds
['baPwr', INT, 1, None],
['abPwr', INT, 1, None],
['stability', FLOAT, 8, None],
],
},
'serializer' : 'serialize_getPathStats',
'deserializer' : 'deserialize_getStats',
},
# security
{
'id' : 'getConfig',
'name' : 'getSecurity',
'description': '''Get the Security configuration''',
'request' : [
],
'response' : {
'Security': [
['securityMode', STRING, 20, 'securityMode'],
['acceptHARTDevicesOnly', BOOL, 1, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam' : ['config', 'Security'],
},
{
'id' : 'getConfig',
'name' : 'getAcls',
'description': '''Get the list of devices on the ACL''',
'request' : [
],
'response' : {
'Acl': [
['macAddr', STRING, 25, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam' : ['config', 'Security', 'Acl'],
'isResponseArray': True,
},
{
'id' : 'getConfig',
'name' : 'getAcl',
'description': '''Check whether a device is part of the ACL''',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
'Acl': [
['macAddr', STRING, 25, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam' : ['config', 'Security', 'Acl', 'Device'],
},
# getBlacklist -- return LIST of frequencies
{
'id' : 'getConfig',
'name' : 'getBlacklist',
'description': 'Get the channel blacklist',
'request' : [
],
'response' : {
'ChannelBlackList': [
['frequency', INT, 4, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Network', 'ChannelBlackList'],
'isResponseArray': True,
},
# getRedundancy
{
'id' : 'getConfig',
'name' : 'getRedundancy',
'description': 'Get the redundancy state',
'request' : [
],
'response' : {
'Redundancy': [
['localMode', STRING, 16, 'redundancyMode'],
['peerStatus', STRING, 16, 'redundancyPeerStatus'],
['peerControllerSwRev', STRING, 16, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Redundancy'],
},
# getSla
{
'id' : 'getConfig',
'name' : 'getSla',
'description': 'Get the Service Level Agreement (SLA) configuration',
'request' : [
],
'response' : {
'Sla': [
['minNetReliability', FLOAT, 8, None],
['maxNetLatency', INT, 4, None],
['minNetPathStability', FLOAT, 8, None],
['apRdntCoverageThreshold', FLOAT,8, None],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Network', 'Sla'],
},
# getUsers -- return LIST of users
{
'id' : 'getConfig',
'name' : 'getUsers',
'description': 'Get the list of users',
'request' : [
],
'response' : {
'User': [
['userName', STRING, 16, None],
['privilege', STRING, 16, 'userPrivilege'],
],
},
'serializer' : 'serialize_getConfig',
'serializerParam': ['config', 'Users'],
'isResponseArray': True,
},
# getUser
{
'id' : 'getConfig',
'name' : 'getUser',
'description': 'Get the description of a user ',
'request' : [
['userName', STRING, 16, None],
],
'response' : {
'User': [
['userName', STRING, 16, None],
['privilege', STRING, 16, 'userPrivilege'],
],
},
'serializer' : 'serialize_getUser',
},
# setSystem
{
'id' : 'setConfig',
'name' : 'setSystem',
'description': 'Set system-level configuration',
'request' : [
['systemName', STRING, 16, None],
['location', STRING, 16, None],
['cliTimeout', INT, 4, None],
],
'response' : {
'System': [
# TODO: return all elements?
['systemName', STRING, 50, None],
['location', STRING, 50, None],
['cliTimeout', INT, 4, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'System'],
},
# setNetwork
{
'id' : 'setConfig',
'name' : 'setNetwork',
'description': 'Set network configuration',
'request' : [
['netName', STRING, 16, None],
['networkId', INT, 4, None],
['maxMotes', INT, 4, None],
['optimizationEnable', BOOL, 1, None],
['accessPointPA', BOOL, 1, None],
['ccaEnabled', BOOL, 1, None],
['requestedBasePkPeriod', INT, 4, None],
['minServicesPkPeriod', INT, 4, None],
['minPipePkPeriod', INT, 4, None],
['bandwidthProfile', STRING, 16, 'bandwidthProfile'],
['manualUSFrameSize', INT, 4, None],
['manualDSFrameSize', INT, 4, None],
['manualAdvFrameSize', INT, 4, None],
['locationMode', STRING, 8, 'onOff'],
# backbone parameters added in 4.1.0.3
# TODO: UG! adding these parameters prevents backward compatibility
#['backboneEnabled', BOOL, 1, None],
#['backboneSize', INT, 4, None],
],
'response' : {
'Network': [
# TODO: return all elements?
['netName', STRING, 16, None],
['networkId', INT, 4, None],
['maxMotes', INT, 4, None],
['optimizationEnable', BOOL, 1, None],
['accessPointPA', BOOL, 1, None],
['ccaEnabled', BOOL, 1, None],
['requestedBasePkPeriod', INT, 4, None],
['minServicesPkPeriod', INT, 4, None],
['minPipePkPeriod', INT, 4, None],
['bandwidthProfile', STRING, 16, 'bandwidthProfile'],
['manualUSFrameSize', INT, 4, None],
['manualDSFrameSize', INT, 4, None],
['manualAdvFrameSize', INT, 4, None],
['locationMode', STRING, 8, 'onOff'],
# backbone parameters added in 4.1.0.3
['backboneEnabled', BOOL, 1, None],
['backboneSize', INT, 4, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Network'],
},
# setMote
{
'id' : 'setConfig',
'name' : 'setMote',
'description': 'Set mote configuration',
'request' : [
['macAddr', STRING, 25, None],
['name', STRING, 16, None],
['enableRouting', BOOL, 1, None],
],
'response' : {
'Mote': [
['moteId', INT, 4, None],
['macAddr', STRING, 25, None],
['name', STRING, 16, None],
['state', STRING, 16, 'moteState'],
['numJoins', INT, 4, None],
['joinTime', INT, 8, None], # TODO: date time
['reason', STRING, 16, None],
['isAccessPoint', BOOL, 1, None],
['powerSource', STRING, 16, None], # TODO: enum
['dischargeCurrent', INT, 4, None],
['dischargeTime', INT, 4, None],
['recoveryTime', INT, 4, None],
['enableRouting', BOOL, 1, None],
['productName', STRING, 16, None],
['hwModel', INT, 1, None],
['hwRev', INT, 1, None],
['swRev', STRING, 16, None],
['voltage', FLOAT, 8, None],
['numNeighbors', INT, 4, None],
['needNeighbor', BOOL, 1, None],
['goodNeighbors', INT, 4, None],
['allocatedPkPeriod', INT, 4, None],
['allocatedPipePkPeriod', INT, 4, None],
['pipeStatus', STRING, 4, 'pipeStatus'],
['advertisingStatus', STRING, 4, 'advertisingStatus'],
['locationTag', STRING, 16, 'locationTag'],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Motes', 'Mote'],
},
# setSla
{
'id' : 'setConfig',
'name' : 'setSla',
'description': 'Set SLA configuration',
'request' : [
['minNetReliability', FLOAT, 8, None],
['maxNetLatency', INT, 4, None],
['minNetPathStability', FLOAT, 8, None],
['apRdntCoverageThreshold', FLOAT, 8, None],
],
'response' : {
'Sla': [
['minNetReliability', FLOAT, 8, None],
['maxNetLatency', INT, 4, None],
['minNetPathStability', FLOAT, 8, None],
['apRdntCoverageThreshold', FLOAT, 8, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Network', 'Sla'],
},
# setSecurity
{
'id' : 'setConfig',
'name' : 'setSecurity',
'description': 'Set security configuration',
'request' : [
['securityMode', STRING, 20, 'securityMode'],
['commonJoinKey', HEXDATA, 16, None],
['acceptHARTDevicesOnly', BOOL, 1, None],
],
'response' : {
'Security': [
['securityMode', STRING, 20, 'securityMode'],
['acceptHARTDevicesOnly', BOOL, 1, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Security'],
},
# setUser
{
'id' : 'setConfig',
'name' : 'setUser',
'description': 'Add or update user configuration',
'request' : [
['userName', STRING, 16, None],
['password', STRING, 16, None],
['privilege', STRING, 16, 'userPrivilege'],
],
'response' : {
'User': [
['userName', STRING, 16, None],
['privilege', STRING, 16, 'userPrivilege'],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Users', 'User'],
},
# setAcl
{
'id' : 'setConfig',
'name' : 'setAcl',
'description': 'Add or update a device in the ACL',
'request' : [
['macAddr', STRING, 25, None],
['joinKey', HEXDATA, 16, None],
],
'response' : {
'Device': [
['macAddr', STRING, 25, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Security', 'Acl', 'Device'],
},
# setBlackList
{
'id' : 'setConfig',
'name' : 'setBlacklist',
'description': 'Update the channel blacklist',
'request' : [
['frequency', INT, 4, None],
],
'response' : {
'ChannelBlackList': [
['frequency', INT, 4, None],
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Network', 'ChannelBlackList'],
},
# deleteAcl
{
'id' : 'deleteConfig',
'name' : 'deleteAcl',
'description': 'Remove a device from the ACL',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS: [
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Security', 'Acl', 'Device'],
},
# deleteUser
{
'id' : 'deleteConfig',
'name' : 'deleteUser',
'description': 'Remove a user',
'request' : [
['userName', STRING, 16, None],
],
'response' : {
FIELDS: [
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Users', 'User'],
},
# deleteMote
{
'id' : 'deleteConfig',
'name' : 'deleteMote',
'description': 'Remove a mote from the manager configuration',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS: [
],
},
'serializer' : 'serialize_setConfig',
'serializerParam' : ['config', 'Motes', 'Mote'],
},
# Send packet commands
{
'id' : 'sendRequest',
'name' : 'sendRequest',
'description': 'Send downstream (request) data',
'request' : [
['macAddr', STRING, 25, None],
['domain', STRING, 16, 'appDomain'],
['priority', STRING, 16, 'packetPriority'],
['reliable', BOOL, 0, None],
['data', HEXDATA, None,None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
{
'id' : 'sendResponse',
'name' : 'sendResponse',
'description': 'Send downstream data as a response. sendResponse should only be used in special cases.',
'request' : [
['macAddr', STRING, 25, None],
['domain', STRING, 16, 'appDomain'],
['priority', STRING, 16, 'packetPriority'],
['reliable', BOOL, 0, None],
['callbackId', INT, 4, None],
['data', HEXDATA, None, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeNetworkKey
{
'id' : 'exchangeNetworkKey',
'name' : 'exchangeNetworkKey',
'description': 'Exchange the network key',
'request' : [
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeJoinKey
{
'id' : 'exchangeJoinKey',
'name' : 'exchangeJoinKey',
'description': 'Exchange the common join key',
'request' : [
['newKey', HEXDATA, 16, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeMoteJoinKey
{
'id' : 'exchangeMoteJoinKey',
'name' : 'exchangeMoteJoinKey',
'description': 'Exchange a mote\'s join key',
'request' : [
['macAddr', STRING, 25, None],
['newKey', HEXDATA, 16, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeNetworkId
{
'id' : 'exchangeNetworkId',
'name' : 'exchangeNetworkId',
'description': 'Exchange the network ID',
'request' : [
['newId', INT, 4, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeMoteNetworkId
{
'id' : 'exchangeMoteNetworkId',
'name' : 'exchangeMoteNetworkId',
'description': 'Exchange the network ID for a mote',
'request' : [
['macAddr', STRING, 25, None],
['newId', INT, 4, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# exchangeSessionKey
{
'id' : 'exchangeSessionKey',
'name' : 'exchangeSessionKey',
'description': 'Exchange a mote\'s session key',
'request' : [
['macAddrA', STRING, 25, None],
['macAddrB', STRING, 25, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# Miscellaneous commands
{
'id' : 'activateFastPipe',
'name' : 'activateFastPipe',
'description': 'Activate the fast network pipe to the specified mote.',
'request' : [
['macAddr', STRING, 25, None],
['pipeDirection', STRING, 25, 'pipeDirection'],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
{
'id' : 'deactivateFastPipe',
'name' : 'deactivateFastPipe',
'description': 'Deactivate the fast network pipe to the specified mote.',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
{
'id' : 'getLatency',
'name' : 'getLatency',
'description': 'Get estimated latency for a mote.',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['downstream', INT, 4, None],
['upstream', INT, 4, None],
],
},
},
{
'id' : 'getTime',
'name' : 'getTime',
'description': 'Get the current time.',
'request' : [
],
'response' : {
FIELDS : [
['utc_time', FLOAT, 0, None], # TODO: return as a date-time format
['asn_time', INT, 8, None],
],
},
},
# activateAdvertising
{
'id' : 'activateAdvertising',
'name' : 'activateAdvertising',
'description': 'Activate advertisement frame',
'request' : [
['macAddr', STRING, 25, None],
['timeout', INT, 4, None]
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# startOtap
{
'id' : 'startOtap',
'name' : 'startOtap',
'description': 'This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software on motes and the Access Point. By default, the process will retry the OTAP file transmission 100 times.',
'request' : [
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# startOtapWithRetries
{
'id' : 'startOtapWithRetries',
'name' : 'startOtapWithRetries',
'description': 'This command initiates the OTAP (Over-The-Air-Programming) process to upgrade software for motes and the Access Point, using the specified number of retries.',
'request' : [
['retries', INT, 1, None]
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# cancelOtap
{
'id' : 'cancelOtap',
'name' : 'cancelOtap',
'description': 'This command cancels the OTAP (Over-The-Air-Programming) process to upgrade software on motes and the access point.',
'request' : [
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# decommissionDevice
{
'id' : 'decommissionDevice',
'name' : 'decommissionDevice',
'description': 'Decommission a device in the network',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# promoteToOperational
{
'id' : 'promoteToOperational',
'name' : 'promoteToOperational',
'description': 'Promote a quarantined device to operational',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# pingMote
{
'id' : 'pingMote',
'name' : 'pingMote',
'description': '''Ping the specified mote. A Net Ping Reply event notification will contain the mote's response.''',
'request' : [
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['callbackId', INT, 4, None],
],
},
},
# Licensing
{
'id' : 'getLicense',
'name' : 'getLicense',
'description': '''Get the software license key.''',
'request' : [
],
'response' : {
FIELDS : [
['license', STRING, 40, None],
],
},
},
{
'id' : 'setLicense',
'name' : 'setLicense',
'description': 'Set the software license key.',
'request' : [
['license', STRING, 40, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# reset
{
'id' : 'reset',
'name' : 'reset',
'description': 'Reset the system or network',
'request' : [
['object', STRING, 25, 'resetObject'],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# resetWithId
{
'id' : 'reset',
'name' : 'resetWithId',
'description': 'Reset mote by ID',
'request' : [
['object', STRING, 25, 'resetMote'],
['moteId', INT, 4, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# resetWithMac
{
'id' : 'reset',
'name' : 'resetWithMac',
'description': 'Reset mote by MAC address',
'request' : [
['object', STRING, 25, 'resetMote'],
['macAddr', STRING, 25, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
# subscribe, unsubscribe
{
'id' : 'subscribe',
'name' : 'subscribe',
'description': '''Subscribe to notifications. This function creates or updates the subscribed notifications to match 'filter'. The filter is a space-separated list of notification types. Valid types include 'data', 'events', 'alarms', 'log'.''',
'request' : [
['filter', STRING, 128, None],
],
'response' : {
FIELDS : [
['notif_token', STRING, 32, None],
# note: this is intentionally different from the subscribe API command
# (not returning the notification port) because the SmartMesh SDK method
# also handles connecting to the notification channel.
],
},
'command_override': 'subscribe_override',
},
{
'id' : 'unsubscribe',
'name' : 'unsubscribe',
'description': 'Unsubscribe from notifications. This function clears the existing notification subscription of the client and stops the notification thread. ',
'request' : [
# note: this is intentionally different from the unsubscribe API
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
'command_override': 'unsubscribe_override',
},
# cli -- the CLI command is deprecated
{
'id' : 'cli',
'name' : 'cli',
'description': 'This command tunnels a given command through to the manager\'s Command Line Interface (CLI). The CLI command can be called by only one XML API client at a time. The response to the given CLI command is tunneled back to the client via the notifications channel. To receive the CLI notification, the client must be subscribed to CLI notifications (see Notification Channel)',
'request' : [
['command', STRING, 128, None],
],
'response' : {
FIELDS : [
['result', STRING, 32, None],
],
},
},
]
| {
"repo_name": "twatteyne/dustlink_academy",
"path": "SmartMeshSDK/ApiDefinition/HartMgrDefinition.py",
"copies": "3",
"size": "79712",
"license": "bsd-3-clause",
"hash": -822044396181852900,
"line_mean": 39.380952381,
"line_max": 401,
"alpha_frac": 0.3646753312,
"autogenerated": false,
"ratio": 4.65934065934066,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.010704332599138928,
"num_lines": 1974
} |
"""api_demo_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from api_demo import views
router = routers.DefaultRouter()
router.register(r'stuff', views.StuffViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
]
| {
"repo_name": "BFriedland/api-demo",
"path": "api_demo_site/urls.py",
"copies": "1",
"size": "1057",
"license": "mit",
"hash": 3648863426549177000,
"line_mean": 35.4482758621,
"line_max": 77,
"alpha_frac": 0.6868495743,
"autogenerated": false,
"ratio": 3.546979865771812,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9733829440071813,
"avg_score": 0,
"num_lines": 29
} |
"""API Discovery api.
The AXIS API Discovery service makes it possible to retrieve information about APIs supported on their products.
"""
import attr
from .api import APIItem, APIItems, Body
URL = "/axis-cgi/apidiscovery.cgi"
API_DISCOVERY_ID = "api-discovery"
API_VERSION = "1.0"
class ApiDiscovery(APIItems):
"""API Discovery for Axis devices."""
def __init__(self, request: object) -> None:
"""Initialize API discovery manager."""
super().__init__({}, request, URL, Api)
async def update(self) -> None:
"""Refresh data."""
raw = await self.get_api_list()
self.process_raw(raw)
@staticmethod
def pre_process_raw(raw: dict) -> dict:
"""Return a dictionary of discovered APIs."""
api_data = raw.get("data", {}).get("apiList", [])
return {api["id"]: api for api in api_data}
async def get_api_list(self) -> dict:
"""List all APIs registered on API Discovery service."""
return await self._request(
"post",
URL,
json=attr.asdict(
Body("getApiList", API_VERSION),
filter=attr.filters.exclude(attr.fields(Body).params),
),
)
async def get_supported_versions(self) -> dict:
"""Supported versions of API Discovery API."""
return await self._request(
"post",
URL,
json=attr.asdict(
Body("getSupportedVersions", API_VERSION),
filter=attr.filters.include(attr.fields(Body).method),
),
)
class Api(APIItem):
"""API Discovery item."""
@property
def name(self):
"""Name of API."""
return self.raw["name"]
@property
def version(self):
"""Version of API."""
return self.raw["version"]
| {
"repo_name": "Kane610/axis",
"path": "axis/api_discovery.py",
"copies": "1",
"size": "1840",
"license": "mit",
"hash": 5116531372514992000,
"line_mean": 26.0588235294,
"line_max": 112,
"alpha_frac": 0.5679347826,
"autogenerated": false,
"ratio": 4.043956043956044,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0001301405517959396,
"num_lines": 68
} |
# api_dividebatur.py
# Ronald L. Rivest
# July 31, 2016
# python3
"""
This is a draft API as a possible interface between the
Bayesian audit code (or other audit code) and the implementation
of the STV social choice function by Grahame Bowland.
"""
import copy
import hashlib
import os
import random
# Add parent directory to path so that we can find the dividebatur module.
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
import dividebatur.dividebatur.senatecount as sc
import dividebatur.dividebatur.counter as cnt
from dividebatur.dividebatur.results import BaseResults
##############################################################################
## Results of the count
class APIResults(BaseResults):
"""
minimal implementation of the dividebatur BaseResults abc,
merely tracking which candidates were elected. almost all
methods are stubs.
"""
def __init__(self):
self.candidates_elected = []
def round_begin(self, round_number):
pass
def round_complete(self):
pass
def exclusion_distribution_performed(self, obj):
pass
def election_distribution_performed(self, obj):
pass
def candidate_aggregates(self, obj):
pass
def candidate_elected(self, obj):
"""
Called by the counter when a candidate is elected.
``obj`` is an instance of dividebatur.results.CandidateElected.
"""
self.candidates_elected.append(obj.candidate_id)
def candidates_excluded(self, obj):
pass
def provision_used(self, obj):
pass
def started(self, vacancies, total_papers, quota):
pass
def finished(self):
pass
##############################################################################
## Candidates
"""
A candidate is represented by the Candidate named-tuple datatype
as defined in dividbatur senatecount.py. A candidate has attributes:
CandidateID # integer
Surname # string
GivenNm # string
PartyNm # string
"""
##############################################################################
## Ballot (preference tuple)
"""
A ballot is a tuple of candidate_ids, in order of decreasing preference.
It may have any length, possibly less than the number of candidates;
candidates not mentioned are preferred less than those mentioned.
One may think of this as the (BTL) form of a single cast paper ballot.
(It could alternatively be a tuple of (preference_no, candidate_id) pairs,
as long as it is hashable, and things are sorted into order. But I prefer
the simpler tuple of candidate_ids.)
"""
##############################################################################
## Election
class Election:
"""
An Election represents the basic information about an election,
including candidates, number of seats available, list of cast
ballots (with multiplicities), etc.
"""
ID = 'id'
SCF = 'method'
ORDER = 'order'
FORMAT = 'format'
CONTESTS = 'count'
ELECTED = 'elected'
CONTEST_NAME = 'name'
ELECTION_ID = 'title'
AEC_DATA = 'aec-data'
VERIFY_FLAG = 'verified'
NUM_VACANCIES = 'vacancies'
def __init__(self):
self.electionID = "NoElection" # string
self.n = 0 # integer
self.seats = 0 # integer
self.candidate_ids = [] # list of candidate_ids
self.candidates = [] # list of candidates
self.ballots = [] # list of ballots drawn so far
self.ballots_drawn = 0 # integer
self.ballot_weights = {} # dict mapping ballots to weights
self.total_ballot_weight = 0.0 # sum of all ballot weights
self.remaining_tickets = [] # list of remaining tickets to draw ballots from.
# `dividebatur` specific variables.
self.out_dir = None # string representing the directory path for writing election results
self.data_dir = None # string representing the directory path containing the election data
self.contest_config = None # dict containing contest-specific information (i.e. number of seats)
self.data = None # data structure storing contest tickets, candidates, SCF, etc.
"""
Remarks:
* `self.ballot_weights` is a python dict mapping ballots in `self.ballots` to weights that are
>= 0. These weights are *not* modified by the counting; they always represent the number of times
each preference list was input as a ballot. These weights need *not* be integers.
* `self.remaining_tickets` is a list of all tickets in the election contest. This list is modified
when ballots are drawn at random to grow an audit sample. Note that there may be duplicates of the
same ballot in `self.remaining_tickets` (i.e. multiplicities are expanded).
"""
def load_election(self, contest_name, config_file=None, out_dir=None , max_tickets=None):
"""
Load election data for the contest with the provided name using the provided configuration file name. Sets
self.electionID
self.seats
self.candidate_ids
self.candidates
self.remaining_tickets
As well as `dividebatur`-specific instance variables
self.out_dir
self.data_dir
self.contest_config
self.data
Remarks:
* Formality checks are performed as the initial data is being loaded and processed by `dividebatur`.
* `dividebatur` handles all ATL to BTL conversions. The `self.remaining_tickets` contains BTL ballots.
"""
# Sets configuration file and out directory to default values if not set by caller.
config_file = config_file or '../dividebatur/aec_data/fed2016/aec_fed2016.json'
self.data_dir = os.path.dirname(os.path.abspath(config_file))
self.out_dir = out_dir or '../dividebatur/angular/data/'
# Read the configuration file for the election data.
election_config = sc.read_config(config_file)
self.electionID = election_config[Election.ELECTION_ID]
# An election may have multiple contests. Here we select the contest with the provided
# contest name (e.g. 'TAS' or 'NT', for Tasmania and Northern Territory, respecitvely).
self.contest_config = next((contest for contest in election_config[Election.CONTESTS] if contest[Election.CONTEST_NAME] == contest_name), None)
if self.contest_config is None:
possible_names = ', '.join([contest[Election.CONTEST_NAME] for contest in election_config[Election.CONTESTS]])
raise Exception('Contest with name %s not found. Try one of %s.' % (contest_name, str(possible_names)))
# Get the number of seats for this contest.
self.seats = self.contest_config[Election.NUM_VACANCIES]
# Get the social chocie function.
input_cls = sc.get_input_method(self.contest_config[Election.AEC_DATA][Election.FORMAT])
try:
# Remove this key to suppress verification checks which would
# not be valid for a subsample of the ballots from the contest.
del self.contest_config[Election.VERIFY_FLAG]
except KeyError:
pass
#Overide max_tickets if set
try:
if max_tickets:
self.contest_config.update({'max_tickets': max_tickets})
except KeyError:
pass
# Get ticket data.
self.data = sc.get_data(input_cls, self.data_dir, self.contest_config)
# Build remaining ticket data structure from tickets and randomly shuffle for sampling.
for ticket, weight in self.data.tickets_for_count:
# NOTE: We expand multiplicities here such that for each ticket, there are `weight` copies of that ticket
# in `self.remaining_tickets`. We do this for ease of random sampling (e.g. note that a dictionary mapping
# tickets to their corresponding weights does not facilitate easy random sampling).
for _ in range(weight):
if max_tickets and len(self.remaining_tickets) >= max_tickets:
break
self.remaining_tickets.append(copy.deepcopy(ticket))
self.n += 1
if max_tickets and len(self.remaining_tickets) >= max_tickets:
break
print('Total number of ballots in contest:', self.n)
random.shuffle(self.remaining_tickets)
# Get candidate data.
self.candidate_ids = self.data.get_candidate_ids()
self.candidates = self.data.candidates.candidates
def add_ballot(self, ballot, weight):
"""
Add BTL ballot with given weight to the election.
If ballot with same preferences already exists, then
just add to its weight.
No formality checks are made.
"""
if ballot in self.ballot_weights:
self.ballot_weights[ballot] += weight
else:
self.ballots.append(ballot)
self.ballot_weights[ballot] = weight
self.total_ballot_weight += weight
def load_more_ballots(self, batch_size):
"""
Expand the current sample by `batch_size` by adding each new BTL ballot with a weight of 1.
"""
# Make sure not to over draw remaining ballots.
ballots_to_draw = min(batch_size, len(self.remaining_tickets))
for _ in range(ballots_to_draw):
# Pop off the first ticket in `self.remaining_tickets`, convert it from a ticket to a ballot,
# and finally add it to the growing sample of ballots.
self.add_ballot(self.remaining_tickets.pop(0), 1)
self.ballots_drawn += ballots_to_draw
def get_outcome(self, new_ballot_weights=None, **params):
"""
Return list of candidates who are elected in this election, where
self.ballot_weights gives weights of each ballot.
However, if new_ballot_weights is given, use those instead
of self.ballot_weights.
params is dict giving parameters that may affect how computation
is done, such as tie-breaking info, or number n of ballots cast overall
in election (not just sample size).
params may also control output (e.g. logging output).
"""
nonce = str(params['nonce'])
def tie_break_by_sha256_sort(items):
"""
`tie_break_by_sha256_sort` takes a list of items. It then converts every item in the
list to a string and concatenates that string with the tie break string. This concatenation
is then unicode encoded and the SHA-256 is taken. These hashes are then converted to HEX and
sorted lexicographically. Finally, the original index of the first item in this sorted list
of hashes is returned as the index of the item to chose for breaking the given tie. Here the
original index refers to the item's position in the input `items`.
"""
def get_sha256_hash_of_item(item):
return hashlib.sha256((str(item) + nonce).encode('utf-8')).hexdigest()
indices = sorted(range(len(items)), key=lambda i : get_sha256_hash_of_item(items[i]))
return indices[0]
ballot_weights = new_ballot_weights or self.ballot_weights
# Reset tickets for count
self.data.tickets_for_count = sc.PapersForCount()
for ballot, weight in ballot_weights.items():
self.data.tickets_for_count.add_ticket(tuple(ballot), weight)
# Set up the counter, and ask it to report results into our
# result tracking class
results = APIResults()
counter = cnt.SenateCounter(
results,
self.seats,
self.data.tickets_for_count,
self.data.get_candidate_ids(),
self.data.get_candidate_order,
disable_bulk_exclusions=True)
counter.set_election_order_callback(tie_break_by_sha256_sort)
counter.set_candidate_tie_callback(tie_break_by_sha256_sort)
# Run the count
counter.run()
return tuple(sorted(results.candidates_elected))
| {
"repo_name": "ron-rivest/2016-aus-senate-audit",
"path": "rivest/api_dividebatur.py",
"copies": "1",
"size": "12551",
"license": "apache-2.0",
"hash": 477775727614217100,
"line_mean": 39.6181229773,
"line_max": 151,
"alpha_frac": 0.6207473508,
"autogenerated": false,
"ratio": 4.12183908045977,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.006040344548405226,
"num_lines": 309
} |
"""API Doc generator for the server side API."""
from hydrus.hydraspec.doc_writer import HydraDoc, HydraClass, HydraClassProp, HydraClassOp
import json
def doc_gen(API: str, BASE_URL: str) -> HydraDoc:
"""Generate API Doc for server."""
# Main API Doc
api_doc = HydraDoc(API,
"API Doc for the server side API",
"API Documentation for the server side system",
API,
BASE_URL)
# State Class
state = HydraClass("State", "State", "Class for drone state objects")
# Properties
state.add_supported_prop(HydraClassProp(
"http://auto.schema.org/speed", "Speed", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "Position", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/Property", "Direction", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/fuelCapacity", "Battery", False, False, True))
state.add_supported_prop(HydraClassProp(
"https://schema.org/status", "SensorStatus", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
# Operations
state.add_supported_op(HydraClassOp("GetState",
"GET",
None,
"vocab:State",
[{"statusCode": 404, "description": "State not found"},
{"statusCode": 200, "description": "State Returned"}]))
# Drone Class
drone = HydraClass("Drone", "Drone", "Class for a drone")
# Properties
drone.add_supported_prop(HydraClassProp(
"vocab:State", "DroneState", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/name", "name", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/model", "model", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://auto.schema.org/speed", "MaxSpeed", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/device", "Sensor", False, False, True))
# Operations
# Drones will submit their state to the server at certain intervals or
# when some event happens
drone.add_supported_op(HydraClassOp("SubmitDrone",
"POST",
"vocab:Drone",
None,
[{"statusCode": 200, "description": "Drone updated"}]))
drone.add_supported_op(HydraClassOp("CreateDrone",
"PUT",
"vocab:Drone",
None,
[{"statusCode": 200, "description": "Drone added"}]))
drone.add_supported_op(HydraClassOp("GetDrone",
"GET",
None,
"vocab:Drone",
[{"statusCode": 404, "description": "Drone not found"},
{"statusCode": 200, "description": "Drone Returned"}]))
# NOTE: Commands are stored in a collection. You may GET a command or you
# may DELETE it, there is not UPDATE.
command = HydraClass("Command", "Command", "Class for drone commands")
command.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
command.add_supported_prop(HydraClassProp(
"vocab:State", "State", False, False, True))
# Used by mechanics to get newly added commands
command.add_supported_op(HydraClassOp("GetCommand",
"GET",
None,
"vocab:Command",
[{"statusCode": 404, "description": "Command not found"},
{"statusCode": 200, "description": "Command Returned"}]))
# Used by server to add new commands
command.add_supported_op(HydraClassOp("AddCommand",
"PUT",
"vocab:Command",
None,
[{"statusCode": 201, "description": "Command added"}]))
command.add_supported_op(HydraClassOp("DeleteCommand",
"DELETE",
None,
None,
[{"statusCode": 201, "description": "Command deleted"}]))
# Logs to be accessed mostly by the GUI. Mechanics should add logs for
# every event.
log = HydraClass("LogEntry", "LogEntry", "Class for a log entry")
# Subject
log.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", True, True, False))
# Predicate
log.add_supported_prop(HydraClassProp(
"http://schema.org/UpdateAction", "Update", False, True, False))
log.add_supported_prop(HydraClassProp(
"http://schema.org/ReplyAction", "Get", False, True, False))
log.add_supported_prop(HydraClassProp(
"http://schema.org/SendAction", "Send", False, True, False))
# Objects
log.add_supported_prop(HydraClassProp(
"vocab:State", "State", False, True, False))
log.add_supported_prop(HydraClassProp(
"vocab:Datastream", "Data", False, True, False))
log.add_supported_prop(HydraClassProp(
"vocab:Command", "Command", False, True, False))
# GUI will get a certain log entry.
log.add_supported_op(HydraClassOp("GetLog",
"GET",
None,
"vocab:LogEntry",
[{"statusCode": 404, "description": "Log entry not found"},
{"statusCode": 200, "description": "Log entry returned"}]))
log.add_supported_op(HydraClassOp("AddLog",
"PUT",
"vocab:LogEntry",
None,
[{"statusCode": 201, "description": "Log entry created"}]))
# Data is stored as a collection. Each data object can be read.
# New data added to the collection
datastream = HydraClass("Datastream", "Datastream",
"Class for a datastream entry")
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/QuantitativeValue", "Temperature", False, False, True))
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "Position", False, False, True))
datastream.add_supported_op(HydraClassOp("ReadDatastream",
"GET",
None,
"vocab:Datastream",
[{"statusCode": 404, "description": "Data not found"},
{"statusCode": 200, "description": "Data returned"}]))
datastream.add_supported_op(HydraClassOp("UpdateDatastream",
"POST",
"vocab:Datastream",
None,
[{"statusCode": 200, "description": "Data updated"}]))
datastream.add_supported_op(HydraClassOp("DeleteDatastream",
"DELETE",
None,
None,
[{"statusCode": 200, "description": "Data deleted"}]))
# Single object representing the area of interest. No collections.
area = HydraClass(
"Area", "Area", "Class for Area of Interest of the server", endpoint=True)
# Using two positions to have a bounding box
area.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "TopLeft", False, False, True))
area.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "BottomRight", False, False, True))
# Allowing updation of the area of interest
area.add_supported_op(HydraClassOp("UpdateArea",
"POST",
"vocab:Area",
None,
[{"statusCode": 200, "description": "Area of interest changed"}]))
area.add_supported_op(HydraClassOp("GetArea",
"GET",
None,
"vocab:Area",
[{"statusCode": 404, "description": "Area of interest not found"},
{"statusCode": 200, "description": "Area of interest returned"}]))
message = HydraClass("Message", "Message",
"Class for messages received by the GUI interface")
message.add_supported_prop(HydraClassProp(
"http://schema.org/Text", "MessageString", False, False, True))
message.add_supported_op(HydraClassOp("GetMessage",
"GET",
None,
"vocab:Message",
[{"statusCode": 404, "description": "Message not found"},
{"statusCode": 200, "description": "Message returned"}]))
message.add_supported_op(HydraClassOp("DeleteMessage",
"DELETE",
None,
None,
[{"statusCode": 200, "description": "Message deleted"}]))
api_doc.add_supported_class(drone, collection=True)
api_doc.add_supported_class(state, collection=True)
api_doc.add_supported_class(datastream, collection=True)
api_doc.add_supported_class(log, collection=True)
api_doc.add_supported_class(area, collection=False)
api_doc.add_supported_class(command, collection=True)
api_doc.add_supported_class(message, collection=True)
api_doc.add_baseResource()
api_doc.add_baseCollection()
api_doc.gen_EntryPoint()
return api_doc
if __name__ == "__main__":
dump = json.dumps(
doc_gen("api", "http://localhost:8080/").generate(), indent=4, sort_keys=True)
doc = '''"""\nGenerated API Documentation for Server API using server_doc_gen.py."""\n\ndoc = %s''' % dump
doc = doc.replace('true', '"true"')
doc = doc.replace('false', '"false"')
doc = doc.replace('null', '"null"')
f = open("doc.py", "w")
f.write(doc)
f.close()
| {
"repo_name": "xadahiya/hydrus",
"path": "examples/drones/doc_gen.py",
"copies": "1",
"size": "11478",
"license": "mit",
"hash": -6635439770086230000,
"line_mean": 51.4109589041,
"line_max": 110,
"alpha_frac": 0.4960794564,
"autogenerated": false,
"ratio": 4.582035928143712,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5578115384543713,
"avg_score": null,
"num_lines": null
} |
"""API Doc generator for the server side API."""
import json
from hydra_python_core.doc_writer import (HydraClass, HydraClassOp,
HydraClassProp, HydraDoc,
HydraStatus, HydraCollection)
def doc_gen(API: str, BASE_URL: str) -> HydraDoc:
"""Generate API Doc for server."""
# Main API Doc
api_doc = HydraDoc(API,
"API Doc for the server side API",
"API Documentation for the server side system",
API,
BASE_URL,
"vocab")
# State Class
state = HydraClass("State", "Class for drone state objects", endpoint=True)
# Properties
state.add_supported_prop(HydraClassProp(
"http://auto.schema.org/speed", "Speed", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "Position", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/Property", "Direction", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/fuelCapacity", "Battery", False, False, True))
state.add_supported_prop(HydraClassProp(
"https://schema.org/status", "SensorStatus", False, False, True))
state.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
# Operations
state.add_supported_op(
HydraClassOp(
"GetState", "GET", None, state.id_,
possible_status=[HydraStatus(
code=404, desc="State not found"),
HydraStatus(
code=200, desc="State Returned")]))
state_collection_manages = {
"property": "rdfs:type",
"object": state.id_
}
state_collection = HydraCollection(collection_name="StateCollection",
collection_description="A collection of states",
manages=state_collection_manages)
# Drone Class
drone = HydraClass("Drone", "Class for a drone", endpoint=True)
# Properties
drone.add_supported_prop(HydraClassProp(
state.id_, "DroneState", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/name", "name", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/model", "model", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://auto.schema.org/speed", "MaxSpeed", False, False, True))
drone.add_supported_prop(HydraClassProp(
"http://schema.org/device", "Sensor", False, False, True))
# Operations
# Drones will submit their state to the server at certain intervals or
# when some event happens
drone.add_supported_op(
HydraClassOp(
"SubmitDrone", "POST", drone.id_, None,
possible_status=[HydraStatus(code=200, desc="Drone updated")]))
drone.add_supported_op(
HydraClassOp(
"CreateDrone", "PUT", drone.id_, None,
possible_status=[HydraStatus(code=200, desc="Drone added")]))
drone.add_supported_op(
HydraClassOp(
"GetDrone", "GET", None, drone.id_,
possible_status=[HydraStatus(
code=404, desc="Drone not found"),
HydraStatus(
code=200, desc="Drone Returned")]))
drone_collection_manages = {
"property": "rdfs:type",
"object": drone.id_
}
drone_collection = HydraCollection(collection_name="DroneCollection",
collection_description="A collection of drones",
manages=drone_collection_manages)
# NOTE: Commands are stored in a collection. You may GET a command or you
# may DELETE it, there is not UPDATE.
command = HydraClass("Command", "Class for drone commands", endpoint=True)
command.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
command.add_supported_prop(HydraClassProp(
state.id_, "State", False, False, True))
# Used by mechanics to get newly added commands
command.add_supported_op(
HydraClassOp(
"GetCommand", "GET", None, command.id_,
possible_status=[
HydraStatus(
code=404, desc="Command not found"),
HydraStatus(
code=200, desc="Command Returned")]))
# Used by server to add new commands
command.add_supported_op(
HydraClassOp(
"AddCommand", "PUT", command.id_, None,
possible_status=[HydraStatus(code=201, desc="Command added")]))
command.add_supported_op(
HydraClassOp(
"DeleteCommand", "DELETE", None, None,
possible_status=[
HydraStatus(
code=201, desc="Command deleted")]))
command_collection_manages = {
"property": "rdfs:type",
"object": command.id_
}
command_collection = HydraCollection(collection_name="CommandCollection",
collection_description="A collection of commands",
manages=command_collection_manages)
# Data is stored as a collection. Each data object can be read.
# New data added to the collection
datastream = HydraClass("Datastream",
"Class for a datastream entry", endpoint=True)
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/QuantitativeValue", "Temperature", False, False, True))
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", False, False, True))
datastream.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "Position", False, False, True))
datastream.add_supported_op(
HydraClassOp(
"ReadDatastream", "GET", None, datastream.id_,
possible_status=[
HydraStatus(
code=404, desc="Data not found"),
HydraStatus(
code=200, desc="Data returned")]))
datastream.add_supported_op(
HydraClassOp(
"UpdateDatastream", "POST", datastream.id_, None,
possible_status=[HydraStatus(code=200, desc="Data updated")]))
datastream.add_supported_op(
HydraClassOp(
"DeleteDatastream", "DELETE", None, None,
possible_status=[HydraStatus(code=200, desc="Data deleted")]))
datastream_collection_manages = {
"property": "rdfs:type",
"object": datastream.id_
}
datastream_collection = HydraCollection(collection_name="DatastreamCollection",
collection_description="A collection of datastream",
manages=datastream_collection_manages)
# Logs to be accessed mostly by the GUI. Mechanics should add logs for
# every event.
log = HydraClass("LogEntry", "Class for a log entry", endpoint=True)
# Subject
log.add_supported_prop(HydraClassProp(
"http://schema.org/identifier", "DroneID", True, True, False))
# Predicate
log.add_supported_prop(HydraClassProp(
"http://schema.org/UpdateAction", "Update", False, True, False))
log.add_supported_prop(HydraClassProp(
"http://schema.org/ReplyAction", "Get", False, True, False))
log.add_supported_prop(HydraClassProp(
"http://schema.org/SendAction", "Send", False, True, False))
# Objects
log.add_supported_prop(HydraClassProp(
state.id_, "State", False, True, False))
log.add_supported_prop(HydraClassProp(
datastream.id_, "Data", False, True, False))
log.add_supported_prop(HydraClassProp(
command.id_, "Command", False, True, False))
# GUI will get a certain log entry.
log.add_supported_op(
HydraClassOp(
"GetLog", "GET", None, log.id_,
possible_status=[
HydraStatus(
code=404, desc="Log entry not found"),
HydraStatus(
code=200, desc="Log entry returned")]))
log.add_supported_op(
HydraClassOp(
"AddLog", "PUT", log.id_, None,
possible_status=[HydraStatus(code=201, desc="Log entry created")]))
log_collection_manages = {
"property": "rdfs:type",
"object": log.id_
}
log_collection = HydraCollection(collection_name="LogEntryCollection",
collection_description="A collection of logs",
manages=log_collection_manages)
# Single object representing the area of interest. No collections.
area = HydraClass("Area", "Class for Area of Interest of the server", endpoint=True)
# Using two positions to have a bounding box
area.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "TopLeft", False, False, True))
area.add_supported_prop(HydraClassProp(
"http://schema.org/geo", "BottomRight", False, False, True))
# Allowing updation of the area of interest
area.add_supported_op(
HydraClassOp(
"UpdateArea", "POST", area.id_, None,
possible_status=[
HydraStatus(
code=200, desc="Area of interest changed")]))
area.add_supported_op(
HydraClassOp(
"GetArea", "GET", None, area.id_,
possible_status=[
HydraStatus(
code=200, desc="Area of interest not found"),
HydraStatus(
code=200, desc="Area of interest returned")]))
message = HydraClass("Message",
"Class for messages received by the GUI interface", endpoint=True)
message.add_supported_prop(HydraClassProp(
"http://schema.org/Text", "MessageString", False, False, True))
message.add_supported_op(
HydraClassOp(
"GetMessage", "GET", None, message.id_,
possible_status=[
HydraStatus(
code=200, desc="Message not found"),
HydraStatus(
code=200, desc="Message returned")]))
message.add_supported_op(
HydraClassOp(
"DeleteMessage", "DELETE", None, None,
possible_status=[
HydraStatus(
code=200, desc="Message deleted")]))
message_collection_manages = {
"property": "rdfs:type",
"object": message.id_
}
message_collection = HydraCollection(collection_name="MessageCollection",
collection_description="A collection of messages",
manages=message_collection_manages)
api_doc.add_supported_class(drone)
api_doc.add_supported_collection(drone_collection)
api_doc.add_supported_class(state)
api_doc.add_supported_collection(state_collection)
api_doc.add_supported_class(datastream)
api_doc.add_supported_collection(datastream_collection)
api_doc.add_supported_class(log)
api_doc.add_supported_collection(log_collection)
api_doc.add_supported_class(area)
api_doc.add_supported_class(command)
api_doc.add_supported_collection(command_collection)
api_doc.add_supported_class(message)
api_doc.add_supported_collection(message_collection)
api_doc.add_baseResource()
api_doc.add_baseCollection()
api_doc.gen_EntryPoint()
return api_doc
if __name__ == "__main__":
dump = json.dumps(
doc_gen("api", "http://localhost:8080/").generate(), indent=4, sort_keys=True)
doc = '''"""\nGenerated API Documentation for Server API using server_doc_gen.py."""\n\ndoc = %s''' % dump
doc = doc.replace('true', '"true"')
doc = doc.replace('false', '"false"')
doc = doc.replace('null', '"null"')
f = open("doc.py", "w")
f.write(doc)
f.close()
| {
"repo_name": "HTTP-APIs/hydrus",
"path": "examples/drones/doc_gen.py",
"copies": "1",
"size": "12115",
"license": "mit",
"hash": 2262051825291629300,
"line_mean": 42.5791366906,
"line_max": 110,
"alpha_frac": 0.5902600083,
"autogenerated": false,
"ratio": 3.918175937904269,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5008435946204269,
"avg_score": null,
"num_lines": null
} |
# API docs: http://anilist-api.readthedocs.org/en/latest/
from logging import debug, info, warning, error
import re
from .. import AbstractInfoHandler
from data.models import UnprocessedShow, ShowType
class InfoHandler(AbstractInfoHandler):
_show_link_base = "http://anilist.co/anime/{id}"
_show_link_matcher = "https?://anilist\\.co/anime/([0-9]+)"
_season_url = "http://anilist.co/api/browse/anime?year={year}&season={season}&type=Tv"
def __init__(self):
super().__init__("anilist", "AniList")
self.rate_limit_wait = 2
def get_link(self, link):
if link is None:
return None
return self._show_link_base.format(id=link.site_key)
def extract_show_id(self, url):
if url is not None:
match = re.match(self._show_link_matcher, url, re.I)
if match:
return match.group(1)
return None
def get_episode_count(self, link, **kwargs):
return None
def get_show_score(self, show, link, **kwargs):
return None
def get_seasonal_shows(self, year=None, season=None, **kwargs):
#debug("Getting season shows: year={}, season={}".format(year, season))
# Request season page from AniDB
#url = self._season_url.format(year=year, season=season)
#response = self._site_request(url, **kwargs)
#if response is None:
# error("Cannot get show list")
# return list()
# Parse page
#TODO
return list()
def find_show(self, show_name, **kwargs):
return list()
def find_show_info(self, show_id, **kwargs):
return None
def _site_request(self, url, **kwargs):
return self.request(url, html=True, **kwargs)
| {
"repo_name": "TheEnigmaBlade/holo",
"path": "src/services/info/anilist.py",
"copies": "2",
"size": "1564",
"license": "mit",
"hash": -4915715992756173000,
"line_mean": 26.4385964912,
"line_max": 87,
"alpha_frac": 0.6777493606,
"autogenerated": false,
"ratio": 2.9343339587242028,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8573816103268348,
"avg_score": 0.20765344321117105,
"num_lines": 57
} |
# API docs: https://kitsu.docs.apiary.io
from logging import debug, info, warning, error
import re
from .. import AbstractInfoHandler
from data.models import UnprocessedShow, ShowType
class InfoHandler(AbstractInfoHandler):
_show_link_base = "https://kitsu.io/anime/{slug}"
_show_link_matcher = "https?://kitsu\.io/anime/([a-zA-Z0-9-]+)"
_season_url = "https://kitsu.io/api/edge/anime?filter[year]={year}&filter[season]={season}&filter[subtype]=tv&page[limit]=20"
_api_base = "https:///kitsu.io/api/edge/anime"
def __init__(self):
super().__init__("kitsu", "Kitsu")
def get_link(self, link):
if link is None:
return None
return self._show_link_base.format(slug=link.site_key)
def extract_show_id(self, url):
if url is not None:
match = re.match(self._show_link_matcher, url, re.I)
if match:
return match.group(1)
return None
def get_episode_count(self, link, **kwargs):
#debug("Getting episode count")
# Request show data from Kitsu
#url = self._api_base + "?filter[slug]=" + link.site_key + "&fields[anime]=episodeCount"
#response = self._site_request(url, **kwargs)
#if response is None:
# error("Cannot get show data")
# return None
# Parse show data
#count = response["data"][0]["attributes"]["episodeCount"]
#if count is None:
# warning(" Count not found")
# return None
#return count
return None
def get_show_score(self, show, link, **kwargs):
#debug("Getting show score")
# Request show data
#url = self._api_base + "?filter[slug]=" + link.site_key + "&fields[anime]=averageRating"
#response = self._site_request(url, **kwargs)
#if response is None:
# error("Cannot get show data")
# return None
# Find score
#score = response["data"][0]["attributes"]["averageRating"]
#if score is None:
# warning(" Score not found")
# return None
#return score
return None
def get_seasonal_shows(self, year=None, season=None, **kwargs):
#debug("Getting season shows: year={}, season={}".format(year, season))
# Request season data from Kitsu
#url = self._season_url.format(year=year, season=season)
#response = self._site_request(url, **kwargs)
#if response is None:
# error("Cannot get show list")
# return list()
# Parse data
#TODO
return list()
def find_show(self, show_name, **kwargs):
#url = self._api_base + "?filter[text]=" + show_name
#result = self._site_request(url, **kwargs)
#if result is None:
# error("Failed to find show")
# return list()
#shows = list()
#TODO
#return shows
return list()
def find_show_info(self, show_id, **kwargs):
#debug("Getting show info for {}".format(show_id))
# Request show data from Kitsu
#url = self._api_base + "?filter[slug]=" + show_id + "&fields[anime]=titles,abbreviatedTitles"
#response = self._site_request(url, **kwargs)
#if response is None:
# error("Cannot get show data")
# return None
# Parse show data
#name_english = response["data"][0]["attributes"]["titles"]["en"]
#if name_english is None:
# warning(" English name was not found")
# return None
#names = [name_english]
#return UnprocessedShow(self.key, id, None, names, ShowType.UNKNOWN, 0, False)
return None
def _site_request(self, url, **kwargs):
return self.request(url, json=True, **kwargs)
| {
"repo_name": "andrewhillcode/holo",
"path": "src/services/info/kitsu.py",
"copies": "2",
"size": "3320",
"license": "mit",
"hash": -7062429695393677000,
"line_mean": 27.3760683761,
"line_max": 126,
"alpha_frac": 0.6578313253,
"autogenerated": false,
"ratio": 2.9537366548042705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4611567980104271,
"avg_score": null,
"num_lines": null
} |
# A piece of code to get the list of registered endpoints on keystone
# can be filtered by service id if it is specified
# Execution example: python listAllRegisteredEPs.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_ID]
__author__ = 'Mohammad'
import sys
import getopt
from keystoneclient.v2_0 import client
def main(argv):
try:
opts, args = getopt.getopt(argv,"hu:p:t:a:s:",["username=","password=","tenant_name=","auth_url=","service_id="])
except getopt.GetoptError:
print 'Usage: python listAllRegisteredEPs.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_ID]'
exit(0)
user_name = None
passwd = None
tenant_name = None
auth_url = None
s_id = None
for opt, arg in opts:
if opt == '-h':
print 'Usage: python listAllRegisteredEPs.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_ID]'
exit(0)
elif opt in ("-u", "--username"):
user_name = arg
elif opt in ("-p", "--password"):
passwd = arg
elif opt in ("-t", "--tenant_name"):
tenant_name = arg
elif opt in ("-a", "--auth_url"):
auth_url = arg
elif opt in ("-s", "--service_id"):
s_id = arg
if user_name is None:
user_name = 'dummy'
if passwd is None:
passwd = 'dummy'
if tenant_name is None:
tenant_name = 'dummy'
if auth_url is None:
auth_url = 'http://dummy:5000/v2.0'
if s_id is None:
s_id = None
keystone = client.Client(username=user_name, password=passwd, tenant_name=tenant_name, auth_url=auth_url)
ep_list = keystone.endpoints.list()
if s_id is None:
for item in ep_list:
print "Service ID: \"" + item._info['service_id'] + "\" Region: \"" + item._info['region'] + "\" Public URL: \"" + item._info['publicurl'] + "\" Endpoint ID: \"" + item._info['id'] + "\"\n"
return 1
else:
for item in ep_list:
if item._info['service_id'] == s_id:
print "Service ID: \"" + item._info['service_id'] + "\" Region: \"" + item._info['region'] + "\" Public URL: \"" + item._info['publicurl'] + "\" Endpoint ID: \"" + item._info['id'] + "\"\n"
return 1
print "Endpoint not found."
return 0
if __name__ == "__main__":
main(sys.argv[1:])
| {
"repo_name": "MobileCloudNetworking/dssaas",
"path": "dss-side-scripts/listAllRegisteredEPs.py",
"copies": "1",
"size": "2428",
"license": "apache-2.0",
"hash": -797558676089607300,
"line_mean": 31.8108108108,
"line_max": 205,
"alpha_frac": 0.5514827018,
"autogenerated": false,
"ratio": 3.3910614525139664,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9429101275258911,
"avg_score": 0.0026885758110111705,
"num_lines": 74
} |
# A piece of code to get the list of registered services on keystone
# Execution example: python delRegisteredEP.py -e <ENDPOINT_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]
__author__ = 'Mohammad'
import sys
import getopt
from keystoneclient.v2_0 import client
def main(argv):
try:
opts, args = getopt.getopt(argv,"he:u:p:t:a:",["endpoint_id=","username=","password=","tenant_name=","auth_url="])
except getopt.GetoptError:
print 'Usage: python delRegisteredEP.py -e <ENDPOINT_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]'
exit(0)
user_name = None
passwd = None
tenant_name = None
auth_url = None
e_id = None
for opt, arg in opts:
if opt == '-h':
print 'Usage: python delRegisteredEP.py -e <ENDPOINT_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]'
exit(0)
elif opt in ("-u", "--username"):
user_name = arg
elif opt in ("-p", "--password"):
passwd = arg
elif opt in ("-t", "--tenant_name"):
tenant_name = arg
elif opt in ("-a", "--auth_url"):
auth_url = arg
elif opt in ("-e", "--endpoint_id"):
e_id = arg
if user_name is None:
user_name = 'dummy'
if passwd is None:
passwd = 'dummy'
if tenant_name is None:
tenant_name = 'dummy'
if auth_url is None:
auth_url = 'http://dummy:5000/v2.0'
if e_id is None:
print 'Endpoint ID is mandatory!'
exit(0)
keystone = client.Client(username=user_name, password=passwd, tenant_name=tenant_name, auth_url=auth_url)
ep_list = keystone.endpoints.list()
for item in ep_list:
if item._info['id'] == e_id:
res = keystone.endpoints.delete(e_id)
print res.__repr__()
return 1
print "EP not found."
return 0
if __name__ == "__main__":
main(sys.argv[1:])
| {
"repo_name": "MobileCloudNetworking/dssaas",
"path": "dss-side-scripts/delRegisteredEP.py",
"copies": "1",
"size": "1976",
"license": "apache-2.0",
"hash": -1880547038697404200,
"line_mean": 27.2285714286,
"line_max": 128,
"alpha_frac": 0.5607287449,
"autogenerated": false,
"ratio": 3.4186851211072664,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4479413866007267,
"avg_score": null,
"num_lines": null
} |
# A piece of code to get the list of registered services on keystone
# Execution example: python delRegisteredService.py -s <SERVICE_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]
__author__ = 'Mohammad'
import sys
import getopt
from keystoneclient.v2_0 import client
def main(argv):
try:
opts, args = getopt.getopt(argv,"hs:u:p:t:a:",["service_id=","username=","password=","tenant_name=","auth_url="])
except getopt.GetoptError:
print 'Usage: python delRegisteredService.py -s <SERVICE_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]'
exit(0)
user_name = None
passwd = None
tenant_name = None
auth_url = None
s_id = None
for opt, arg in opts:
if opt == '-h':
print 'Usage: python delRegisteredService.py -s <SERVICE_ID> -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL]'
exit(0)
elif opt in ("-u", "--username"):
user_name = arg
elif opt in ("-p", "--password"):
passwd = arg
elif opt in ("-t", "--tenant_name"):
tenant_name = arg
elif opt in ("-a", "--auth_url"):
auth_url = arg
elif opt in ("-s", "--service_id"):
s_id = arg
if user_name is None:
user_name = 'dummy'
if passwd is None:
passwd = 'dummy'
if tenant_name is None:
tenant_name = 'dummy'
if auth_url is None:
auth_url = 'http://dummy:5000/v2.0'
if s_id is None:
print 'Service ID param is mandatory! '
exit(0)
keystone = client.Client(username=user_name, password=passwd, tenant_name=tenant_name, auth_url=auth_url)
service_list = keystone.services.list()
for item in service_list:
if item._info['id'] == s_id:
res = keystone.services.delete(s_id)
print res.__repr__()
return 1
print "Service not found."
return 0
if __name__ == "__main__":
main(sys.argv[1:])
| {
"repo_name": "MobileCloudNetworking/dssaas",
"path": "dss-side-scripts/delRegisteredService.py",
"copies": "1",
"size": "2005",
"license": "apache-2.0",
"hash": 2569133459635980000,
"line_mean": 27.6428571429,
"line_max": 132,
"alpha_frac": 0.566084788,
"autogenerated": false,
"ratio": 3.456896551724138,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4522981339724138,
"avg_score": null,
"num_lines": null
} |
# A piece of code to get the list of registered services on keystone
# Execution example: python listAllRegisteredServices.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_NAME]
# SERVICE_NAME parameter can be just a part of the service name.
# For example -s dss can return results that have dss, dssaas, dssservice, etc.
__author__ = 'Mohammad'
import sys
import getopt
from keystoneclient.v2_0 import client
def main(argv):
try:
opts, args = getopt.getopt(argv,"hu:p:t:a:s:",["username=","password=","tenant_name=","auth_url=","service_name="])
except getopt.GetoptError:
print 'Usage: python listAllRegisteredServices.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_NAME]'
exit(0)
user_name = None
passwd = None
tenant_name = None
auth_url = None
s_name = None
for opt, arg in opts:
if opt == '-h':
print 'Usage: python listAllRegisteredServices.py -u [USERNAME] -p [PASSWORD] -t [TENANT_NAME] -a [AUTH_URL] -s [SERVICE_NAME]'
exit(0)
elif opt in ("-u", "--username"):
user_name = arg
elif opt in ("-p", "--password"):
passwd = arg
elif opt in ("-t", "--tenant_name"):
tenant_name = arg
elif opt in ("-a", "--auth_url"):
auth_url = arg
elif opt in ("-s", "--service_name"):
s_name = arg
if user_name is None:
user_name = 'dummy'
if passwd is None:
passwd = 'dummy'
if tenant_name is None:
tenant_name = 'dummy'
if auth_url is None:
auth_url = 'http://dummy:5000/v2.0'
if s_name is None:
s_name = None
keystone = client.Client(username=user_name, password=passwd, tenant_name=tenant_name, auth_url=auth_url)
service_list = keystone.services.list()
if s_name is None:
for item in service_list:
print "Service ID: \"" + item._info['id'] + "\" Description: \"" + item._info['description'] + "\" Type: \"" + item._info['type'] + "\"\n"
return 1
else:
service_found = 0
for item in service_list:
if s_name in item._info['type']:
print "Service ID: \"" + item._info['id'] + "\" Description: \"" + item._info['description'] + "\" Type: \"" + item._info['type'] + "\"\n"
service_found = 1
if service_found == 1:
return 1
else:
print "Service not found."
return 0
if __name__ == "__main__":
main(sys.argv[1:])
| {
"repo_name": "MobileCloudNetworking/dssaas",
"path": "dss-side-scripts/listAllRegisteredServices.py",
"copies": "1",
"size": "2556",
"license": "apache-2.0",
"hash": -8662053742193196000,
"line_mean": 31.3544303797,
"line_max": 154,
"alpha_frac": 0.5661189358,
"autogenerated": false,
"ratio": 3.515818431911967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4581937367711967,
"avg_score": null,
"num_lines": null
} |
"""API endpoint for the AsciiPic API."""
import cherrypy
from cherrypy import tools
from asciipic.api import base as base_api
from asciipic.db.managers import user
from asciipic.tasks import base as base_task
from asciipic.tasks import echo_task
class EchoEndpoint(base_api.BaseAPI):
"""Action related to users."""
# A list that contains all the resources (endpoints) available for the
# current metadata service
# Whether this application should be available for clients
exposed = True
# pylint: disable=no-self-use
@user.check_credentials
@tools.json_out()
def POST(self, **kwargs):
"""Post a new echo job."""
data = kwargs.pop("data", "")
sleep = bool(data.lstrip("echo").strip())
task = echo_task.Echo(sleep=sleep)
job = base_task.run_task(task)
response = {
"meta": {
"status": True,
"verbose": "Ok",
"job_id": job.id,
},
"content": sleep
}
return response
# pylint: disable=no-self-use, arguments-differ
@user.check_credentials
@tools.json_out()
@cherrypy.popargs('job_id')
def GET(self, job_id=None):
"""Get the result of the echo job."""
job = base_task.get_job_by_id(job_id)
response = {
"meta": {
"status": True,
"verbose": "Ok",
"job_status": job.status,
"job_id": job.id
},
"content": job.result
}
return response
| {
"repo_name": "micumatei/asciipic",
"path": "asciipic/api/api_endpoint/echo/__init__.py",
"copies": "1",
"size": "1581",
"license": "mit",
"hash": -4969057752802292000,
"line_mean": 26.2586206897,
"line_max": 74,
"alpha_frac": 0.5572422517,
"autogenerated": false,
"ratio": 3.923076923076923,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49803191747769227,
"avg_score": null,
"num_lines": null
} |
"""API Endpoint
Validates inputs to the Security Fairy tool,
then creates and executes the State Machine
which orchestrates the Security Fairy
Lambda functions.
"""
import json
import re
import os
import string
import boto3
from botocore.exceptions import ProfileNotFound
from aws_entity import AWSEntity
try:
SESSION = boto3.session.Session(profile_name='training', region_name='us-east-1')
except ProfileNotFound as pnf:
SESSION = boto3.session.Session()
def lambda_handler(event, context):
"""
Executed by the Lambda service.
Returns the validated inputs and invokes
the State Machine that orchestrates
Security Fairy.
"""
api_return_payload = {
'statusCode': 500,
'headers':{
'Content-Type':'application/json'
},
'body':'Security Fairy Internal Server Error.'
}
domain = get_domain(event)
method = event['httpMethod']
if method == 'GET':
return api_website(event, domain)
if method == 'POST':
return post_response(event, domain)
return api_return_payload
def post_response(event, domain):
api_return_payload = {
'statusCode': 500,
'headers':{
'Content-Type':'application/json'
},
'body':'Security Fairy Internal Server Error.'
}
print(event)
try:
inputs = validate_inputs(event)
invoke_state_machine(inputs)
api_return_payload['statusCode'] = 200
api_return_payload['body'] = 'The auditing process can take up to 20 minutes. An email will be sent upon completion.'
except Exception as error:
print(error)
api_return_payload['statusCode'] = 200
api_return_payload['body'] = "Unsuccessful: {error}".format(error=error)
print api_return_payload
return api_return_payload
def get_domain(event):
# Supports test invocations from API Gateway
if event['headers'] is None:
return "https://testinvocation/start"
# Extracts the domain from event object based on for both api gateway URLs
# or custom domains
if 'amazonaws.com' in event['headers']['Host']:
return "https://{domain}/{stage}{path}".format(domain=event['headers']['Host'],
stage=event['requestContext']['stage'],
path=event['path'])
else:
return "https://{domain}{path}".format(domain=event['headers']['Host'],
path=event['path'])
def invoke_state_machine(inputs):
"""Invoke state machine"""
print json.dumps(inputs)
sfn_client = SESSION.client('stepfunctions')
response = sfn_client.start_execution(stateMachineArn=os.environ['state_machine'],
input=json.dumps(inputs)
)
print(response)
def validate_inputs(event):
"""Validate inputs"""
input_payload = json.loads(event['body'])
num_days = validate_date_window(input_payload.get('num_days', 7))
entity_arn = validate_entity_arn(input_payload.get('entity_arn'))
return {
'num_days' : num_days*-1,
'entity_arn': entity_arn
}
def validate_date_window(days):
"""Validate the date range for the Security Fairy query"""
window = abs(days)
if window > 30 or window < 1:
print window
raise ValueError('Valid number of days is between 1 and 30 inclusive.')
return window
def validate_entity_arn(entity_arn):
"""Validate entity ARN"""
# account_number = SESSION.client('sts').get_caller_identity()["Account"]
# Roles are valid: arn:aws:iam::842337631775:role/1S-Admins
# arn:aws:sts::281782457076:assumed-role/1S-Admins/alex
# Users are invalid: arn:aws:iam::842337631775:user/aaron
try:
arn = AWSEntity(entity_arn)
except Exception:
raise ValueError('Malformed ARN. Please enter a role ARN.')
print(arn.entity_type)
if 'user' in arn.entity_type:
raise ValueError('Users not supported. Please enter a role ARN.')
if 'group' in arn.entity_type:
raise ValueError('Groups not supported. Please enter a role ARN.')
if not arn.is_assumed_role() and not arn.is_role():
raise ValueError('Invalid Resource ARN.')
# pattern = re.compile("arn:aws:(sts|iam)::(\d{12})?:(role|assumed-role)\/(.*)")
# if not pattern.match(entity_arn):
# raise ValueError('Invalid Resource ARN.')
assumed_role_pattern = re.compile("arn:aws:sts::(\d{12})?:assumed-role\/(.*)\/(.*)")
if not assumed_role_pattern.match(entity_arn):
refactored_arn = "arn:aws:sts::" + arn.get_account_number() + ":assumed-role/" + arn.get_entity_name()
entity_arn = refactored_arn
SESSION.client('iam').get_role(RoleName=arn.get_entity_name())
return entity_arn
def invoke_state_machine(inputs):
print(json.dumps(inputs))
response = SESSION.client('stepfunctions').start_execution( stateMachineArn=os.environ['state_machine'],
input=json.dumps(inputs))
print(response)
def api_website(event, domain):
body = """
<html>
<body bgcolor=\"#E6E6FA\">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.form {
padding-left: 1cm;
}
.div{
padding-left: 1cm;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var entity_arn = document.getElementById("entity_arn").value;
var dict = {};
dict["entity_arn"] = entity_arn;
if (document.getElementById("num_days").value != "") {
dict["num_days"] = Number(document.getElementById("num_days").value);
}
else{
dict["num_days"] = 30;
};
$.ajax({
type: 'POST',
headers: {
'Content-Type':'application/json',
'Accept':'text/html'
},
url:'$domain',
crossDomain: true,
data: JSON.stringify(dict),
dataType: 'text',
success: function(responseData) {
alert(responseData);
//document.getElementById("id").innerHTML = responseData;
document.getElementById("entity_arn").value="";
document.getElementById("num_days").value="";
},
error: function (responseData) {
//alert(responseData);
alert('POST failed.'+ JSON.stringify(responseData));
}
});
});
});
</script>
</head>
<title>Security Fairy IAM Policy Remediation Tool</title>
<h1 class="div">Security Fairy IAM Remediation Tool</h1>
<body>
<form class="form" action="" method="post">
<textarea rows="1" cols="50" name="text" id="entity_arn" placeholder="arn:aws:iam::0123456789:role/roleName"></textarea>
</form>
<form class="form" action="" method="post">
<textarea rows="1" cols="50" name="text" id="num_days" placeholder="Scan the logs for between 1-30 days (Enter Number)"></textarea>
</form>
<div class="div"><button class="btn btn-primary">Audit Entity</button></div>
<div class="div" id="id"></div>
</body>
</html>
"""
return {
"statusCode": 200,
"headers": {
"Content-Type": 'text/html',
"Access-Control-Allow-Origin": "*"
},
"body": string.Template(body).safe_substitute({"domain": domain})
}
if __name__ == '__main__':
print(validate_entity_arn('arn:aws:sts::842337631775:assumed-role/1S-Admins/potato'))
| {
"repo_name": "1Strategy/security-fairy",
"path": "api_endpoint.py",
"copies": "1",
"size": "8262",
"license": "apache-2.0",
"hash": 674863282986904700,
"line_mean": 30.534351145,
"line_max": 212,
"alpha_frac": 0.5884773663,
"autogenerated": false,
"ratio": 3.8285449490268766,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9904684050406038,
"avg_score": 0.0024676529841676374,
"num_lines": 262
} |
""" API endpoints for admin controls """
import gzip
import json
from paste.httpheaders import CONTENT_DISPOSITION # pylint: disable=E0611
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.response import FileIter
from pyramid.view import view_config, view_defaults
from pyramid_duh import argify
from six import BytesIO
from pypicloud.route import AdminResource
@view_defaults(context=AdminResource, subpath=(), permission='admin',
renderer='json')
class AdminEndpoints(object):
""" Collection of admin endpoints """
def __init__(self, request):
self.request = request
@view_config(name='rebuild')
def rebuild_package_list(self):
""" Rebuild the package cache in the database """
self.request.db.reload_from_storage()
return self.request.response
@view_config(name='pending_users', request_method='GET')
def get_pending_users(self):
""" Get the list of pending users """
return self.request.access.pending_users()
@view_config(name='user', request_method='GET')
def get_users(self):
""" Get the list of users """
return self.request.access.user_data()
@view_config(name='user', subpath=('username/*'), request_method='GET')
def get_user(self):
""" Get a single user """
username = self.request.named_subpaths['username']
return self.request.access.user_data(username)
@view_config(name='user', subpath=('username/*'), request_method='DELETE')
def delete_user(self):
""" Delete a user """
username = self.request.named_subpaths['username']
self.request.access.delete_user(username)
return self.request.response
@view_config(name='user', subpath=('username/*', 'approve'),
request_method='POST')
def approve_user(self):
""" Approve a pending user """
username = self.request.named_subpaths['username']
self.request.access.approve_user(username)
return self.request.response
@view_config(name='user', subpath=('username/*', 'admin'),
request_method='POST')
@argify
def set_admin_status(self, admin):
""" Approve a pending user """
username = self.request.named_subpaths['username']
self.request.access.set_user_admin(username, admin)
return self.request.response
@view_config(name='user', subpath=('username/*', 'group', 'group/*'),
request_method='PUT')
@view_config(name='user', subpath=('username/*', 'group', 'group/*'),
request_method='DELETE')
def mutate_group_member(self):
""" Add a user to a group """
username = self.request.named_subpaths['username']
group = self.request.named_subpaths['group']
self.request.access.edit_user_group(username, group,
self.request.method == 'PUT')
return self.request.response
@view_config(name='group', request_method='GET')
def get_groups(self):
""" Get the list of groups """
return self.request.access.groups()
@view_config(name='group', subpath=('group/*'), request_method='PUT')
def create_group(self):
""" Create a group """
group = self.request.named_subpaths['group']
if group in ('everyone', 'authenticated'):
return HTTPBadRequest("'%s' is a reserved name" % group)
self.request.access.create_group(group)
return self.request.response
@view_config(name='group', subpath=('group/*'), request_method='DELETE')
def delete_group(self):
""" Delete a group """
group = self.request.named_subpaths['group']
self.request.access.delete_group(group)
return self.request.response
@view_config(name='user', subpath=('username/*', 'permissions'))
def get_user_permissions(self):
""" Get the package permissions for a user """
username = self.request.named_subpaths['username']
return self.request.access.user_package_permissions(username)
@view_config(name='group', subpath=('group/*'))
def get_group(self):
""" Get the members and package permissions for a group """
group = self.request.named_subpaths['group']
return {
'members': self.request.access.group_members(group),
'packages': self.request.access.group_package_permissions(group),
}
@view_config(name='package', subpath=('package/*'), request_method='GET')
def get_package_permissions(self):
""" Get the user and group permissions set on a package """
package = self.request.named_subpaths['package']
user_perms = [{'username': key, 'permissions': val} for key, val in
self.request.access.user_permissions(package).iteritems()]
group_perms = [{'group': key, 'permissions': val} for key, val in
self.request.access.group_permissions(package).iteritems()]
return {
'user': user_perms,
'group': group_perms,
}
@view_config(name='package',
subpath=('package/*', 'type/user|group/r',
'name/*', 'permission/read|write/r'),
request_method='PUT')
@view_config(name='package',
subpath=('package/*', 'type/user|group/r',
'name/*', 'permission/read|write/r'),
request_method='DELETE')
def edit_permission(self):
""" Edit user permission on a package """
package = self.request.named_subpaths['package']
name = self.request.named_subpaths['name']
permission = self.request.named_subpaths['permission']
owner_type = self.request.named_subpaths['type']
if owner_type == 'user':
self.request.access.edit_user_permission(
package, name, permission, self.request.method == 'PUT')
else:
self.request.access.edit_group_permission(
package, name, permission,
self.request.method == 'PUT')
return self.request.response
@view_config(name='register', request_method='POST')
@argify
def toggle_allow_register(self, allow):
""" Allow or disallow user registration """
self.request.access.set_allow_register(allow)
return self.request.response
@view_config(name='acl.json.gz', request_method='GET')
def download_access_control(self):
""" Download the ACL data as a gzipped-json file """
data = self.request.access.dump()
compressed = BytesIO()
zipfile = gzip.GzipFile(mode='wb', fileobj=compressed)
json.dump(data, zipfile, separators=(',', ':'))
zipfile.close()
compressed.seek(0)
disp = CONTENT_DISPOSITION.tuples(filename='acl.json.gz')
self.request.response.headers.update(disp)
self.request.response.app_iter = FileIter(compressed)
return self.request.response
| {
"repo_name": "a-tal/pypicloud",
"path": "pypicloud/views/admin.py",
"copies": "1",
"size": "7051",
"license": "mit",
"hash": 5785213240279692000,
"line_mean": 39.7572254335,
"line_max": 82,
"alpha_frac": 0.6149482343,
"autogenerated": false,
"ratio": 4.152532391048292,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5267480625348292,
"avg_score": null,
"num_lines": null
} |
"""API endpoints for bookmarks."""
from flask import url_for, g
from flask.views import MethodView
from flask_login import login_required
from flask_smorest import Blueprint, abort
from bookmarks import csrf
from bookmarks.models import Bookmark
from bookmarks.logic import _get, _post, _put, _delete
from .pagination import CursorPage
from .schemas import (
BookmarkSchema,
BookmarkPOSTSchema,
BookmarkPUTSchema,
BookmarksQueryArgsSchema
)
bookmarks_api = Blueprint('bookmarks_api', 'Bookmarks', url_prefix='/api/v1/bookmarks/',
description='Operations on Bookmarks')
@bookmarks_api.route('/')
class BookmarksAPI(MethodView):
decorators = [csrf.exempt]
@bookmarks_api.arguments(BookmarksQueryArgsSchema, location='query')
@bookmarks_api.response(BookmarkSchema(many=True))
@bookmarks_api.paginate(CursorPage)
def get(self, args):
"""Return all bookmarks of the authenticated user."""
query = _get(args)
return query
@bookmarks_api.route('/')
class BookmarksAuthAPI(MethodView):
decorators = [csrf.exempt, login_required]
@bookmarks_api.arguments(BookmarkPOSTSchema)
def post(self, data):
"""Add new bookmark and add its tags if don't exist."""
bookmark = Bookmark.query.filter_by(url=data['url']).scalar()
if bookmark is not None:
abort(409, message='Url already exists')
bookmark_id = _post(data)
bookmark_url = url_for(
'bookmarks_api.BookmarkAPI',
id=bookmark_id,
_method='GET',
_external=True
)
return {}, 201, {'location': bookmark_url}
@bookmarks_api.route('/<int:id>')
class BookmarkAPI(MethodView):
decorators = [csrf.exempt]
@bookmarks_api.response(BookmarkSchema())
def get(self, id):
"""Return bookmark."""
return Bookmark.query.get(id) or abort(404)
@bookmarks_api.route('/<int:id>')
class BookmarkAuthAPI(BookmarkAPI):
decorators = [csrf.exempt, login_required]
@bookmarks_api.arguments(BookmarkPUTSchema)
def put(self, data, id):
"""
Update an existing bookmark.
In case tag(s) changes check if no other bookmark is related with
that tag(s) and if not, delete it.
"""
bookmark = Bookmark.query.get(id)
if bookmark is None:
abort(404, message='Bookmark not found')
if 'url' in data and data['url'] != bookmark.url:
existing_url = Bookmark.query.filter_by(url=data['url']).scalar()
if existing_url is not None:
abort(409, message='New url already exists')
_put(id, data)
bookmark_url = url_for(
'bookmarks_api.BookmarkAPI',
id=bookmark.id,
_method='GET',
_external=True
)
return {}, 204, {'location': bookmark_url}
@bookmarks_api.response(code=204)
def delete(self, id):
"""Delete a bookmark."""
bookmark = Bookmark.query.get(id)
if bookmark is None:
abort(404, message='Bookmark not found')
if bookmark.user_id != g.user.id:
abort(403, message='Forbidden')
_delete(id)
| {
"repo_name": "ev-agelos/Python-bookmarks",
"path": "bookmarks/api/bookmarks.py",
"copies": "1",
"size": "3229",
"license": "mit",
"hash": -7096757027590723000,
"line_mean": 28.623853211,
"line_max": 88,
"alpha_frac": 0.6262000619,
"autogenerated": false,
"ratio": 3.9282238442822384,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5054423906182238,
"avg_score": null,
"num_lines": null
} |
"""API endpoints for users."""
from flask import g, url_for, request
from flask.views import MethodView
from flask_login import login_required
from flask_smorest import abort, Blueprint
from bookmarks import db, csrf
from bookmarks import utils
from bookmarks.users.models import User
from .schemas import UserPUTSchema, UserSchema
users_api = Blueprint('users_api', 'Users', url_prefix='/api/v1/users/',
description='Operations on Users')
@users_api.route('/me')
@users_api.response(UserSchema())
@csrf.exempt
@login_required
def me():
return g.user
@users_api.route('/')
class UsersAPI(MethodView):
decorators = [csrf.exempt]
@users_api.response(UserSchema(many=True, exclude=("email", )))
def get(self):
"""Return all users."""
return User.query.filter_by(active=True)
@users_api.route('/<int:id>')
class UserAPI(MethodView):
decorators = [csrf.exempt, login_required]
@users_api.response(UserSchema(exclude=("email", )))
def get(self, id):
"""Return user with given id."""
return (
id == g.user.id and g.user
or User.query.get(id)
or abort(404, message='User not found')
)
@users_api.arguments(UserPUTSchema)
@users_api.response(code=204)
def put(self, data, id):
"""Update an existing user."""
id != g.user.id and abort(403)
if data.get('username') and data['username'] != g.user.username:
if User.query.filter_by(username=data['username']).scalar():
abort(409, message='Username already taken')
g.user.username = data['username']
if data.get('email') and data['email'] != g.user.email:
if User.query.filter_by(email=data['email']).scalar():
abort(409, message='Email already taken')
# XXX it should revoke current API connection
g.user.auth_token = g.user.generate_auth_token(email=data['email'])
activation_link = url_for('auth_api.confirm', token=g.user.auth_token,
_external=True)
text = f'Click the link to confim your email address:\n{activation_link}'
utils.send_email('Email change confirmation - PyBook', data['email'], text)
if any(key in data for key in ('currentPassword', 'newPassword', 'confirmPassword')):
if data['newPassword'] == '':
abort(409, message="New password must not be empty")
if data['newPassword'] != data['confirmPassword']:
abort(409, message='Passwords differ')
if not g.user.is_password_correct(data['currentPassword']):
abort(409, message='Current password is wrong')
g.user.auth_token = ''
g.user.password = data['newPassword']
text = (
'The password for your PyBook account on <a href="{}">{}</a> '
'has successfully\nbeen changed.\n\nIf you did not initiate '
'this change, please contact the administrator immediately.'
).format(request.host_url, request.host_url)
utils.send_email('Password changed', g.user.email, text)
db.session.add(g.user)
db.session.commit()
| {
"repo_name": "ev-agelos/Python-bookmarks",
"path": "bookmarks/api/users.py",
"copies": "1",
"size": "3278",
"license": "mit",
"hash": 2982480249049388500,
"line_mean": 36.25,
"line_max": 93,
"alpha_frac": 0.6070774863,
"autogenerated": false,
"ratio": 3.95416164053076,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005190685679977876,
"num_lines": 88
} |
"""API endpoints for votes."""
from flask import url_for, g
from flask.views import MethodView
from flask_login import login_required
from flask_smorest import Blueprint, abort
from bookmarks import csrf
from bookmarks.models import Bookmark, Vote
from .schemas import VoteSchema, VotePOSTSchema, VotePUTSchema
from ..logic import _post_vote, _put_vote, _delete_vote
votes_api = Blueprint('votes_api', 'Votes', url_prefix='/api/v1/votes/',
description='Operations on Votes')
@votes_api.route('/')
class VotesAPI(MethodView):
decorators = [login_required, csrf.exempt]
@votes_api.response(VoteSchema(many=True))
def get(self):
"""Get all votes."""
return Vote.query.filter_by(user_id=g.user.id).all()
@votes_api.arguments(VotePOSTSchema)
def post(self, data):
"""Add a new vote for a bookmark."""
if Vote.query.filter_by(user_id=g.user.id, bookmark_id=data['bookmark_id']).scalar():
abort(409, message='Vote already exists')
bookmark = Bookmark.query.get(data['bookmark_id'])
if bookmark is None:
abort(404, message='Bookmark not found')
vote_id = _post_vote(bookmark, data['direction'])
vote_url = url_for(
'votes_api.VoteAPI',
id=vote_id,
_method='GET',
_external=True
)
return {}, 201, {'location': vote_url}
@votes_api.route('/<int:id>')
class VoteAPI(MethodView):
decorators = [login_required, csrf.exempt]
@votes_api.response(VoteSchema())
def get(self, id):
vote = Vote.query.get(id)
if vote.user != g.user:
abort(403, message='forbidden')
return vote or abort(404, message='Vote not found')
@votes_api.arguments(VotePUTSchema)
def put(self, data, id):
"""Update an existing vote for a bookmark."""
vote = Vote.query.get(id)
if vote is None:
abort(404, message='Vote not found')
if vote.user != g.user:
abort(403, message='Vote belongs to different user')
_put_vote(vote, data['direction'])
vote_url = url_for(
'votes_api.VoteAPI',
id=vote.id,
_method='GET',
_external=True
)
return {}, 204, {'location': vote_url}
@votes_api.response(code=204)
def delete(self, id):
"""Delete a vote for a bookmark."""
vote = Vote.query.get(id)
if vote is None:
abort(404, message='Vote not found')
if vote.user != g.user:
abort(403, message='Vote belongs to different user')
_delete_vote(vote)
| {
"repo_name": "ev-agelos/Python-bookmarks",
"path": "bookmarks/api/votes.py",
"copies": "1",
"size": "2659",
"license": "mit",
"hash": -5881221931589563000,
"line_mean": 30.6547619048,
"line_max": 93,
"alpha_frac": 0.5979691613,
"autogenerated": false,
"ratio": 3.602981029810298,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4700950191110298,
"avg_score": null,
"num_lines": null
} |
## API End Points
CREATE_USER = "/createuser"
CREDENTIALS = "/auth/credentials"
GET_PLAYER = "/getplayer"
GET_FRIENDS = "/getfriends"
SELECT_INIT_CHARACTER = "/selectinitialcharacter"
UNLOCK_STAGE = "/unlockstagegoo"
FINISH_TUTORIAL = "/finishTutorial"
STAGE_START = "/stagestart"
STAGE_INFO = "/stageinfo"
STAGE_CLEAR = "/stageclear"
GACHA = "/gacha"
MAP_REWARD = "/claimmapreward"
STAMP_REWARD = "/claimstampreward"
LUNCHBOX = "/setlunchbox"
PURCHASE = "/purchase"
GET_INBOX = "/getinbox"
## API Data Calls
GAME_DATA_VERSION = 30576
## Initial Charaters duing the tutorials
INIT_CHARACTERS = ["CBS_CHAR_FOOD_HERO_026",
"CBS_CHAR_FOOD_HERO_001",
"CBS_CHAR_FOOD_HERO_016",
"CBS_CHAR_FOOD_HERO_004",
"CBS_CHAR_FOOD_HERO_010"]
STAGE_IDS = ["SBS_AREA01_NORMAL_STAGE01",
"SBS_AREA01_NORMAL_STAGE02",
"SBS_AREA01_MIDBOSS_STAGE01",
"SBS_AREA01_NORMAL_STAGE03",
"SBS_AREA01_NORMAL_STAGE04",
"SBS_AREA01_NORMAL_STAGE05",
"SBS_AREA01_NORMAL_STAGE06",
"SBS_AREA01_NORMAL_STAGE07",
"SBS_AREA01_BOSS_STAGE01"]
SHOP_ITEMS = [
"SBS_BOOST_CHAR_COUNT",
"SBS_BOOST_SCORE_VALUE",
"SBS_BOOST_COIN_ELIXIR_PERCENT",
"SBS_BOOST_LUCKY_BOMB_PERCENT",
"SBS_BOOST_ELEMENT_WEAKNESS_TARGET_BONUS",
"SBS_BOOST_NOTHING_FAVORITE_COUNT_REWARD",
"SBS_BOOST_EGG_COUNT"
]
MAP_REWARDS = [
{"areaId":"ABS_AREA01_00","rewardPackId":"GRP_AREA01_REWARD_000","eventAreaId":"EBS_BOX_AREA01_00_REWARD001"}
]
# Task Weightage
WEIGHTAGE_GACHA = 2
WEIGHTAGE_UNLOCK = 2
WEIGHTAGE_START = 3
WEIGHTAGE_REWARD = 1
WEIGHTAGE_INBOX = 1
WEIGHTAGE_PURCHASE = 1 | {
"repo_name": "liaogz82/locust-fabric-deployment",
"path": "settings.py",
"copies": "2",
"size": "1516",
"license": "mit",
"hash": -6524322928298273000,
"line_mean": 24.7118644068,
"line_max": 109,
"alpha_frac": 0.731530343,
"autogenerated": false,
"ratio": 2.2359882005899707,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.39675185435899707,
"avg_score": null,
"num_lines": null
} |
"""API endpoints"""
import os
import json
import requests
import jwt
from datetime import datetime, timedelta
from urlparse import parse_qsl
from flask import Flask, request, jsonify, make_response, render_template
from checkit.backend import users, todo_lists, setup_stores
app = Flask(__name__, static_url_path='/static')
class InvalidAPIUsage(Exception):
"""Handle invalid API calls"""
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidAPIUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def landing_page():
return app.send_static_file('index.html')
@app.route('/v1/users', methods=['GET', 'POST'])
def get_users():
""" Get a list of users or create a new user"""
if request.method == 'GET':
us = users.get_users()
return jsonify({"users": [user.to_dict() for user in us]})
else:
user_data = request.json
try:
user = users.create_user(user_data)
except:
raise InvalidAPIUsage('Wrong or incomplete user data', status_code=400)
return make_response(jsonify(user.to_dict()), 201)
@app.route('/v1/users/<user_id>')
def get_user(user_id):
"""Get a specific user"""
user = users.get_user(user_id)
if user is not None:
return jsonify({'user': user.to_dict()})
else:
return jsonify({})
@app.route('/v1/users/<user_id>/lists', methods=['GET', 'POST'])
def get_user_todo_lists(user_id):
"""Get all user's lists or create a new Todo list"""
if request.method == 'GET':
td_lists = todo_lists.get_todo_lists(user_id)
return jsonify({'lists': [l.to_dict() for l in td_lists]})
else:
list_data = request.json
try:
todo_list = todo_lists.create_todo_list(list_data, user_id)
except:
raise InvalidAPIUsage("Wrong or incomplete todo_list data")
return make_response(jsonify(todo_list.to_dict()), 201)
@app.route('/v1/users/<user_id>/lists/<list_id>', methods=['GET', 'DELETE'])
def get_user_todo_list(user_id, list_id):
"""Get a user's concrete TODO list"""
if request.method == 'GET':
td_list = todo_lists.get_user_todo_list(list_id)
if td_list is not None:
return jsonify({'list': td_list.to_dict()})
else:
return jsonify({})
else:
removed = todo_lists.delete_todo_list(list_id)
if removed:
return make_response(jsonify({}), 200)
else:
return make_response(jsonify({'message': 'Could not remove the list'}), 400)
@app.route('/v1/users/<user_id>/lists/<list_id>/items', methods=['GET', 'POST'])
def get_list_items(user_id, list_id):
"""Get items of a TODO list"""
if request.method == 'GET':
items = todo_lists.get_list_items(list_id)
return jsonify({"items": [item.to_dict() for item in items]})
else:
item_data = request.json
try:
item = todo_lists.create_item(list_id, item_data)
except:
raise InvalidAPIUsage("Wrong or incomplete item data")
return make_response(jsonify(item.to_dict()), 201)
@app.route('/v1/users/<user_id>/lists/<list_id>/items/<item_id>')
def get_item(user_id, list_id, item_id):
"""Get a TODO list's concrete item"""
item_list = todo_lists.get_item(item_id)
if item_list is not None:
return jsonify({'item': item_list.to_dict()})
else:
return jsonify({})
@app.route('/v1/users/<user_id>/lists/<list_id>/items/<item_id>', methods=['PUT'])
def update_item(user_id, list_id, item_id):
"""Modify an existing item"""
item_data = request.json
mod_item = todo_lists.update_item(item_data)
if mod_item is not None:
return jsonify(mod_item.to_dict())
else:
return jsonify({})
@app.route('/v1/1000fc1e-56dc-4a7d-add0-a83d1120c5d7')
def _reset_db():
"""_secret_ endpoint to cleanup and setup the database"""
DB_URI = os.environ.get('DB_URI')
setup_stores(DB_URI)
users.reset()
users.bootstrap()
todo_lists.reset()
todo_lists.bootstrap()
return app.send_static_file('index.html')
#################
# Authorization #
#################
def create_token(user):
payload = {
'sub': user.id,
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(days=14)
}
token = jwt.encode(payload, app.config['GITHUB_SECRET'])
return token.decode('unicode_escape')
def parse_token(req):
token = req.headers.get('Authorization').split()[1]
return jwt.decode(token, app.config['GITHUB_SECRET'])
@app.route('/auth/github', methods=['POST'])
def github():
access_token_url = 'https://github.com/login/oauth/access_token'
users_api_url = 'https://api.github.com/user'
params = {
'client_id': request.json['clientId'],
'redirect_uri': request.json['redirectUri'],
'client_secret': app.config['GITHUB_SECRET'],
'code': request.json['code']
}
# Step 1. Exchange authorization code for access token.
r = requests.get(access_token_url, params=params)
access_token = dict(parse_qsl(r.text))
headers = {'User-Agent': 'Satellizer'}
# Step 2. Retrieve information about the current user.
r = requests.get(users_api_url, params=access_token, headers=headers)
profile = json.loads(r.text)
# Step 3. Create a new account or return an existing one.
user = users.get_user(profile['id'])
if user:
token = create_token(user)
return jsonify(token=token, user_id=user.id)
else:
user = users.create_user({'id': profile['id'], 'name': profile['name']})
token = create_token(user)
return jsonify(token=token, user_id=user.id)
| {
"repo_name": "guillermo-carrasco/checkit",
"path": "checkit/server/api.py",
"copies": "1",
"size": "6173",
"license": "mit",
"hash": 6593753135540023000,
"line_mean": 29.865,
"line_max": 88,
"alpha_frac": 0.6167179653,
"autogenerated": false,
"ratio": 3.4621424565339316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4578860421833931,
"avg_score": null,
"num_lines": null
} |
""" API endpoints related to home operations. """
import logging
from pyramid.security import NO_PERMISSION_REQUIRED
from pyramid.view import view_config
LOG = logging.getLogger(__name__)
@view_config(route_name='unlock', request_method='POST', permission='unlock')
def unlock(request):
""" Unlock the gate for a brief period """
request.call_worker('door', 'on_off', relay='outside_latch', duration=3)
return request.response
@view_config(route_name='doorbell', request_method='POST', permission='troll')
def ring_doorbell(request):
""" Ring the doorbell """
request.call_worker('door', 'on_off', relay='doorbell', duration=0.2)
return request.response
@view_config(route_name='on_sms', request_method='GET', renderer='string',
permission=NO_PERMISSION_REQUIRED)
def received_sms(request):
""" Open the door if the SMS is from an approved number """
if not request.validate_twilio():
return request.error('auth', "Failed HMAC")
from_number = request.param('From')
if from_number not in request.registry.phone_access and \
not request.cal.is_guest(from_number):
LOG.warning("%r attempted unauthorized entry", from_number)
return ("I'm sorry, you are not authorized to enter this dwelling. "
"Please contact the residents.")
request.call_worker('door', 'on_off', relay='outside_latch', duration=3)
return request.response
| {
"repo_name": "stevearc/stiny",
"path": "stiny/home.py",
"copies": "1",
"size": "1442",
"license": "mit",
"hash": -5255315134429649000,
"line_mean": 37.972972973,
"line_max": 78,
"alpha_frac": 0.6865464632,
"autogenerated": false,
"ratio": 3.765013054830287,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49515595180302874,
"avg_score": null,
"num_lines": null
} |
"""Api endpoints to interactions for the Image ndb model
"""
# local imports
from app.base.handlers import AdminAjaxHandler
from app.handlers.apis.mixins import ListCreateMixin
from app.handlers.apis.mixins import OrderMixin
from app.handlers.apis.mixins import RetrieveUpdateDeleteMixin
from app.forms.events import EventForm
from app.models.events import Event
class AdminList(ListCreateMixin, OrderMixin, AdminAjaxHandler):
form = EventForm
model = Event
sort_order = 'order'
def _populate_form(self, data, record=None):
if data.get('start'):
data['start'] = data['start'][4:15]
if data.get('end'):
data['end'] = data['end'][4:15]
return super(AdminList, self)._populate_form(data, record)
class AdminDetail(RetrieveUpdateDeleteMixin, AdminAjaxHandler):
form = EventForm
model = Event
def _populate_form(self, data, record=None):
if data.get('start'):
data['start'] = data['start'][4:15]
if data.get('end'):
data['end'] = data['end'][4:15]
return super(AdminDetail, self)._populate_form(data, record)
| {
"repo_name": "mjmcconnell/sra",
"path": "src-server/app/handlers/apis/events.py",
"copies": "1",
"size": "1139",
"license": "apache-2.0",
"hash": 4081892569596422000,
"line_mean": 28.2051282051,
"line_max": 68,
"alpha_frac": 0.6707638279,
"autogenerated": false,
"ratio": 3.784053156146179,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4954816984046179,
"avg_score": null,
"num_lines": null
} |
"""Api endpoints to interactions for the Image ndb model
"""
# third-party imports
from google.appengine.api import mail
# local imports
from app import config
from app.base.handlers import BaseAjaxHandler
from app.base.handlers import AdminAjaxHandler
from app.handlers.apis.mixins import ListCreateMixin
from app.handlers.apis.mixins import OrderMixin
from app.handlers.apis.mixins import RetrieveUpdateDeleteMixin
from app.forms.workshops import WorkshopForm
from app.forms.workshops import WorkshopContactForm
from app.models.workshops import Workshop
class AdminList(ListCreateMixin, OrderMixin, AdminAjaxHandler):
form = WorkshopForm
model = Workshop
sort_order = 'order'
def _populate_form(self, data, record=None):
if data.get('start'):
data['start'] = data['start'][4:15]
if data.get('end'):
data['end'] = data['end'][4:15]
return super(AdminList, self)._populate_form(data, record)
class AdminDetail(RetrieveUpdateDeleteMixin, AdminAjaxHandler):
form = WorkshopForm
model = Workshop
def _populate_form(self, data, record=None):
if data.get('start'):
data['start'] = data['start'][4:15]
if data.get('end'):
data['end'] = data['end'][4:15]
return super(AdminDetail, self)._populate_form(data, record)
class ContactHandler(BaseAjaxHandler):
"""Handles the form submission from the frontend contact page.
"""
def post(self):
"""Validate the form data, if successful send of the email
returning a successful json response with the submitted data.
Else return a failed json response with the form errors.
"""
code = 200
return_data = {}
form = WorkshopContactForm(self.request.POST)
if form.validate():
# Render the user generated content using jinja2,
# to enable auto-escaping
template_data = {
'title': 'Someone has made an enquiry about the workshops.',
'form': form
}
mail.send_mail(
sender='workshops@{}.appspotmail.com'.format(config.APP_ID),
to=config.EMAIL_TO,
subject='Workshops enquiry',
body=self.render_to_string('emails/form.txt', template_data),
html=self.render_to_string('emails/form.html', template_data)
)
return_data['status'] = 'success'
else:
code = 400
return_data['status'] = 'fail'
return_data['data'] = form.errors
self.response.set_status(code)
return self.render_json(return_data)
| {
"repo_name": "mjmcconnell/sra",
"path": "src-server/app/handlers/apis/workshops.py",
"copies": "1",
"size": "2687",
"license": "apache-2.0",
"hash": 7155740049462739000,
"line_mean": 31.3734939759,
"line_max": 77,
"alpha_frac": 0.6319315221,
"autogenerated": false,
"ratio": 4.0589123867069485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5190843908806949,
"avg_score": null,
"num_lines": null
} |
"""Api endpoints to interactions for the Page ndb model
"""
# local imports
from app.base.handlers import AdminAjaxHandler
from app.handlers.apis.mixins import ListMixin
from app.handlers.apis.mixins import OrderMixin
from app.handlers.apis.mixins import RetrieveMixin
from app.handlers.apis.mixins import UpdateMixin
from app.handlers.templates.admin.pages import get_form
from app.forms.pages.base import PageForm
from app.models.pages import MetaData
class AdminList(ListMixin, OrderMixin, AdminAjaxHandler):
form = PageForm
model = MetaData
sort_order = 'order'
class AdminDetail(RetrieveMixin, UpdateMixin, AdminAjaxHandler):
form = PageForm
model = MetaData
def post(self, _id):
"""Update an existing datastore record.
"""
record = self._get_record()
if record is None:
self.response.set_status(400)
return self.render_json({'message': 'Record not found'})
self.form = get_form(record.page.kind())
form = self._populate_form(self.request.POST, record)
if form.validate():
form = self._upload_images(form, record)
record.update(form)
return self.render_json({'data': record.to_dict()})
self.response.set_status(400)
return self.render_json({
'message': 'Failed to update item',
'data': form.errors
})
| {
"repo_name": "mjmcconnell/sra",
"path": "src-server/app/handlers/apis/pages.py",
"copies": "1",
"size": "1406",
"license": "apache-2.0",
"hash": 1629649959023111200,
"line_mean": 28.2916666667,
"line_max": 68,
"alpha_frac": 0.667140825,
"autogenerated": false,
"ratio": 4.051873198847262,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5219014023847262,
"avg_score": null,
"num_lines": null
} |
#api en python y kivy
#api example
#josue de leon
from kivy.app import App #importing the app class so as
#to run the damn application
from kivy.uix.boxlayout import BoxLayout #importing BoxLayout widget since i don't
#want to create a dynamic class
from kivy.properties import ObjectProperty,ListProperty,NumericProperty,StringProperty #importing kivy properties
from kivy.network.urlrequest import UrlRequest
import json
from kivy.uix.listview import ListItemButton
class WeatherApp(App):
pass
class WeatherRoot(BoxLayout):
'''this is the root widget which must have various configuration methods
to decide how the screen looks.Other classes declared below will be children
of the root class WeatherRoot in the kivy language file '''
current_weather=ObjectProperty()
def show_current_weather(self,location):
self.clear_widgets()
if location is None and self.current_weather is None:
location=("New York","US")
if location is not None:
self.current_weather=CurrentLocation()
self.current_weather.location=location
self.current_weather.update_weather()
self.add_widget(self.current_weather)
def addlocation(self):
self.clear_widgets()
self.add_widget(AddLocationForm())
def args_converter(self,index,data_item):
city,country=data_item
return {'location':(city,country)}
class AddLocationForm(BoxLayout):
'''this class inherits from the BoxLayout widget of the kivy language
and contains the logic related to the location form,however the design part
lies with kivy file.The basic mockup in the mind is that of textinput,two buttons,
and a listview widget containing all the places the man has already searched for'''
search_input=ObjectProperty()
search_results=ObjectProperty()
def search_location(self):
print(self.search_input.text)
search_template="http://api.openweathermap.org/data/2.5/" + "find?q={}&type=like"
search_url=search_template.format(self.search_input.text)
print("finding location......")
request=UrlRequest(search_url,self.found_location)
def found_location(self,request,data):
'''To notice in this method is the ListView can use different classes
as the widget to be displayed .Two classes ListItemLabel and ListItemButton
that behave normally only that they are containing info for tracking selection
.Thus,its often a good idea to extend these classes
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
Above is an example of the json code and so is to be taken care of.
json is lightweight data interchange format.It is self-describing
.It is a syntax for storing and exchanging data.Its an alternative of
XML.Again,XML is a markup language made only to describe data.HTML to
display data.
'''
data=json.loads(data.decode()) if not isinstance(data,dict) else data
cities = [(d['name'], d['sys']['country']) for d in data['list']]
self.search_results.item_strings=cities
self.search_results.adapter.data.clear()
self.search_results.adapter.data.extend(cities)
self.search_results._trigger_reset_populate()
print("function found_location searched")
#this above line is just for the update the display when data changes
class LocationButton(ListItemButton):
location=ListProperty()
class CoverPage(BoxLayout):
pass
class CurrentLocation(BoxLayout):
location=ListProperty()
conditions=StringProperty()
temp=NumericProperty()
wind=NumericProperty()
temp_max=NumericProperty()
def update_weather(self):
print("I am working")
weather_template="http://api.openweathermap.org/data/2.5/"+"weather?q={}&units=metric"
weather_url=weather_template.format(self.location[0])
print("Dude i submitted the request")
request2=UrlRequest(weather_url,on_success=self.weather_founded,on_failure=self.weather_failure,on_redirect=self.weather_redirect)
print("I think i am going good")
def weather_founded(self,request2,data2):
print("Man i am working too")
data2=json.loads(data2.decode()) if not isinstance(data2,dict) else data2
self.conditions=data2['weather'][0]['description']
self.temp=data2['main']['temp']
print(self.temp)
print(self.conditions)
self.wind=data2['wind']['speed']
self.temp_max=data2['main']['temp_max']
def weather_failure(self,request2,data2):
print("suyash i think its failing")
def weather_redirect(self,request2,data2):
print("Damn you")
if __name__=='__main__':
WeatherApp().run()
#Refactoring the code means to change the code which makes no development.
#however helps the code to get more usable and more api compatible.
#Thus refactoring the code is a very important part.
2
| {
"repo_name": "JOSUEXLION/prog3-uip",
"path": "investigaciones/API.py",
"copies": "1",
"size": "4685",
"license": "mit",
"hash": 2177486657253594400,
"line_mean": 40.4601769912,
"line_max": 132,
"alpha_frac": 0.7545357524,
"autogenerated": false,
"ratio": 3.460118168389956,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9471061206172949,
"avg_score": 0.04871854292340129,
"num_lines": 113
} |
"""API example script: Create an order from a given form.
NOTE: You need to change several variables to make this work. See below.
NOTE: This uses the third-party 'requests' module, which is better than
the standard 'urllib' module.
"""
import simplejson as json # XXX Python 3 kludge
# Third-party package: http://docs.python-requests.org/en/master/
import requests
# Variables whose values must be changed for your site:
BASE_URL = 'http://localhost:8886' # Base URL for your OrderPortal instance.
API_KEY = '7f075a4c5b324e3ca63f22d8dc0929c4' # API key for the user account.
FORM_IUID = 'dadd37b9e2644caa80eb358773cec00b' # The IUID of the form.
url = "{base}/api/v1/order".format(base=BASE_URL)
headers = {'X-OrderPortal-API-key': API_KEY}
data = {'title': 'The title for a new order created by API call',
'form': FORM_IUID}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200, (response.status_code, response.reason)
print(json.dumps(response.json(), indent=2))
| {
"repo_name": "pekrau/OrderPortal",
"path": "orderportal/scripts/api_create_order.py",
"copies": "1",
"size": "1034",
"license": "mit",
"hash": 7967340446153292000,
"line_mean": 34.6551724138,
"line_max": 77,
"alpha_frac": 0.7330754352,
"autogenerated": false,
"ratio": 3.152439024390244,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9385514459590244,
"avg_score": 0,
"num_lines": 29
} |
"""API example script: Edit an order; fields, title, tags and history.
NOTE: You need to change several variables to make this work. See below.
NOTE: This uses the third-party 'requests' module, which is better than
the standard 'urllib' module.
"""
import simplejson as json # XXX Python 3 kludge
# Third-party package: http://docs.python-requests.org/en/master/
import requests
# Variables whose values must be changed for your site:
BASE_URL = 'http://localhost:8886' # Base URL for your OrderPortal instance.
API_KEY = '7f075a4c5b324e3ca63f22d8dc0929c4' # API key for the user account.
ORDER_ID = 'NMI00603' # The ID or IUID for the order.
url = "{base}/api/v1/order/{id}".format(base=BASE_URL,
id=ORDER_ID)
headers = {'X-OrderPortal-API-key': API_KEY}
data = {'title': 'New title',
'tags': ['first_tag', 'second_tag'], # NOTE: identifier format!
'links': {'external': [{'href': 'http://scilifelab.se',
'title': 'SciLifeLab'},
{'href': 'http://dummy.com'}]},
'fields': {'Expected_results': 'Fantastic!',
'Node_support': 'KTH'},
'history': {'accepted': '2018-11-01'}} # Only admin can edit history.
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200, (response.status_code, response.reason)
print(json.dumps(response.json(), indent=2))
| {
"repo_name": "pekrau/OrderPortal",
"path": "orderportal/scripts/api_edit_order.py",
"copies": "1",
"size": "1455",
"license": "mit",
"hash": -3369908776884650000,
"line_mean": 39.4166666667,
"line_max": 77,
"alpha_frac": 0.6281786942,
"autogenerated": false,
"ratio": 3.4642857142857144,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4592464408485714,
"avg_score": null,
"num_lines": null
} |
"""API example script: Submit the order.
NOTE: You need to change several variables to make this work. See below.
NOTE: This uses the third-party 'requests' module, which is better than
the standard 'urllib' module.
"""
import sys
import simplejson as json # XXX Python 3 kludge
# Third-party package: http://docs.python-requests.org/en/master/
import requests
# Variables whose values must be changed for your site:
BASE_URL = 'http://localhost:8886' # Base URL for your OrderPortal instance.
API_KEY = '7f075a4c5b324e3ca63f22d8dc0929c4' # API key for the user account.
ORDER_ID = 'NMI00603' # The ID for the order. The IUID can also be used.
url = "{base}/api/v1/order/{id}".format(base=BASE_URL,
id=ORDER_ID)
headers = {'X-OrderPortal-API-key': API_KEY}
# First just get the order data as JSON. It contains all allowed transitions.
response = requests.get(url, headers=headers)
assert response.status_code == 200, (response.status_code, response.reason)
# Get the URL for the transition to status 'submitted'.
data = response.json()
try:
url = data['links']['submitted']['href']
except KeyError:
print('Error: No href for submit; the order status does not allow it.')
sys.exit()
# Actually do the transition by the POST method.
response = requests.post(url, headers=headers)
assert response.status_code == 200, (response.status_code, response.reason)
data = response.json()
if data['status'] == 'submitted':
print('Order submitted.')
else:
print('Error: Order was not submitted.')
| {
"repo_name": "pekrau/OrderPortal",
"path": "orderportal/scripts/api_submit_order.py",
"copies": "1",
"size": "1565",
"license": "mit",
"hash": 6138662363612158000,
"line_mean": 33.0217391304,
"line_max": 77,
"alpha_frac": 0.7067092652,
"autogenerated": false,
"ratio": 3.508968609865471,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4715677875065471,
"avg_score": null,
"num_lines": null
} |
"""API example script: Uploading the order report.
NOTE: The upload operation URL requires the IUID for the order;
the order identifier (NMI00603 in this case) won't work for this call.
NOTE: You need to change several variables to make this work. See below.
NOTE: This uses the third-party 'requests' module, which is better than
the standard 'urllib' module.
"""
import sys
# Third-party package: http://docs.python-requests.org/en/master/
import requests
# Variables whose values must be changed for your site:
BASE_URL = 'http://localhost:8886' # Base URL for your OrderPortal instance.
API_KEY = '7f075a4c5b324e3ca63f22d8dc0929c4' # API key for the user account.
ORDER_IUID = 'b1abccfbc77048e1941034d7c0101f22' # The IUID for the order!
url = "{base}/api/v1/order/{iuid}/report".format(base=BASE_URL,
iuid=ORDER_IUID)
headers = {'X-OrderPortal-API-key': API_KEY,
'content-type': 'text/plain'}
data = 'Some text in a report.\nAnd a second line.'
# NOTE: The method PUT is used to upload a report to the order.
response = requests.put(url, headers=headers, data=data)
assert response.status_code == 200, (response.status_code, response.reason)
print('report uploaded')
| {
"repo_name": "pekrau/OrderPortal",
"path": "orderportal/scripts/api_upload_report.py",
"copies": "1",
"size": "1252",
"license": "mit",
"hash": -4215652917473734700,
"line_mean": 35.8235294118,
"line_max": 77,
"alpha_frac": 0.7092651757,
"autogenerated": false,
"ratio": 3.3386666666666667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45479318423666665,
"avg_score": null,
"num_lines": null
} |
"""Api extension initialization"""
import warnings
from webargs.flaskparser import abort # noqa
from .spec import APISpecMixin
from .blueprint import Blueprint # noqa
from .pagination import Page # noqa
from .error_handler import ErrorHandlerMixin
__version__ = '0.17.1'
warnings.warn(
"flask-rest-api has been renamed to flask-smorest.",
DeprecationWarning,
)
class Api(APISpecMixin, ErrorHandlerMixin):
"""Main class
Provides helpers to build a REST API using Flask.
:param Flask app: Flask application
:param dict spec_kwargs: kwargs to pass to internal APISpec instance
The ``spec_kwargs`` dictionary is passed as kwargs to the internal APISpec
instance. **flask-rest-api** adds a few parameters to the original
parameters documented in :class:`apispec.APISpec <apispec.APISpec>`:
:param apispec.BasePlugin flask_plugin: Flask plugin
:param apispec.BasePlugin marshmallow_plugin: Marshmallow plugin
:param list|tuple extra_plugins: List of additional ``BasePlugin``
instances
:param str openapi_version: OpenAPI version. Can also be passed as
application parameter `OPENAPI_VERSION`.
This allows the user to override default Flask and marshmallow plugins.
`title` and `version` APISpec parameters can't be passed here, they are set
according to the app configuration.
For more flexibility, additional spec kwargs can also be passed as app
parameter `API_SPEC_OPTIONS`.
"""
def __init__(self, app=None, *, spec_kwargs=None):
self._app = app
self.spec = None
# Use lists to enforce order
self._fields = []
self._converters = []
if app is not None:
self.init_app(app, spec_kwargs=spec_kwargs)
def init_app(self, app, *, spec_kwargs=None):
"""Initialize Api with application"""
self._app = app
# Register flask-rest-api in app extensions
app.extensions = getattr(app, 'extensions', {})
ext = app.extensions.setdefault('flask-rest-api', {})
ext['ext_obj'] = self
# Initialize spec
self._init_spec(**(spec_kwargs or {}))
# Initialize blueprint serving spec
self._register_doc_blueprint()
# Register error handlers
self._register_error_handlers()
def register_blueprint(self, blp, **options):
"""Register a blueprint in the application
Also registers documentation for the blueprint/resource
:param Blueprint blp: Blueprint to register
:param dict options: Keyword arguments overriding Blueprint defaults
Must be called after app is initialized.
"""
self._app.register_blueprint(blp, **options)
# Register views in API documentation for this resource
blp.register_views_in_doc(self._app, self.spec)
# Add tag relative to this resource to the global tag list
self.spec.tag({'name': blp.name, 'description': blp.description})
| {
"repo_name": "Nobatek/flask-rest-api",
"path": "flask_rest_api/__init__.py",
"copies": "1",
"size": "3000",
"license": "mit",
"hash": -3024706197750398500,
"line_mean": 31.2580645161,
"line_max": 79,
"alpha_frac": 0.6746666667,
"autogenerated": false,
"ratio": 4.225352112676056,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5400018779376056,
"avg_score": null,
"num_lines": null
} |
"""API field validators."""
import re
from django.core.exceptions import ValidationError
from django.db.models import Model
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django.utils.six import string_types
from rest_framework.exceptions import ValidationError as DRFValidationError
@deconstructible
class LanguageDictValidator(object):
"""Check for valid language dictionary."""
def __init__(self, allow_canonical=False):
self.allow_canonical = allow_canonical
def __call__(self, value):
if value is None:
return
if not isinstance(value, dict):
raise ValidationError(
_('Value must be a JSON dictionary of language codes to'
' strings.'))
if 'zxx' in value:
if self.allow_canonical and list(value.keys()) != ['zxx']:
raise ValidationError(
_("Language code 'zxx' not allowed with other values."))
elif not self.allow_canonical:
raise ValidationError(_("Language code 'zxx' not allowed"))
elif 'en' not in value:
raise ValidationError(_("Missing required language code 'en'."))
for language_code, text in value.items():
if not isinstance(text, string_types):
raise ValidationError(
_('For language "%(lang)s, text "%(text)s" is not a'
' string.'),
params={'lang': language_code, 'text': text})
def __eq__(self, other):
"""Check equivalency to another LanguageDictValidator.
Required for migration detection.
"""
if isinstance(other, self.__class__):
return self.allow_canonical == other.allow_canonical
else:
return False
def __ne__(self, other):
"""Check non-equivalency to another LanguageDictValidator."""
return not self.__eq__(other)
class VersionAndStatusValidator(object):
"""For Version resource, restrict version/status combinations."""
# From http://stackoverflow.com/questions/82064
re_numeric = re.compile(r"^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$")
def __init__(self):
"""Initialize for Django model validation."""
self.instance = None
self.Error = ValidationError
def set_context(self, serializer_field):
"""
Switch to Django Rest Framework (DRF) Serializer validation.
DRF 3.1.3 treats Django's ValidationError as non-field errors, ignoring
the message dictionary calling out the particular fields. When
DRF calls set_context(), switch to the DRF ValidationError class, so
that errors will be targetted to the field that needs to be changed.
"""
self.instance = serializer_field.instance
self.Error = DRFValidationError
def __call__(self, value):
"""Validate version/status combinations."""
if isinstance(value, Model):
# Called from Django model validation, value is Version instance
version = value.version
status = value.status
else:
# Called from DRF serializer validation, value is dict
if self.instance:
# Called from update
version = value.get('version', self.instance.version)
status = value.get('status', self.instance.status)
else:
# Called from create
version = value['version']
status = value.get('status', 'unknown')
if not version:
# DRF will catch in field validation
raise self.Error({'version': ['This field may not be blank.']})
is_numeric = bool(self.re_numeric.match(version))
numeric_only = ['beta', 'retired beta', 'retired', 'unknown']
if status in numeric_only and not is_numeric:
msg = 'With status "{0}", version must be numeric.'.format(status)
raise self.Error({'version': [msg]})
if status == 'future' and is_numeric:
msg = ('With status "future", version must be non-numeric.'
' Use status "beta" for future numbered versions.')
raise self.Error({'version': [msg]})
if status == 'current' and not (is_numeric or version == 'current'):
msg = ('With status "current", version must be numeric or'
' "current".')
raise self.Error({'version': [msg]})
if version == 'current' and status != 'current':
msg = 'With version "current", status must be "current".'
raise self.Error({'status': [msg]})
| {
"repo_name": "mdn/browsercompat",
"path": "webplatformcompat/validators.py",
"copies": "2",
"size": "4727",
"license": "mpl-2.0",
"hash": 9029685751938997000,
"line_mean": 39.0593220339,
"line_max": 79,
"alpha_frac": 0.5936111699,
"autogenerated": false,
"ratio": 4.70816733067729,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6301778500577291,
"avg_score": null,
"num_lines": null
} |
"""Api file for the pet example API.
"""
pet = {
'category': {
'id': 42,
'name': 'string'
},
'status': 'string',
'name': 'doggie',
'tags': [
{
'id': 42,
'name': 'string'
}
],
'photoUrls': [
'string',
'string2'
],
'id': 42
}
order = {
'status': 'string',
'shipDate': '2015-08-28T09:02:57.481Z',
'complete': True,
'petId': 42,
'id': 42,
'quantity': 42
}
user = {
'username': 'string',
'firstName': 'string',
'lastName': 'string',
'userStatus': 42,
'email': 'string',
'phone': 'string',
'password': 'string',
'id': 42
}
def addPet():
return (pet, 201)
def updatePet():
return (pet, 200)
def findPetsByStatus():
return ([pet], 200)
def findPetsByTags():
return ([pet], 200)
def getPetById(petId=None):
return (pet, 200)
def updatePetWithForm(petId=None):
return (pet, 201)
def deletePet(petId=None):
return ('', 204)
def placeOrder():
return (order, 200)
def getOrderById(orderId=None):
return (order, 200)
def deleteOrder(orderId=None):
return ('', 204)
def createUser():
return ('', 201)
def createUsersWithArrayInput():
return ('', 201)
def createUsersWithListInput():
return ('', 201)
def loginUser():
return ('', 200)
def logoutUser():
return ('', 200)
def getUserByName(username=None):
return (user, 200)
def updateUser(username=None):
return (pet, 200)
def updateUserEmail(username):
return ('+1-202-555-0153', 200)
def deleteUser(username=None):
return ('', 204)
def testHeaderPath():
return ('', 200)
| {
"repo_name": "Trax-air/swagger-tester",
"path": "tests/api.py",
"copies": "1",
"size": "1693",
"license": "mit",
"hash": -7580248740013144000,
"line_mean": 12.8770491803,
"line_max": 43,
"alpha_frac": 0.5469580626,
"autogenerated": false,
"ratio": 3.146840148698885,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4193798211298885,
"avg_score": null,
"num_lines": null
} |
"""API filters for the Contribution App."""
from django.utils import dateparse, timezone
from rest_framework import filters
from bulbs.content.filters import Published
class ESPublishedFilterBackend(filters.BaseFilterBackend):
"""
Used for elasticsearch publish queries in reporting.
Rounds values to their given date & final second.
"""
def filter_queryset(self, request, queryset, view):
"""Apply the relevant behaviors to the view queryset."""
start_value = self.get_start(request)
if start_value:
queryset = self.apply_published_filter(queryset, "after", start_value)
end_value = self.get_end(request)
if end_value:
# Forces the end_value to be the last second of the date provided in the query.
# Necessary currently as our Published filter for es only applies to gte & lte.
queryset = self.apply_published_filter(queryset, "before", end_value)
return queryset
def apply_published_filter(self, queryset, operation, value):
"""
Add the appropriate Published filter to a given elasticsearch query.
:param queryset: The DJES queryset object to be filtered.
:param operation: The type of filter (before/after).
:param value: The date or datetime value being applied to the filter.
"""
if operation not in ["after", "before"]:
raise ValueError("""Publish filters only use before or after for range filters.""")
return queryset.filter(Published(**{operation: value}))
def get_start(self, request):
start_value = self.get_date_datetime_param(request, "start")
if start_value:
return timezone.make_aware(start_value).astimezone(timezone.pytz.utc)
def get_end(self, request):
end_value = self.get_date_datetime_param(request, "end")
if end_value:
end_value += timezone.timedelta(days=1)
end_value -= timezone.timedelta(seconds=1)
return timezone.make_aware(end_value).astimezone(timezone.pytz.utc)
def get_date_datetime_param(self, request, param):
"""Check the request for the provided query parameter and returns a rounded value.
:param request: WSGI request object to retrieve query parameter data.
:param param: the name of the query parameter.
"""
if param in request.GET:
param_value = request.GET.get(param, None)
# Match and interpret param if formatted as a date.
date_match = dateparse.date_re.match(param_value)
if date_match:
return timezone.datetime.combine(
dateparse.parse_date(date_match.group(0)), timezone.datetime.min.time()
)
datetime_match = dateparse.datetime_re.match(param_value)
if datetime_match:
return timezone.datetime.combine(
dateparse.parse_datetime(datetime_match.group(0)).date(),
timezone.datetime.min.time()
)
return None
class StartEndFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
start = request.QUERY_PARAMS.get("start", None)
if start:
start_date = dateparse.parse_date(start)
queryset = self.filter_start(queryset, view, start_date)
end = request.QUERY_PARAMS.get("end", None)
if end:
end_date = dateparse.parse_date(end)
queryset = self.filter_end(queryset, view, end_date)
return queryset
def filter_start(self, queryset, view, start_date):
start_fields = getattr(view, "start_fields", None)
if start_fields:
_filters = {}
for field_name in start_fields:
_filters = {"{}__gte".format(field_name): start_date}
return queryset.filter(**_filters)
def filter_end(self, queryset, view, end_date):
end_fields = getattr(view, "end_fields", None)
if end_fields:
_filters = {}
for field_name in end_fields:
_filters = {"{}__lte".format(field_name): end_date}
return queryset.filter(**_filters)
| {
"repo_name": "theonion/django-bulbs",
"path": "bulbs/contributions/filters.py",
"copies": "1",
"size": "4249",
"license": "mit",
"hash": -8529987678297016000,
"line_mean": 40.6568627451,
"line_max": 95,
"alpha_frac": 0.625558955,
"autogenerated": false,
"ratio": 4.266064257028113,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008867922547193621,
"num_lines": 102
} |
# API for accessing the core plugin of SublimePapyrus
import sublime, sublime_plugin, sys, os, json, threading, time
PYTHON_VERSION = sys.version_info
SUBLIME_VERSION = None
if PYTHON_VERSION[0] == 2:
SUBLIME_VERSION = int(sublime.version())
import imp
root, module = os.path.split(os.getcwd())
coreModule = "SublimePapyrus"
# SublimePapyrus core module
mainPackage = os.path.join(root, coreModule, "Plugin.py")
imp.load_source("SublimePapyrus", mainPackage)
del mainPackage
import SublimePapyrus
# Skyrim linter module
linterPackage = os.path.join(root, module, "Linter.py")
imp.load_source("Linter", linterPackage)
del linterPackage
import Linter
# Cleaning up
del root
del module
del coreModule
elif PYTHON_VERSION[0] >= 3:
from SublimePapyrus import Plugin as SublimePapyrus
from . import Linter
VALID_SCOPE = "source.papyrus.skyrim"
def plugin_loaded():
global SUBLIME_VERSION
SUBLIME_VERSION = int(sublime.version())
# Completion generation
class SublimePapyrusSkyrimGenerateCompletionsCommand(sublime_plugin.WindowCommand):
def run(self):
view = self.window.active_view()
if view:
self.paths = SublimePapyrus.GetSourcePaths(view)
if self.paths:
if PYTHON_VERSION[0] == 2:
self.window.show_quick_panel(self.paths, self.on_select, 0, -1)
elif PYTHON_VERSION[0] >= 3:
self.window.show_quick_panel(self.paths, self.on_select, 0, -1, None)
def on_select(self, index):
if index >= 0:
self.path = self.paths[index]
thread = threading.Thread(target=self.generate_completions)
thread.start()
def generate_completions(self):
outputFolder = os.path.join(sublime.packages_path(), "User")
lex = Linter.Lexical()
syn = Linter.Syntactic()
sem = Linter.Semantic()
files = [f for f in os.listdir(self.path) if ".psc" in f]
if len(files) > 100:
if not sublime.ok_cancel_dialog("You are about to generate static completions for %d scripts.\n\nAre you sure you want to continue?" % len(files)):
return
for file in files:
path = os.path.join(self.path, file)
scriptName = file[:-4]
scriptContents = ""
try:
with open(path) as fi:
scriptContents = fi.read()
except UnicodeDecodeError:
with open(path, encoding="utf8") as fi:
scriptContents = fi.read()
if scriptContents:
lines = []
tokens = []
try:
for token in lex.Process(scriptContents):
if token.type == lex.NEWLINE:
if tokens:
lines.append(tokens)
tokens = []
elif token.type != lex.COMMENT_LINE and token.type != lex.COMMENT_BLOCK:
tokens.append(token)
except Linter.LexicalError as e:
if PYTHON_VERSION[0] == 2:
print("SublimePapyrus - Lexical error on line %d, column %d in '%s': %s" % (e.line, e.column, path, e.message))
elif PYTHON_VERSION[0] >= 3:
SublimePapyrus.ShowMessage("Error on line %d, column %d in '%s': %s" % (e.line, e.column, path, e.message))
return
if lines:
statements = []
for line in lines:
try:
stat = syn.Process(line)
if stat and (stat.type == sem.STAT_FUNCTIONDEF or stat.type == sem.STAT_EVENTDEF):
statements.append(stat)
except Linter.SyntacticError as e:
if PYTHON_VERSION[0] == 2:
print("SublimePapyrus - Syntactic error on line %d in '%s': %s" % (e.line, path, e.message))
elif PYTHON_VERSION[0] >= 3:
SublimePapyrus.ShowMessage("Error on line %d in '%s': %s" % (e.line, path, e.message))
return
scriptNameLower = scriptName.lower()
completions = [{"trigger": "%s\t%s" % (scriptNameLower, "script"), "contents": scriptName}]
for stat in statements:
if stat.type == sem.STAT_FUNCTIONDEF:
temp = SublimePapyrus.MakeFunctionCompletion(stat, sem, script=scriptNameLower)
completions.append({"trigger": temp[0], "contents": temp[1]})
elif stat.type == sem.STAT_EVENTDEF:
temp = SublimePapyrus.MakeEventCompletion(stat, sem, calling=False, script=scriptNameLower)
completions.append({"trigger": temp[0], "contents": temp[1]})
output = {
"scope": VALID_SCOPE,
"completions": completions
}
with open(os.path.join(outputFolder, "SublimePapyrus - Skyrim - %s.sublime-completions" % scriptName), "w") as fo:
json.dump(output, fo, indent=2)
print("SublimePapyrus - Finished generating completions for scripts in '%s'" % self.path)
linterCache = {}
completionCache = {}
cacheLock = threading.RLock()
lex = Linter.Lexical()
syn = Linter.Syntactic()
sem = Linter.Semantic()
class EventListener(sublime_plugin.EventListener):
def __init__(self):
super(EventListener,self).__init__()
self.linterQueue = 0
self.linterRunning = False
self.linterErrors = {}
self.completionRunning = False
self.validScope = "source.papyrus.skyrim"
self.completionKeywordAs = ("as\tcast", "As ",)
self.completionKeywordAuto = ("auto\tkeyword", "Auto",)
self.completionKeywordAutoReadOnly = ("autoreadonly\tkeyword", "AutoReadOnly",)
self.completionKeywordConditional = ("conditional\tkeyword", "Conditional",)
self.completionKeywordExtends = ("extends\tkeyword", "Extends ",)
self.completionKeywordGlobal = ("global\tkeyword", "Global",)
self.completionKeywordHidden = ("hidden\tkeyword", "Hidden",)
self.completionKeywordNative = ("native\tkeyword", "Native",)
self.completionKeywordParent = ("parent\tkeyword", "Parent",)
self.completionKeywordSelf = ("self\tkeyword", "Self",)
self.completionKeywordFalse = ("false\tkeyword", "False",)
self.completionKeywordNone = ("none\tkeyword", "None",)
self.completionKeywordTrue = ("true\tkeyword", "True",)
self.scriptContents = None
# Clear cache in order to force an update
def on_close(self, view):
if self.IsValidScope(view):
bufferID = view.buffer_id()
if bufferID:
if self.linterErrors.get(bufferID, None):
del self.linterErrors[bufferID]
self.ClearLinterCache(bufferID)
# Linter
def on_post_save(self, view):
if self.IsValidScope(view):
settings = SublimePapyrus.GetSettings()
if settings and settings.get("linter_on_save", True):
filePath = view.file_name()
if filePath:
folderPath, fileName = os.path.split(filePath)
scriptName = fileName[:fileName.rfind(".")].upper()
if self.linterRunning:
return
self.ClearSemanticAnalysisCache(scriptName)
self.ClearCompletionCache(scriptName)
self.bufferID = view.buffer_id()
if self.bufferID:
self.linterQueue += 1
lineNumber, columnNumber = view.rowcol(view.sel()[0].begin())
lineNumber += 1
self.Linter(view, lineNumber)
def on_modified(self, view):
if self.IsValidScope(view):
settings = SublimePapyrus.GetSettings()
global SUBLIME_VERSION
tooltipParameters = settings.get("tooltip_function_parameters", True)
tooltipDocstring = settings.get("tooltip_function_docstring", True)
if SUBLIME_VERSION >= 3070 and (tooltipParameters or tooltipDocstring):
if self.linterRunning:
return
elif self.completionRunning:
return
global cacheLock
global lex
global syn
global sem
with cacheLock:
locations = [view.sel()[0].begin()]
prefix = view.word(locations[0])
line, column = view.rowcol(locations[0])
line += 1
lineString = view.substr(sublime.Region(view.line(locations[0]).begin(), locations[0]-len(prefix))).strip()
bufferID = view.buffer_id()
if bufferID:
currentScript = self.GetScript(bufferID)
if currentScript:
try:
sem.GetContext(currentScript, line)
except Linter.FunctionDefinitionCancel as e:
tokens = []
try:
for token in lex.Process(lineString):
if token.type != lex.NEWLINE:
tokens.append(token)
if tokens and tokens[-1].type != lex.COMMENT_LINE:
try:
syn.Process(tokens)
except Linter.ExpectedIdentifierError as f:
if tokens[-1].type != lex.OP_DOT:
stack = syn.stack[:]
arguments = []
for item in reversed(stack):
if item.type == sem.NODE_FUNCTIONCALLARGUMENT:
arguments.insert(0, stack.pop())
elif item.type == sem.LEFT_PARENTHESIS:
break
stackLength = len(stack)
func = None
if stackLength >= 2 and stack[-2].type == sem.IDENTIFIER:
name = stack[-2].value.upper()
if stackLength >= 4 and stack[-3].type == sem.OP_DOT:
try:
result = sem.NodeVisitor(stack[-4])
if result.type != sem.KW_SELF:
try:
script = sem.GetCachedScript(result.type)
if script:
func = script.functions.get(name, None)
except Linter.SemanticError as e:
return
else:
for scope in reversed(e.functions):
func = scope.get(name, None)
if func:
break
except Linter.SemanticError as e:
return
else:
for scope in reversed(e.functions):
func = scope.get(name, None)
if func:
break
for imp in e.imports:
script = sem.GetCachedScript(imp)
temp = script.functions.get(name, None)
if temp:
if func:
func = None
else:
func = temp
break
if func:# and func.data.parameters:
self.ShowFunctionInfo(view, tokens, func, len(arguments), tooltipParameters, tooltipDocstring)
except Linter.SyntacticError as f:
pass
except Linter.LexicalError as f:
pass
except Linter.SemanticError as e:
pass
if settings and settings.get("linter_on_modified", True):
self.QueueLinter(view)
def ShowFunctionInfo(self, aView, aTokens, aFunction, aArgumentCount, aParameters, aDocstring):
funcName = aFunction.data.identifier
currentParameter = None
if len(aTokens) > 2 and aTokens[-1].type == lex.OP_ASSIGN and aTokens[-2].type == lex.IDENTIFIER:
currentParameter = aTokens[-2].value.upper()
paramIndex = 0
funcParameters = []
if aParameters:
for param in aFunction.data.parameters:
paramName = param.identifier
paramType = param.typeIdentifier
if param.array:
paramType = "%s[]" % paramType
paramContent = None
if param.expression:
paramDefaultValue = sem.GetLiteral(param.expression, True)
paramContent = "%s %s = %s" % (paramType, paramName, paramDefaultValue)
else:
paramContent = "%s %s" % (paramType, paramName)
if currentParameter:
if currentParameter == paramName.upper():
paramContent = "<b>%s</b>" % paramContent
else:
if paramIndex == aArgumentCount:
paramContent = "<b>%s</b>" % paramContent
paramIndex += 1
funcParameters.append(paramContent)
docstring = ""
if aDocstring:
if aFunction.data.docstring:
if funcParameters:
docstring = "<br><br>%s" % "<br>".join(aFunction.data.docstring.data.value.split("\n"))
else:
docstring = "<br>".join(aFunction.data.docstring.data.value.split("\n"))
settings = SublimePapyrus.GetSettings()
backgroundColor = settings.get("tooltip_background_color", "#393939")
bodyTextColor = settings.get("tooltip_body_text_color", "#747369")
bodyFontSize = settings.get("tooltip_font_size", "12")
boldTextColor = settings.get("tooltip_bold_text_color", "#ffffff")
headingTextColor = settings.get("tooltip_heading_text_color", "#bfbfbf")
headingFontSize = settings.get("tooltip_heading_font_size", "14")
css = """<style>
html {
background-color: %s;
}
body {
font-size: %spx;
color: %s;
}
b {
color: %s;
}
h1 {
color: %s;
font-size: %spx;
}
</style>""" % (backgroundColor, bodyFontSize, bodyTextColor, boldTextColor, headingTextColor, headingFontSize)
content = "%s<h1>%s</h1>%s%s" % (css, funcName, "<br>".join(funcParameters), docstring)
if aView.is_popup_visible():
aView.update_popup(content)
else:
aView.show_popup(content, flags=sublime.COOPERATE_WITH_AUTO_COMPLETE, max_width=int(settings.get("tooltip_max_width", 600)), max_height=int(settings.get("tooltip_max_height", 300)))
def QueueLinter(self, view):
if self.linterRunning: # If an instance of the linter is running, then cancel
return
self.linterQueue += 1 # Add to queue
settings = SublimePapyrus.GetSettings()
delay = 0.500
if settings:
delay = settings.get("linter_delay", 500)/1000.0
if delay < 0.050:
delay = 0.050
self.bufferID = view.buffer_id()
if self.bufferID:
lineNumber, columnNumber = view.rowcol(view.sel()[0].begin())
lineNumber += 1
if PYTHON_VERSION[0] == 2:
self.scriptContents = view.substr(sublime.Region(0, view.size()))
self.sourcePaths = SublimePapyrus.GetSourcePaths(view)
SublimePapyrus.ClearLinterHighlights(view)
t = threading.Timer(delay, self.Linter, kwargs={"view": None, "lineNumber": lineNumber})
t.daemon = True
t.start()
elif PYTHON_VERSION[0] >= 3:
t = threading.Timer(delay, self.Linter, kwargs={"view": view, "lineNumber": lineNumber})
t.daemon = True
t.start()
def Linter(self, view, lineNumber):
self.linterQueue -= 1 # Remove from queue
if self.linterQueue > 0: # If there is a queue, then cancel
return
elif self.completionRunning: # If completions are being generated, then cancel
return
self.linterRunning = True # Block further attempts to run the linter until this instance has finished
if view:
SublimePapyrus.ClearLinterHighlights(view)
#start = None #DEBUG
def Exit():
#print("Linter: Finished in %f milliseconds and releasing lock..." % ((time.time()-start)*1000.0)) #DEBUG
self.linterRunning = False
return False
global cacheLock
global lex
global syn
global sem
global SUBLIME_VERSION
with cacheLock:
if not self.linterErrors.get(self.bufferID, None):
self.linterErrors[self.bufferID] = {}
#start = time.time() #DEBUG
settings = None
if view:
settings = SublimePapyrus.GetSettings()
if SUBLIME_VERSION >= 3103 and view.is_auto_complete_visible(): # If a list of completions is visible, then cancel
return Exit()
if view:
SublimePapyrus.SetStatus(view, "sublimepapyrus-linter", "The linter is running...")
#lexSynStart = time.time() #DEBUG
scriptContents = None
if view:
scriptContents = view.substr(sublime.Region(0, view.size()))
else:
scriptContents = self.scriptContents
if not scriptContents:
return Exit()
lineCount = scriptContents.count("\n") + 1
statements = []
lines = []
tokens = []
currentLine = None
try:
for token in lex.Process(scriptContents):
if token.type == lex.NEWLINE:
if tokens:
if currentLine:
stat = syn.Process(tokens)
if stat:
statements.append(stat)
elif token.line >= lineNumber:
currentLine = syn.Process(tokens)
if currentLine:
while lines:
stat = syn.Process(lines.pop(0))
if stat:
statements.append(stat)
statements.append(currentLine)
currentLine = True
else:
lines.append(tokens)
tokens = []
else:
if token.line >= lineNumber:
while lines:
stat = syn.Process(lines.pop(0))
if stat:
statements.append(stat)
currentLine = True
elif token.type != lex.COMMENT_LINE and token.type != lex.COMMENT_BLOCK:
tokens.append(token)
except Linter.LexicalError as e:
if view:
error = self.linterErrors[self.bufferID].get(e.message, None)
if error and error.message == e.message and abs(error.line - e.line) < settings.get("linter_error_line_threshold", 2) + 1:
SublimePapyrus.HighlightLinter(view, e.line, e.column, False)
else:
SublimePapyrus.HighlightLinter(view, e.line, e.column)
self.linterErrors[self.bufferID][e.message] = e
SublimePapyrus.SetStatus(view, "sublimepapyrus-linter", "Error on line %d, column %d: %s" % (e.line, e.column, e.message))
if settings.get("linter_panel_error_messages", False):
view.window().show_quick_panel([[e.message, "Line %d, column %d" % (e.line, e.column)]], None)
return Exit()
except Linter.SyntacticError as e:
if view:
error = self.linterErrors[self.bufferID].get(e.message, None)
if error and error.message == e.message and abs(error.line - e.line) < settings.get("linter_error_line_threshold", 2) + 1:
SublimePapyrus.HighlightLinter(view, e.line, center=False)
else:
SublimePapyrus.HighlightLinter(view, e.line)
self.linterErrors[self.bufferID][e.message] = e
SublimePapyrus.SetStatus(view, "sublimepapyrus-linter", "Error on line %d: %s" % (e.line, e.message))
if settings.get("linter_panel_error_messages", False):
view.window().show_quick_panel([[e.message, "Line %d" % e.line]], None)
return Exit()
#print("Linter: Finished lexical and syntactic in %f milliseconds..." % ((time.time()-lexSynStart)*1000.0)) #DEBUG
#semStart = time.time() #DEBUG
if statements:
try:
script = None
if view:
script = sem.Process(statements, SublimePapyrus.GetSourcePaths(view))
else:
script = sem.Process(statements, self.sourcePaths)
if script:
self.SetScript(self.bufferID, script)
except Linter.SemanticError as e:
if view:
error = self.linterErrors[self.bufferID].get(e.message, None)
if error and error.message == e.message and abs(error.line - e.line) < settings.get("linter_error_line_threshold", 2) + 1:
SublimePapyrus.HighlightLinter(view, e.line, center=False)
else:
SublimePapyrus.HighlightLinter(view, e.line)
self.linterErrors[self.bufferID][e.message] = e
SublimePapyrus.SetStatus(view, "sublimepapyrus-linter", "Error on line %d: %s" % (e.line, e.message))
if settings.get("linter_panel_error_messages", False):
window = view.window()
if window: # Has to be checked in ST2 due to only active views returning values other than None.
window.show_quick_panel([[e.message, "Line %d" % e.line]], None)
return Exit()
#print("Linter: Finished semantic in %f milliseconds..." % ((time.time()-semStart)*1000.0)) #DEBUG
if view:
SublimePapyrus.ClearStatus(view, "sublimepapyrus-linter")
if self.linterErrors.get(self.bufferID, None):
del self.linterErrors[self.bufferID]
return Exit()
# Completions
def on_query_completions(self, view, prefix, locations):
if self.IsValidScope(view):
settings = SublimePapyrus.GetSettings()
if settings and settings.get("intelligent_code_completion", True):
if self.completionRunning:
return
elif self.linterRunning:
return
self.completionRunning = True
#start = time.time() #DEBUG
completions = None
if not view.find("scriptname", 0, sublime.IGNORECASE):
path = view.file_name()
if path:
_, name = os.path.split(path)
completions = [("scriptname\tscript header", "ScriptName %s" % name[:name.rfind(".")],)]
else:
completions = [("scriptname\tscript header", "ScriptName ",)]
else:
completions = self.Completions(view, prefix, locations)
if completions:
completions = list(set(completions))
elif completions == None:
completions = []
completions = (completions, sublime.INHIBIT_WORD_COMPLETIONS|sublime.INHIBIT_EXPLICIT_COMPLETIONS,)
#print("Completions: Finished in %f milliseconds and releasing lock..." % ((time.time()-start)*1000.0)) #DEBUG
self.completionRunning = False
return completions
def Completions(self, view, prefix, locations):
SublimePapyrus.ClearLinterHighlights(view)
completions = []
flags = None
global cacheLock
global lex
global syn
global sem
with cacheLock:
bufferID = view.buffer_id()
if not bufferID:
return
currentScript = self.GetScript(bufferID)
if not currentScript:
SublimePapyrus.ShowMessage("Run the linter once...")
return
line, column = view.rowcol(locations[0])
line += 1
lineString = view.substr(sublime.Region(view.line(locations[0]).begin(), locations[0]-len(prefix))).strip()
settings = SublimePapyrus.GetSettings()
settingFunctionEventParameters = settings.get("intelligent_code_completion_function_event_parameters", True)
try:
sem.GetContext(currentScript, line)
except Linter.EmptyStateCancel as e:
if not lineString:
# Inherited functions/events
for name, obj in e.functions[0].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, False, "parent"))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, False, "parent"))
completions.append(("import\timport statement", "Import ${0:$SELECTION}",))
completions.append(("property\tproperty def.", "${1:Type} Property ${2:PropertyName} ${3:Auto}",))
completions.append(("endproperty\tkeyword", "EndProperty",))
completions.append(("fullproperty\tfull property def.", "${1:Type} Property ${2:PropertyName}\n\t${1:Type} Function Get()\n\t\t${3}\n\tEndFunction\n\n\tFunction Set(${1:Type} Variable)\n\t\t${4}\n\tEndFunction\nEndProperty",))
completions.append(("autostate\tauto state def.", "Auto State ${1:StateName}\n\t${0}\nEndState",))
completions.append(("state\tstate def.", "State ${1:StateName}\n\t${0}\nEndState",))
completions.append(("endstate\tkeyword", "EndState",))
completions.append(("event\tevent def.", "Event ${1:EventName}(${2:Parameters})\n\t${0}\nEndEvent",))
completions.append(("endevent\tkeyword", "EndEvent",))
completions.append(("function\tfunction def.", "${1:Type} Function ${2:FunctionName}(${3:Parameters})\n\t${0}\nEndFunction",))
completions.append(("endfunction\tkeyword", "EndFunction",))
# Types to facilitate variable declarations
completions.extend(self.GetTypeCompletions(view, True))
return completions
else:
tokens = []
try:
for token in lex.Process(lineString):
if token.type != lex.NEWLINE:
tokens.append(token)
except Linter.LexicalError as f:
return
if tokens:
if tokens[-1].type != lex.COMMENT_LINE:
try:
stat = syn.Process(tokens)
# Optional flags
if stat.type == syn.STAT_SCRIPTHEADER:
if not stat.data.parent:
completions.append(self.completionKeywordExtends)
if not lex.KW_CONDITIONAL in stat.data.flags:
completions.append(self.completionKeywordConditional)
if not lex.KW_HIDDEN in stat.data.flags:
completions.append(self.completionKeywordHidden)
elif stat.type == syn.STAT_PROPERTYDEF:
if not lex.KW_AUTO in stat.data.flags and not syn.KW_AUTOREADONLY in stat.data.flags:
completions.append(self.completionKeywordAuto)
if not lex.KW_AUTOREADONLY in stat.data.flags and not syn.KW_AUTO in stat.data.flags:
completions.append(self.completionKeywordAutoReadOnly)
if not lex.KW_CONDITIONAL in stat.data.flags:
completions.append(self.completionKeywordConditional)
if not lex.KW_HIDDEN in stat.data.flags:
completions.append(self.completionKeywordHidden)
elif stat.type == syn.STAT_VARIABLEDEF:
if not lex.KW_CONDITIONAL in stat.data.flags:
completions.append(self.completionKeywordConditional)
elif stat.type == syn.STAT_FUNCTIONDEF:
if not lex.KW_NATIVE in stat.data.flags:
completions.append(self.completionKeywordNative)
if not lex.KW_GLOBAL in stat.data.flags:
completions.append(self.completionKeywordGlobal)
elif stat.type == syn.STAT_EVENTDEF:
if not lex.KW_NATIVE in stat.data.flags:
completions.append(self.completionKeywordNative)
return completions
except Linter.ExpectedTypeError as f:
completions.extend(self.GetTypeCompletions(view, f.baseTypes))
return completions
except Linter.ExpectedKeywordError as f:
# Mandatory property flags when initializing a property with a literal
if syn.KW_AUTO in f.keywords:
completions.append(("auto\tkeyword", "Auto",))
if syn.KW_AUTOREADONLY in f.keywords:
completions.append(("autoreadonly\tkeyword", "AutoReadOnly",))
return completions
except Linter.ExpectedLiteralError as f:
# Literals when initializing a property
if tokens[1].type == lex.KW_PROPERTY:
if tokens[0].type == lex.IDENTIFIER:
completions.append(self.completionKeywordNone)
elif tokens[0].type == lex.KW_BOOL:
completions.append(self.completionKeywordTrue)
completions.append(self.completionKeywordFalse)
elif tokens[0].type == lex.KW_STRING:
completions.append(("stringliteral\tstring literal", "\"${0}\""))
return completions
elif tokens[1].type == lex.LEFT_BRACKET and tokens[2].type == lex.RIGHT_BRACKET and tokens[3].type == lex.KW_PROPERTY:
completions.append(self.completionKeywordNone)
return completions
except Linter.SyntacticError as f:
return
return
except Linter.StateCancel as e:
# Functions/events that have not yet been defined in the state.
if not lineString:
# Functions/events defined in the empty state.
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_EVENTDEF and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, False, "self"))
elif stat.type == syn.STAT_FUNCTIONDEF and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "self"))
# Inherited functions/events.
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_EVENTDEF and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, False, "parent"))
elif stat.type == syn.STAT_FUNCTIONDEF and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "parent"))
return completions
else:
tokens = []
try:
for token in lex.Process(lineString):
if token.type != lex.NEWLINE:
tokens.append(token)
except Linter.LexicalError as f:
return
if tokens:
if tokens[-1].type != lex.COMMENT_LINE:
tokenCount = len(tokens)
# Functions without return types and events
if tokenCount == 1:
if tokens[0].type == lex.KW_FUNCTION:
# Functions/events defined in the empty state.
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_FUNCTIONDEF and not stat.data.type and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "self", True))
# Inherited functions/events.
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_FUNCTIONDEF and not stat.data.type and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "parent", True))
return completions
elif tokens[0].type == lex.KW_EVENT:
# Functions/events defined in the empty state.
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_EVENTDEF and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, False, "self", True))
# Inherited functions/events.
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_EVENTDEF and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, False, "parent", True))
return completions
# Functions with non-array return types
elif tokenCount == 2 and tokens[1].type == lex.KW_FUNCTION:
if tokens[0].type == lex.IDENTIFIER or tokens[0].type == lex.KW_BOOL or tokens[0].type == lex.KW_FLOAT or tokens[0].type == lex.KW_INT or tokens[0].type == lex.KW_STRING:
# Functions/events defined in the empty state.
funcType = tokens[0].value.upper()
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_FUNCTIONDEF and not stat.data.array and stat.data.type == funcType and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "self", True))
# Inherited functions/events.
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_FUNCTIONDEF and not stat.data.array and stat.data.type == funcType and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "parent", True))
return completions
# Functions with array return types
elif tokenCount == 4 and tokens[3].type == lex.KW_FUNCTION and tokens[1].type == lex.LEFT_BRACKET and tokens[2].type == lex.RIGHT_BRACKET:
if tokens[0].type == lex.IDENTIFIER or tokens[0].type == lex.KW_BOOL or tokens[0].type == lex.KW_FLOAT or tokens[0].type == lex.KW_INT or tokens[0].type == lex.KW_STRING:
# Functions/events defined in the empty state.
funcType = tokens[0].value.upper()
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_FUNCTIONDEF and stat.data.array and stat.data.type == funcType and not e.functions[2].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "self", True))
# Inherited functions/events.
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_FUNCTIONDEF and stat.data.array and stat.data.type == funcType and not e.functions[2].get(name, False) and not e.functions[1].get(name, False):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, False, "parent", True))
return completions
return
except Linter.FunctionDefinitionCancel as e:
if not lineString:
# Flow control
completions.append(("if\tif", "If ${1:$SELECTION}\n\t${0}\nEndIf",))
completions.append(("elseif\telse-if", "ElseIf ${1:$SELECTION}\n\t${0}",))
completions.append(("else\telse", "Else\n\t${0}",))
completions.append(("endif\tkeyword", "EndIf",))
completions.append(("while\twhile-loop", "While ${1:$SELECTION}\n\t${0}\nEndWhile",))
completions.append(("endwhile\tkeyword", "EndWhile",))
completions.append(("for\tpseudo for-loop", "Int ${1:iCount} = 0\nWhile ${1:iCount} < ${2:maxSize}\n\t${0}\n\t${1:iCount} += 1\nEndWhile",))
if e.signature.data.type:
completions.append(("return\tstat.", "Return ",))
else:
completions.append(("return\tstat.", "Return",))
# Special variables
if not sem.KW_GLOBAL in e.signature.data.flags:
completions.append(self.completionKeywordSelf)
completions.append(self.completionKeywordParent)
# Inherited properties
for name, stat in e.variables[0].items():
if stat.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(stat, "parent"))
# Properties and variables declared in the empty state
for name, stat in e.variables[1].items():
if stat.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(stat))
elif stat.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(stat, "self"))
# Function/event parameters and variables declared in the function
for name, stat in e.variables[2].items():
if stat.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(stat))
elif stat.type == syn.STAT_PARAMETER:
completions.append(SublimePapyrus.MakeParameterCompletion(stat))
# Variables declared in if, elseif, else, and while scopes
if len(e.variables) > 3:
for scope in e.variables[3:]:
for name, stat in scope.items():
if stat.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(stat))
if len(e.functions) > 2:
#Functions/events defined in the non-empty state
for name, stat in e.functions[2].items():
if stat.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
elif stat.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
# Functions/events defined in the empty state
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_FUNCTIONDEF and not e.functions[2].get(name, None):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
elif stat.type == syn.STAT_EVENTDEF and not e.functions[2].get(name, None):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
# Inherited functions/events
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_FUNCTIONDEF and not e.functions[1].get(name, None) and not e.functions[2].get(name, None):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, True, "parent", parameters=settingFunctionEventParameters))
elif stat.type == syn.STAT_EVENTDEF and not e.functions[1].get(name, None) and not e.functions[2].get(name, None):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, True, "parent", parameters=settingFunctionEventParameters))
else:
# Functions/events defined in the empty state
for name, stat in e.functions[1].items():
if stat.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
elif stat.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, True, "self", parameters=settingFunctionEventParameters))
# Inherited functions/events
for name, stat in e.functions[0].items():
if stat.type == syn.STAT_FUNCTIONDEF and not e.functions[1].get(name, None):
completions.append(SublimePapyrus.MakeFunctionCompletion(stat, sem, True, "parent", parameters=settingFunctionEventParameters))
elif stat.type == syn.STAT_EVENTDEF and not e.functions[1].get(name, None):
completions.append(SublimePapyrus.MakeEventCompletion(stat, sem, True, "parent", parameters=settingFunctionEventParameters))
# Imported global functions
for imp in e.imports:
functions = self.GetFunctionCompletions(imp, True)
if not functions:
try:
script = sem.GetCachedScript(imp)
if script:
functions = []
impLower = imp.lower()
for name, obj in script.functions.items():
if lex.KW_GLOBAL in obj.data.flags:
functions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, impLower, parameters=settingFunctionEventParameters))
self.SetFunctionCompletions(imp, functions, True)
except:
return
if functions:
completions.extend(functions)
# Types to facilitate variable declarations
completions.extend(self.GetTypeCompletions(view, True))
return completions
else:
tokens = []
try:
for token in lex.Process(lineString):
if token.type != lex.NEWLINE:
tokens.append(token)
except Linter.LexicalError as f:
return
if tokens:
if tokens[-1].type != lex.COMMENT_LINE:
try:
stat = syn.Process(tokens)
if stat.type == syn.STAT_VARIABLEDEF:
completions.append(self.completionKeywordAs)
return completions
elif stat.type == syn.STAT_ASSIGNMENT:
completions.append(self.completionKeywordAs)
return completions
elif stat.type == syn.STAT_EXPRESSION:
completions.append(self.completionKeywordAs)
return completions
elif stat.type == syn.STAT_RETURN:
if e.signature.data.type:
for name, obj in e.functions[0].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
for name, obj in e.functions[1].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
for name, obj in e.variables[0].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "parent"))
for name, obj in e.variables[1].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "self"))
elif obj.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(obj))
for scope in e.variables[2:]:
for name, obj in scope.items():
if obj.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(obj))
elif obj.type == syn.STAT_PARAMETER:
completions.append(SublimePapyrus.MakeParameterCompletion(obj))
completions.extend(self.GetTypeCompletions(view, False))
completions.append(self.completionKeywordFalse)
completions.append(self.completionKeywordTrue)
completions.append(self.completionKeywordNone)
if not sem.KW_GLOBAL in e.signature.data.flags:
completions.append(self.completionKeywordSelf)
completions.append(self.completionKeywordParent)
# Imported global functions
for imp in e.imports:
functions = self.GetFunctionCompletions(imp, True)
if not functions:
try:
script = sem.GetCachedScript(imp)
if script:
functions = []
impLower = imp.lower()
for name, obj in script.functions.items():
if lex.KW_GLOBAL in obj.data.flags:
functions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, impLower, parameters=settingFunctionEventParameters))
self.SetFunctionCompletions(imp, functions, True)
except:
return
if functions:
completions.extend(functions)
return completions
except Linter.ExpectedTypeError as f:
completions.extend(self.GetTypeCompletions(view, f.baseTypes))
return completions
except Linter.ExpectedIdentifierError as f:
if tokens[-1].type == lex.OP_DOT: # Accessing properties and functions
try:
result = sem.NodeVisitor(syn.stack[-2])
#print(result.type)
#print(result.array)
#print(result.object)
if result.type == lex.KW_SELF:
for name, obj in e.functions[0].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
for name, obj in e.functions[1].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
for name, obj in e.variables[0].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "parent"))
for name, obj in e.variables[1].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "self"))
return completions
elif result.array:
typ = result.type.capitalize()
elementIdentifier = "akElement"
if typ == "Bool":
elementIdentifier = "abElement"
elif typ == "Float":
elementIdentifier = "afElement"
elif typ == "Int":
elementIdentifier = "aiElement"
elif typ == "String":
elementIdentifier = "asElement"
completions.append(("find\tint func.", "Find(${1:%s %s}, ${2:Int aiStartIndex = 0})" % (typ, elementIdentifier),))
completions.append(("rfind\tint func.", "RFind(${1:%s %s}, ${2:Int aiStartIndex = -1})" % (typ, elementIdentifier),))
completions.append(("length\tkeyword", "Length",))
return completions
else:
# None and types that do not have properties nor functions/events
if result.type == lex.KW_NONE or result.type == lex.KW_BOOL or result.type == lex.KW_FLOAT or result.type == lex.KW_INT or result.type == lex.KW_STRING:
return
if not result.object: #Global <TYPE> functions
functions = self.GetFunctionCompletions(result.type, True)
if not functions:
try:
script = sem.GetCachedScript(result.type)
if script:
functions = []
typeLower = result.type.lower()
for name, obj in script.functions.items():
if lex.KW_GLOBAL in obj.data.flags:
functions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, typeLower, parameters=settingFunctionEventParameters))
self.SetFunctionCompletions(result.type, functions, True)
except:
return
if functions:
completions.extend(functions)
return completions
else: # Non-global functions, events, and properties
functions = self.GetFunctionCompletions(result.type, False)
if not functions:
try:
script = sem.GetCachedScript(result.type)
if script:
functions = []
typeLower = result.type.lower()
for name, obj in script.functions.items():
if lex.KW_GLOBAL not in obj.data.flags:
functions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, typeLower, parameters=settingFunctionEventParameters))
self.SetFunctionCompletions(result.type, functions, False)
except:
return
if functions:
completions.extend(functions)
properties = self.GetPropertyCompletions(result.type)
if not properties:
try:
script = sem.GetCachedScript(result.type)
if script:
properties = []
typeLower = result.type.lower()
for name, obj in script.properties.items():
properties.append(SublimePapyrus.MakePropertyCompletion(obj, typeLower))
self.SetPropertyCompletions(result.type, properties)
except:
return
if properties:
completions.extend(properties)
return completions
return
except Linter.SemanticError as g:
return
return completions
else: # Not following a dot
for name, obj in e.functions[0].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "parent", parameters=settingFunctionEventParameters))
for name, obj in e.functions[1].items():
if obj.type == syn.STAT_FUNCTIONDEF:
completions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
elif obj.type == syn.STAT_EVENTDEF:
completions.append(SublimePapyrus.MakeEventCompletion(obj, sem, True, "self", parameters=settingFunctionEventParameters))
for name, obj in e.variables[0].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "parent"))
for name, obj in e.variables[1].items():
if obj.type == syn.STAT_PROPERTYDEF:
completions.append(SublimePapyrus.MakePropertyCompletion(obj, "self"))
elif obj.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(obj))
for scope in e.variables[2:]:
for name, obj in scope.items():
if obj.type == syn.STAT_VARIABLEDEF:
completions.append(SublimePapyrus.MakeVariableCompletion(obj))
elif obj.type == syn.STAT_PARAMETER:
completions.append(SublimePapyrus.MakeParameterCompletion(obj))
completions.extend(self.GetTypeCompletions(view, False))
completions.append(self.completionKeywordFalse)
completions.append(self.completionKeywordTrue)
completions.append(self.completionKeywordNone)
completions.append(self.completionKeywordAs)
if not sem.KW_GLOBAL in e.signature.data.flags:
completions.append(self.completionKeywordSelf)
completions.append(self.completionKeywordParent)
# Imported global functions
for imp in e.imports:
functions = self.GetFunctionCompletions(imp, True)
if not functions:
try:
script = sem.GetCachedScript(imp)
if script:
functions = []
impLower = imp.lower()
for name, obj in script.functions.items():
if lex.KW_GLOBAL in obj.data.flags:
functions.append(SublimePapyrus.MakeFunctionCompletion(obj, sem, True, impLower, parameters=settingFunctionEventParameters))
self.SetFunctionCompletions(imp, functions, True)
except:
return
if functions:
completions.extend(functions)
# Show info about function/event parameters
stack = syn.stack[:]
arguments = []
for item in reversed(stack):
if item.type == sem.NODE_FUNCTIONCALLARGUMENT:
arguments.insert(0, stack.pop())
elif item.type == sem.LEFT_PARENTHESIS:
break
stackLength = len(stack)
func = None
if stackLength >= 2 and stack[-2].type == sem.IDENTIFIER:
name = stack[-2].value.upper()
if stackLength >= 4 and stack[-3].type == sem.OP_DOT:
try:
result = sem.NodeVisitor(stack[-4])
if result.type != sem.KW_SELF:
try:
script = sem.GetCachedScript(result.type)
if script:
func = script.functions.get(name, None)
except Linter.SemanticError as e:
return
else:
for scope in reversed(e.functions):
func = scope.get(name, None)
if func:
break
except Linter.SemanticError as e:
return
else:
for scope in reversed(e.functions):
func = scope.get(name, None)
if func:
break
for imp in e.imports:
script = sem.GetCachedScript(imp)
temp = script.functions.get(name, None)
if temp:
if func:
func = None
else:
func = temp
break
if func and func.data.parameters:
for param in func.data.parameters:
completions.append(SublimePapyrus.MakeParameterCompletion(Linter.Statement(sem.STAT_PARAMETER, 0, param)))
global SUBLIME_VERSION
tooltipParameters = settings.get("tooltip_function_parameters", True)
tooltipDocstring = settings.get("tooltip_function_docstring", True)
if SUBLIME_VERSION >= 3070 and prefix == "" and (tooltipParameters or tooltipDocstring):
if not view.is_popup_visible():
self.ShowFunctionInfo(view, tokens, func, len(arguments), tooltipParameters, tooltipDocstring)
return completions
except Linter.SyntacticError as f:
if syn.stack and syn.stack[-2].type == syn.LEFT_PARENTHESIS and syn.stack[-1].type != syn.RIGHT_PARENTHESIS: # Expression enclosed by parentheses
completions.append(self.completionKeywordAs)
return completions
return
return
except Linter.PropertyDefinitionCancel as e:
if not lineString:
typ = None
if e.array:
typ = "%s[]" % e.type.capitalize()
else:
typ = "%s" % e.type.capitalize()
if not "GET" in e.functions:
completions.append(("get\t%s func." % typ, "%s Function Get()\n\t${0}\nEndFunction" % typ,))
if not "SET" in e.functions:
completions.append(("set\tfunc.", "Function Set(%s aParameter)\n\t${0}\nEndFunction" % typ,))
return completions
else:
tokens = []
try:
for token in lex.Process(lineString):
if token.type != lex.NEWLINE:
tokens.append(token)
except Linter.LexicalError as f:
return
if tokens:
if tokens[-1].type != lex.COMMENT_LINE:
pass
return
except Linter.SemanticError as e:
return
return
def IsValidScope(self, view):
if self.validScope:
return self.validScope in view.scope_name(0)
return False
def ClearCompletionCache(self, script):
global cacheLock
with cacheLock:
global completionCache
if completionCache.get("properties", None):
if completionCache["properties"].get(script, None):
del completionCache["properties"][script]
if completionCache.get("functions", None):
if completionCache["functions"].get(script, None):
del completionCache["functions"][script]
def ClearLinterCache(self, script):
global cacheLock
with cacheLock:
global linterCache
if linterCache.get(script, None):
del linterCache[script]
def ClearSemanticAnalysisCache(self, script):
global cacheLock
global sem
with cacheLock:
if sem:
if sem.cache.get(script, None):
del sem.cache[script]
children = []
for name, obj in sem.cache.items():
if script in obj.extends:
children.append(name)
for child in children:
del sem.cache[child]
def GetScript(self, bufferID):
global cacheLock
with cacheLock:
global linterCache
return linterCache.get(bufferID, None)
def SetScript(self, bufferID, script):
global cacheLock
with cacheLock:
global linterCache
linterCache[bufferID] = script
def GetFunctionCompletions(self, script, glob = False):
global cacheLock
with cacheLock:
global completionCache
functions = completionCache.get("functions", None)
if functions:
functions = functions.get(script, False)
if not functions:
return None
if glob:
return functions.get("global", None)
else:
return functions.get("nonglobal", None)
else:
return None
def SetFunctionCompletions(self, script, obj, glob = False):
global cacheLock
with cacheLock:
global completionCache
functions = completionCache.get("functions", None)
if not functions:
completionCache["functions"] = {}
functions = completionCache.get("functions", None)
if not functions.get(script, False):
functions[script] = {}
if glob:
functions[script]["global"] = obj
else:
functions[script]["nonglobal"] = obj
def GetPropertyCompletions(self, script):
global cacheLock
with cacheLock:
global completionCache
properties = completionCache.get("properties", None)
if properties:
return properties.get(script, None)
def SetPropertyCompletions(self, script, obj):
global cacheLock
with cacheLock:
global completionCache
properties = completionCache.get("properties", None)
if not properties:
completionCache["properties"] = {}
properties = completionCache.get("properties", None)
properties[script] = obj
def GetTypeCompletions(self, view, baseTypes = True):
global cacheLock
with cacheLock:
global completionCache
scripts = completionCache.get("types", None)
if not scripts:
scripts = []
paths = SublimePapyrus.GetSourcePaths(view)
for path in paths:
if os.path.isdir(path):
files = [f for f in os.listdir(path) if ".psc" in f]
for file in files:
scripts.append(("%s\tscript" % file[:-4].lower(), "%s" % file[:-4]))
scripts = list(set(scripts))
self.SetTypeCompletions(scripts)
if baseTypes:
scripts.extend([("bool\ttype", "Bool",), ("float\ttype", "Float",), ("int\ttype", "Int",), ("string\ttype", "String",)])
return scripts
def SetTypeCompletions(self, obj):
global cacheLock
with cacheLock:
global completionCache
completionCache["types"] = obj
class SublimePapyrusSkyrimClearCache(sublime_plugin.WindowCommand):
def run(self):
global cacheLock
global sem
global linterCache
global completionCache
with cacheLock:
linterCache = {}
completionCache = {}
sem.cache = {}
class SublimePapyrusSkyrimActorValueSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"Aggression": "Aggression",
"Alchemy": "Alchemy",
"Alteration modifier": "AlterationMod",
"Alteration power modifier": "AlterationPowerMod",
"Alteration": "Alteration",
"Armor perks": "ArmorPerks",
"Assistance": "Assistance",
"Attack damage multiplier": "AttackDamageMult",
"Block": "Block",
"Bow speed bonus": "BowSpeedBonus",
"Brain condition": "BrainCondition",
"Bypass vendor keyword check": "BypassVendorKeywordCheck",
"Bypass vendor stolen check": "BypassVendorStolenCheck",
"Carry weight": "CarryWeight",
"Combat health regeneration multiplier modifier": "CombatHealthRegenMultMod",
"Combat health regeneration multiplier power modifier": "CombatHealthRegenMultPowerMod",
"Confidence": "Confidence",
"Conjuration modifier": "ConjurationMod",
"Conjuration power modifier": "ConjurationPowerMod",
"Conjuration": "Conjuration",
"Critical chance": "CritChance",
"Damage resistance": "DamageResist",
"Destruction modifier": "DestructionMod",
"Destruction power modifier": "DestructionPowerMod",
"Destruction": "Destruction",
"Detect life range": "DetectLifeRange",
"Disease resistance": "DiseaseResist",
"Dragon souls": "DragonSouls",
"Enchanting": "Enchanting",
"Endurance condition": "EnduranceCondition",
"Energy": "Energy",
"Equipped item charge": "EquippedItemCharge",
"Equipped staff charge": "EquippedStaffCharge",
"Fame": "Fame",
"Favor active": "FavorActive",
"Favor points bonus": "FavorPointsBonus",
"Favors per day timer": "FavorsPerDayTimer",
"Favors per day": "FavorsPerDay",
"Fire resistance": "FireResist",
"Frost resistance": "FrostResist",
"Heal rate": "HealRate",
"Health": "Health",
"Heavy armor": "HeavyArmor",
"Ignore crippled limbs": "IgnoreCrippledLimbs",
"Illusion modifier": "IllusionMod",
"Illusion power modifier": "IllusionPowerMod",
"Illusion": "Illusion",
"Infamy": "Infamy",
"Inventory weight": "InventoryWeight",
"Invisibility": "Invisibility",
"Jumping bonus": "JumpingBonus",
"Last bribed or intimidated": "LastBribedIntimidated",
"Last flattered": "LastFlattered",
"Left attack condition": "LeftAttackCondition",
"Left mobility condition": "LeftMobilityCondition",
"Light armor": "LightArmor",
"Lockpicking": "Lockpicking",
"Magic resistance": "MagicResist",
"Magicka rate": "MagickaRate",
"Magicka": "Magicka",
"Marksman": "Marksman",
"Mass": "Mass",
"Melee damage": "MeleeDamage",
"Mood": "Mood",
"Morality": "Morality",
"Night eye": "NightEye",
"One-handed": "OneHanded",
"Paralysis": "Paralysis",
"Perception condition": "PerceptionCondition",
"Pickpocket": "Pickpocket",
"Poison resistance": "PoisonResist",
"Restoration modifier": "RestorationMod",
"Restoration power modifier": "RestorationPowerMod",
"Restoration": "Restoration",
"Right attack condition": "RightAttackCondition",
"Right mobility condition": "RightMobilityCondition",
"Shield perks": "ShieldPerks",
"Shock resistance": "ElectricResist",
"Shout recovery multiplier": "ShoutRecoveryMult",
"Smithing": "Smithing",
"Sneak": "Sneak",
"Speech": "Speechcraft",
"Speed multiplier": "SpeedMult",
"Stamina rate": "StaminaRate",
"Stamina": "Stamina",
"Two-handed": "TwoHanded",
"Unarmed damage": "UnarmedDamage",
"Variable 01": "Variable01",
"Variable 02": "Variable02",
"Variable 03": "Variable03",
"Variable 04": "Variable04",
"Variable 05": "Variable05",
"Variable 06": "Variable06",
"Variable 07": "Variable07",
"Variable 08": "Variable08",
"Variable 09": "Variable09",
"Variable 10": "Variable10",
"Voice points": "VoicePoints",
"Voice rate": "VoiceRate",
"Waiting for player": "WaitingForPlayer",
"Ward deflection": "WardDeflection",
"Ward power": "WardPower",
"Water breating": "WaterBreathing",
"Water walking": "WaterWalking",
"Weapon speed multiplier": "WeaponSpeedMult",
}
return items
class SublimePapyrusSkyrimFormTypeSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"(TLOD)": 74,
"(TOFT)": 86,
"Acoustic Space (ASPC)": 16,
"Action (AACT)": 6,
"Activator (ACTI)": 24,
"Actor (NPC_)": 43,
"ActorValueInfo (AVIF)": 95,
"Addon Node (ADDN)": 94,
"AI Package (PACK)": 79,
"Ammo (AMMO)": 42,
"Animated Object (ANIO)": 83,
"Apparatus (APPA)": 33,
"Armor (ARMO)": 26,
"Armor Addon (ARMA)": 102,
"Arrow Projectile (PARW)": 64,
"Art Object (ARTO)": 125,
"Association Type (ASTP)": 123,
"Barrier Projectile (PBAR)": 69,
"Beam Projectile (PBEA)": 66,
"Body Part Data (BPTD)": 93,
"Book (BOOK)": 27,
"Camera Path (CPTH)": 97,
"Camera Shot (CAMS)": 96,
"Cell (CELL)": 60,
"Character": 62,
"Class (CLAS)": 10,
"Climate (CLMT)": 55,
"Collision Layer (COLL)": 132,
"Color Form (CLFM)": 133,
"Combat Style (CSTY)": 80,
"Cone/Voice Projectile (PCON)": 68,
"Constructible Object (COBJ)": 49,
"Container (CONT)": 28,
"Debris (DEBR)": 88,
"Default Object Manager (DOBJ)": 107,
"Dialog View (DLVW)": 117,
"Dialogue Branch (DLBR)": 115,
"Door (DOOR)": 29,
"Dual Cast Data (DUAL)": 129,
"Effect Setting": 18,
"Effect Shader (EFSH)": 85,
"Enchantment (ENCH)": 21,
"Encounter Zone (ECZN)": 103,
"Equip Slot (EQUP)": 120,
"Explosion (EXPL)": 87,
"Eyes (EYES)": 13,
"Faction (FACT)": 11,
"Flame Projectile (PLFA)": 67,
"Flora (FLOR)": 39,
"Footstep (FSTP)": 110,
"Footstep Set (FSTS)": 111,
"FormID List (FLST)": 91,
"Furniture (FURN)": 40,
"Game Setting (GMST)": 3,
"Global Variable (GLOB)": 9,
"Grass (GRAS)": 37,
"Grenade Projectile (PGRE)": 65,
"Group (GRUP)": 2,
"Hazard (HAZD)": 51,
"Head Part (HDPT)": 12,
"Idle (IDLE)": 78,
"Idle Marker (IDLM)": 47,
"Image Space (IMGS)": 89,
"Image Space Modifier (IMAD)": 90,
"Impact Data (IPCT)": 100,
"Impact Data Set (IPDS)": 101,
"Ingredient (INGR)": 30,
"Key (KEYM)": 45,
"Keyword (KYWD)": 4,
"Land Texture (LTEX)": 20,
"Landscape (LAND)": 72,
"Leveled Actor (LVLN)": 44,
"Leveled Item (LVLI)": 53,
"Leveled Spell (LVLS)": 82,
"Light (LIGH)": 31,
"Lighting Template (LGTM)": 108,
"Load Screen (LSCR)": 81,
"Location (LCTN)": 104,
"Location Reference Type (LCRT)": 5,
"Main File Header (TES4)": 1,
"Material Object (MATO)": 126,
"Material Type (MATT)": 99,
"Menu Icon": 8,
"Message (MESG)": 105,
"Miscellaneous Object (MISC)": 32,
"Missile Projectile (PMIS)": 63,
"Movable Static (MSTT)": 36,
"Movement Type (MOVT)": 127,
"Music Track (MUST)": 116,
"Music Type (MUSC)": 109,
"Navigation (NAVI)": 59,
"Navigation Mesh (NAVM)": 73,
"None": 0,
"Note": 48,
"Object Reference (REFR)": 61,
"Outfit (OTFT)": 124,
"Perk (PERK)": 92,
"Placed Hazard (PHZD)": 70,
"Potion (ALCH)": 46,
"Projectile (PROJ)": 50,
"Quest (QUST)": 77,
"Race (RACE)": 14,
"Ragdoll (RGDL)": 106,
"Region (REGN)": 58,
"Relationship (RELA)": 121,
"Reverb Parameter (REVB)": 134,
"Scene (SCEN)": 122,
"Script (SCPT)": 19,
"Scroll Item (SCRL)": 23,
"Shader Particle Geometry Data (SPGD)": 56,
"Shout (SHOU)": 119,
"Skill": 17,
"Soul Gem (SLGM)": 52,
"Sound (SOUN)": 15,
"Sound Category (SNCT)": 130,
"Sound Descriptor (SNDR)": 128,
"Sound Output (SOPM)": 131,
"Spell (SPEL)": 22,
"Static (STAT)": 34,
"Static Collection": 35,
"Story Manager Branch Node (SMBN)": 112,
"Story Manager Event Node (SMEN)": 114,
"Story Manager Quest Node (SMQN)": 113,
"Talking Activator (TACT)": 25,
"Texture Set (TXST)": 7,
"Topic (DIAL)": 75,
"Topic Info (INFO)": 76,
"Tree (TREE)": 38,
"Visual/Reference Effect (RFCT)": 57,
"Voice Type (VTYP)": 98,
"Water (WATR)": 84,
"Weapon (WEAP)": 41,
"Weather (WTHR)": 54,
"Word of Power (WOOP)": 118,
"Worldspace (WRLD)": 71
}
return items
"""
class SublimePapyrusSkyrimAnimationEventNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
# http://www.creationkit.com/Animation_Events
def get_items(self, **args):
items = {
# Magic
"BeginCastRight (magic)": "BeginCastRight",
"BeginCastLeft (magic)": "BeginCastLeft",
"MRh_SpellFire_Event (magic)": "MRh_SpellFire_Event",
"MLh_SpellFire_Event (magic)": "MLh_SpellFire_Event",
# Hand-to-hand
"preHitFrame (hand-to-hand)": "preHitFrame",
"weaponSwing (hand-to-hand)": "weaponSwing",
"SoundPlay.WPNSwingUnarmed (hand-to-hand)": "SoundPlay.WPNSwingUnarmed",
"HitFrame (hand-to-hand)": "HitFrame",
"weaponLeftSwing (hand-to-hand)": "weaponLeftSwing",
# Bows - Quick draw and shot
"bowDraw (bows)": "bowDraw",
"SoundPlay.WPNBowNockSD (bows)": "SoundPlay.WPNBowNockSD",
"BowZoomStop (bows)": "BowZoomStop",
"arrowAttach (bows)": "arrowAttach",
"bowDrawStart (bows)": "bowDrawStart",
"InitiateWinBegin (bows)": "InitiateWinBegin",
"BowRelease (bows)": "BowRelease",
"arrowRelease (bows)": "arrowRelease",
"tailCombatIdle (bows)": "tailCombatIdle",
"AttackWinStart (bows)": "AttackWinStart",
"bowEnd (bows)": "bowEnd",
"attackStop (bows)": "attackStop",
"tailCombatState (bows)": "tailCombatState",
"bowReset (bows)": "bowReset",
"arrowDetach (bows)": "arrowDetach",
# Bows - Full draw, held for a moment
"initiateWinEnd (bows)": "initiateWinEnd",
"BowDrawn (bows)": "BowDrawn",
# Blocking
"tailCombatIdle (blocking)": "tailCombatIdle",
"SoundPlay.NPCHumanCombatShieldBlock (blocking)": "SoundPlay.NPCHumanCombatShieldBlock",
"blockStartOut (blocking)": "blockStartOut",
"SoundPlay.NPCHumanCombatShieldRelease (blocking)": "SoundPlay.NPCHumanCombatShieldRelease",
"blockStop (blocking)": "blockStop",
"SoundPlay.NPCHumanCombatShieldBash (blocking)": "SoundPlay.NPCHumanCombatShieldBash",
"preHitFrame (blocking)": "preHitFrame",
"HitFrame (blocking)": "HitFrame",
"FootScuffRight (blocking)": "FootScuffRight",
# Sneak non-combat
"tailSneakIdle (sneaking, not in combat)": "tailSneakIdle",
"tailSneakLocomotion (sneaking, not in combat)": "tailSneakLocomotion",
"tailMTIdle (sneaking, not in combat)": "tailMTIdle",
"tailMTLocomotion (sneaking, not in combat)": "tailMTLocomotion",
# Sneak combat
"tailSneakIdle (sneaking, in combat)": "tailSneakIdle",
"tailSneakLocomotion (sneaking, in combat)": "tailSneakLocomotion",
"tailCombatIdle (sneaking, in combat)": "tailCombatIdle",
"tailCombatLocomotion (sneaking, in combat)": "tailCombatLocomotion",
# Water
"SoundPlay.FSTSwimSwim (swimming)": "SoundPlay.FSTSwimSwim",
"MTState (swimming)": "MTState",
# Walking, turning, and jumping
"Left foot in motion (walking)": "FootLeft",
"Right foot in motion (walking)": "FootRight",
"Player begins jumping up (jumping)": "JumpUp",
"Player begins falling down (jumping/falling)": "JumpFall",
"Player touches the ground (jumping/falling)": "JumpDown",
"Player turns left, slowly (turning)": "turnLeftSlow",
"Player turns left, fast (turning)": "turnLeftFast",
"Player turns right, slowly (turning)": "turnRightSlow",
"Player turns right, fast (turning)": "turnRightFast",
# Sprinting
"StartAnimatedCameraDelta (sprinting)": "StartAnimatedCameraDelta",
"attackStop (sprinting)": "attackStop",
"tailSprint (sprinting)": "tailSprint",
"FootSprintRight (sprinting)": "FootSprintRight",
"FootSprintLeft (sprinting)": "FootSprintLeft",
"EndAnimatedCamera (sprinting)": "EndAnimatedCamera",
"EndAnimatedCameraDelta (sprinting)": "EndAnimatedCameraDelta",
}
return items
"""
class SublimePapyrusSkyrimTrackedStatNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"Locations Discovered": "",
"Dungeons Cleared": "",
"Days Passed": "",
"Hours Slept": "",
"Hours Waiting": "",
"Standing Stones Found": "",
"Gold Found": "",
"Most Gold Carried": "",
"Chests Looted": "",
"Skill Increases": "",
"Skill Books Read": "",
"Food Eaten": "",
"Training Sessions": "",
"Books Read": "",
"Horses Owned": "",
"Houses Owned": "",
"Stores Invested In": "",
"Barters": "",
"Persuasions": "",
"Bribes": "",
"Intimidations": "",
"Diseases Contracted": "",
"Days as a Vampire": "",
"Days as a Werewolf": "",
"Necks Bitten": "",
"Vampirism Cures": "",
"Werewolf Transformations": "",
"Mauls": "",
"Quests Completed": "",
"Misc Objectives Completed": "",
"Main Quests Completed": "",
"Side Quests Completed": "",
"The Companions Quests Completed": "",
"College of Winterhold Quests Completed": "",
"Thieves' Guild Quests Completed": "",
"The Dark Brotherhood Quests Completed": "",
"Civil War Quests Completed": "",
"Daedric Quests Completed": "",
"Questlines Completed": "",
"People Killed": "",
"Animals Killed": "",
"Creatures Killed": "",
"Undead Killed": "",
"Daedra Killed": "",
"Automatons Killed": "",
"Favorite Weapon": "",
"Critical Strikes": "",
"Sneak Attacks": "",
"Backstabs": "",
"Weapons Disarmed": "",
"Brawls Won": "",
"Bunnies Slaughtered": "",
"Spells Learned": "",
"Favorite Spell": "",
"Favorite School": "",
"Dragon Souls Collected": "",
"Words Of Power Learned": "",
"Words Of Power Unlocked": "",
"Shouts Learned": "",
"Shouts Unlocked": "",
"Shouts Mastered": "",
"Times Shouted": "",
"Favorite Shout": "",
"Soul Gems Used": "",
"Souls Trapped": "",
"Magic Items Made": "",
"Weapons Improved": "",
"Weapons Made": "",
"Armor Improved": "",
"Armor Made": "",
"Potions Mixed": "",
"Potions Used": "",
"Poisons Mixed": "",
"Poisons Used": "",
"Ingredients Harvested": "",
"Ingredients Eaten": "",
"Nirnroots Found": "",
"Wings Plucked": "",
"Total Lifetime Bounty": "",
"Largest Bounty": "",
"Locks Picked": "",
"Pockets Picked": "",
"Items Pickpocketed": "",
"Times Jailed": "",
"Days Jailed": "",
"Fines Paid": "",
"Jail Escapes": "",
"Items Stolen": "",
"Assaults": "",
"Murders": "",
"Horses Stolen": "",
"Trespasses": "",
"Eastmarch Bounty": "",
"Falkreath Bounty": "",
"Haafingar Bounty": "",
"Hjaalmarch Bounty": "",
"The Pale Bounty": "",
"The Reach Bounty": "",
"The Rift Bounty": "",
"Tribal Orcs Bounty": "",
"Whiterun Bounty": "",
"Winterhold Bounty": ""
}
return items
class SublimePapyrusSkyrimBooleanAnimationVariableNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"bMotionDriven": "",
"IsBeastRace": "",
"IsSneaking": "",
"IsBleedingOut": "",
"IsCastingDual": "",
"Is1HM": "",
"IsCastingRight": "",
"IsCastingLeft": "",
"IsBlockHit": "",
"IsPlayer": "",
"IsNPC": "",
"bIsSynced": "",
"bVoiceReady": "",
"bWantCastLeft": "",
"bWantCastRight": "",
"bWantCastVoice": "",
"b1HM_MLh_attack": "",
"b1HMCombat": "",
"bAnimationDriven": "",
"bCastReady": "",
"bAllowRotation": "",
"bMagicDraw": "",
"bMLh_Ready": "",
"bMRh_Ready": "",
"bInMoveState": "",
"bSprintOK": "",
"bIdlePlaying": "",
"bIsDialogueExpressive": "",
"bAnimObjectLoaded": "",
"bEquipUnequip": "",
"bAttached": "",
"bEquipOK": "",
"bIsH2HSolo": "",
"bHeadTracking": "",
"bIsRiding": "",
"bTalkable": "",
"bRitualSpellActive": "",
"bInJumpState": "",
"bHeadTrackSpine": "",
"bLeftHandAttack": "",
"bIsInMT": "",
"bHumanoidFootIKEnable": "",
"bHumanoidFootIKDisable": "",
"bStaggerPlayerOverride": "",
"bNoStagger": "",
"bIsStaffLeftCasting": "",
"bPerkShieldCharge": "",
"bPerkQuickShot": "",
"IsAttacking": "",
"Isblocking": "",
"IsBashing": "",
"IsStaggering": "",
"IsRecoiling": "",
"IsEquipping": "",
"IsUnequipping": ""
}
return items
class SublimePapyrusSkyrimFloatAnimationVariableNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"Speed": "",
"VelocityZ": "",
"camerafromx": "",
"camerafromy": "",
"camerafromz": "",
"FemaleOffset": "",
"bodyMorphWeight": "",
"IsInCastState": "",
"IsInCastStateDamped": "",
"blockDown": "",
"blockLeft": "",
"blockRight": "",
"blockUp": "",
"Direction": "",
"TurnDelta": "",
"SpeedWalk": "",
"SpeedRun": "",
"fSpeedMin": "",
"fEquipWeapAdj": "",
"fIdleTimer": "",
"fMinSpeed": "",
"fTwistDirection": "",
"TurnDeltaDamped": "",
"TurnMin": "",
"Pitch": "",
"PitchLook": "",
"attackPowerStartTime": "",
"PitchDefault": "",
"PitchOverride": "",
"staggerMagnitude": "",
"recoilMagnitude": "",
"SpeedSampled": "",
"attackComboStartFraction": "",
"attackIntroLength": "",
"TimeDelta": "",
"PitchOffset": "",
"PitchAcc": "",
"PitchThresh": "",
"weapChangeStartFraction": "",
"RotMax": "",
"1stPRot": "",
"1stPRotDamped": "",
"PitchManualOverride": "",
"SpeedAcc": ""
}
return items
class SublimePapyrusSkyrimIntegerAnimationVariableNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"iSyncIdleLocomotion": "",
"IsAttackReady_32": "",
"iRightHandType": "",
"iWantBlock": "",
"iAnnotation": "",
"iSyncTurnState": "",
"i1stPerson": "",
"iLeftHandType": "",
"iState": "",
"iState_NPCSprinting": "",
"iState_NPCDefault": "",
"iState_NPCSneaking": "",
"iState_NPCBowDrawn :Sets actor in a bow drawn state. *": "",
"iDualMagicState": "",
"iState_NPCBlocking": "",
"iState_NPCBleedout": "",
"iBlockState": "",
"iSyncSprintState": "",
"iIsInSneak": "",
"iMagicEquipped": "",
"iEquippedItemState": "",
"iMagicState": "",
"iIsDialogueExpressive": "",
"iSyncIdleState": "",
"iState_NPC1HM": "",
"iState_NPC2HM": "",
"iState_NPCBow": "",
"iState_NPCMagic": "",
"iState_NPCMagicCasting": "",
"iState_NPCHorse": "",
"iState_HorseSprint": "",
"iCharacterSelector": "",
"iCombatStance": "",
"iSyncTurnDirection": "",
"iRegularAttack": "",
"iRightHandEquipped": "",
"iLeftHandEquipped": "",
"iIsPlayer": "",
"iGetUpType": "",
"iState_NPCAttacking": "",
"iState_NPCPowerAttacking": "",
"iState_NPCAttacking2H": "",
"iDrunkVariable": "",
"iState_NPCDrunk": "",
"iTempSwitch": "",
"iState_NPCBowDrawnQuickShot": "",
"iState_NPCBlockingShieldCharge": ""
}
return items
class SublimePapyrusSkyrimFloatGameSettingNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"fActiveEffectConditionUpdateInterval": "",
"fActorAlertSoundTimer": "",
"fActorAlphaFadeSeconds": "",
"fActorAnimZAdjust": "",
"fActorArmorDesirabilityDamageMult": "",
"fActorArmorDesirabilitySkillMult": "",
"fActorDefaultTurningSpeed": "",
"fActorLeaveWaterBreathTimer": "",
"fActorLuckSkillMult": "",
"fActorStrengthEncumbranceMult": "",
"fActorSwimBreathBase": "",
"fActorSwimBreathDamage": "",
"fActorSwimBreathMult": "",
"fActorTeleportFadeSeconds": "",
"fActorWeaponDesirabilityDamageMult": "",
"fActorWeaponDesirabilitySkillMult": "",
"fAddictionUsageMonitorThreshold": "",
"fAiAcquireKillBase": "",
"fAiAcquireKillMult": "",
"fAIAcquireObjectDistance": "",
"fAiAcquirePickBase": "",
"fAiAcquirePickMult": "",
"fAiAcquireStealBase": "",
"fAiAcquireStealMult": "",
"fAIActivateHeight": "",
"fAIActivateReach": "",
"fAIActorPackTargetHeadTrackMod": "",
"fAIAimBlockedHalfCircleRadius": "",
"fAIAimBlockedToleranceDegrees": "",
"fAIAwareofPlayerTimer": "",
"fAIBestHeadTrackDistance": "",
"fAICombatFleeScoreThreshold": "",
"fAICombatNoAreaEffectAllyDistance": "",
"fAICombatNoTargetLOSPriorityMult": "",
"fAICombatSlopeDifference": "",
"fAICombatTargetUnreachablePriorityMult": "",
"fAICombatUnreachableTargetPriorityMult": "",
"fAICommentTimeWindow": "",
"fAIConversationExploreTime": "",
"fAIDefaultSpeechMult": "",
"fAIDialogueDistance": "",
"fAIDistanceRadiusMinLocation": "",
"fAIDistanceTeammateDrawWeapon": "",
"fAIDodgeDecisionBase": "",
"fAIDodgeFavorLeftRightMult": "",
"fAIDodgeVerticalRangedAttackMult": "",
"fAIDodgeWalkChance": "",
"fAIEnergyLevelBase": "",
"fAIEngergyLevelMult": "",
"fAIEscortFastTravelMaxDistFromPath": "",
"fAIEscortHysteresisWidth": "",
"fAIEscortStartStopDelayTime": "",
"fAIEscortWaitDistanceExterior": "",
"fAIEscortWaitDistanceInterior": "",
"fAIExclusiveGreetingTimer": "",
"fAIExplosiveWeaponDamageMult": "",
"fAIExplosiveWeaponRangeMult": "",
"fAIExteriorSpectatorDetection": "",
"fAIExteriorSpectatorDistance": "",
"fAIFaceTargetAnimationAngle": "",
"fAIFindBedChairsDistance": "",
"fAIFleeConfBase": "",
"fAIFleeConfMult": "",
"fAIFleeHealthMult": "",
"fAIFleeSuccessTimeout": "",
"fAIForceGreetingTimer": "",
"fAIFurnitureDestinationRadius": "",
"fAIGreetingTimer": "",
"fAIHeadTrackDialogueOffsetRandomValue": "",
"fAIHeadTrackDialoguePickNewOffsetTimer": "",
"fAIHeadTrackDialogueResetPositionTimer": "",
"fAIHeadTrackDialogueStayInOffsetMax": "",
"fAIHeadTrackDialogueStayInOffsetMin": "",
"fAIHeadTrackOffsetRandomValueMax": "",
"fAIHeadTrackOffsetRandomValueMin": "",
"fAIHeadTrackPickNewOffsetTimer": "",
"fAIHeadTrackResetPositionTimer": "",
"fAIHeadTrackStayInOffsetMax": "",
"fAIHeadTrackStayInOffsetMin": "",
"fAIHoldDefaultHeadTrackTimer": "",
"fAIHorseSearchDistance": "",
"fAIIdleAnimationDistance": "",
"fAIIdleAnimationLargeCreatureDistanceMult3.000000": "",
"fAIIdleWaitTimeComplexScene": "",
"fAIIdleWaitTime": "",
"fAIInDialogueModeWithPlayerDistance": "",
"fAIInDialogueModewithPlayerTimer": "",
"fAIInteriorHeadTrackMult": "",
"fAIInteriorSpectatorDetection": "",
"fAIInteriorSpectatorDistance": "",
"fAILockDoorsSeenRecentlySeconds": "",
"fAIMagicSpellMult": "",
"fAIMagicTimer": "",
"fAIMarkerDestinationRadius": "",
"fAIMaxAngleRangeMovingToStartSceneDialogue": "",
"fAIMaxHeadTrackDistanceFromPC": "",
"fAIMaxHeadTrackDistance": "",
"fAIMaxLargeCreatureHeadTrackDistance": "",
"fAIMaxSmileDistance": "",
"fAIMaxWanderTime": "",
"fAIMeleeArmorMult": "",
"fAIMeleeHandMult": "",
"fAIMinAngleRangeToStartSceneDialogue": "",
"fAIMinGreetingDistance": "",
"fAIMinLocationHeight": "",
"fAIMoveDistanceToRecalcFollowPath": "",
"fAIMoveDistanceToRecalcTravelPath": "",
"fAIMoveDistanceToRecalcTravelToActor": "",
"fAIPatrolHysteresisWidth": "",
"fAIPatrolMinSecondsAtNormalFurniture": "",
"fAIPowerAttackCreatureChance": "",
"fAIPowerAttackKnockdownBonus": "",
"fAIPowerAttackNPCChance": "",
"fAIPowerAttackRecoilBonus": "",
"fAIPursueDistanceLineOfSight": "",
"fAIRandomizeInitialLocationMinRadius": "",
"fAIRangedWeaponMult": "",
"fAIRangMagicSpellMult": "",
"fAIRevertToScriptTracking": "",
"fAIShoutMinAimSeconds": "",
"fAIShoutRetryDelaySeconds": "",
"fAIShoutToleranceDegrees": "",
"fAISocialchanceForConversationInterior": "",
"fAISocialchanceForConversation": "",
"fAISocialRadiusToTriggerConversationInterior": "",
"fAISocialRadiusToTriggerConversation": "",
"fAISocialTimerForConversationsMax": "",
"fAISocialTimerForConversationsMin": "",
"fAISocialTimerToWaitForEvent": "",
"fAISpectatorCommentTimer": "",
"fAISpectatorRememberThreatTimer": "",
"fAISpectatorShutdownDistance": "",
"fAISpectatorThreatDistExplosion": "",
"fAISpectatorThreatDistMelee": "",
"fAISpectatorThreatDistMine": "",
"fAISpectatorThreatDistRanged": "",
"fAIStayonScriptHeadtrack": "",
"fAItalktoNPCtimer": "",
"fAItalktosameNPCtimer": "",
"fAITrespassWarningTimer": "",
"fAIUpdateMovementRestrictionsDistance": "",
"fAIUseMagicToleranceDegrees": "",
"fAIUseWeaponAnimationTimeoutSeconds": "",
"fAIUseWeaponDistance": "",
"fAIUseWeaponToleranceDegrees": "",
"fAIWaitingforScriptCallback": "",
"fAIWalkAwayTimerForConversation": "",
"fAIWanderDefaultMinDist": "",
"fAlchemyGoldMult": "",
"fAlchemyIngredientInitMult": "",
"fAlchemySkillFactor": "",
"fAmbushOverRideRadiusforPlayerDetection": "",
"fArmorBaseFactor": "",
"fArmorRatingBase": "",
"fArmorRatingMax": "",
"fArmorRatingPCBase": "",
"fArmorRatingPCMax": "",
"fArmorScalingFactor": "",
"fArmorWeightLightMaxMod": "",
"fArrowBounceBlockPercentage": "",
"fArrowBounceLinearSpeed": "",
"fArrowBounceRotateSpeed": "",
"fArrowBowFastMult": "",
"fArrowBowMinTime": "",
"fArrowBowSlowMult": "",
"fArrowFakeMass": "",
"fArrowGravityBase": "",
"fArrowGravityMin": "",
"fArrowGravityMult": "",
"fArrowMaxDistance": "",
"fArrowMinBowVelocity": "",
"fArrowMinDistanceForTrails": "",
"fArrowMinPower": "",
"fArrowMinSpeedForTrails": "",
"fArrowMinVelocity": "",
"fArrowOptimalDistance": "",
"fArrowSpeedMult": "",
"fArrowWeakGravity": "",
"fAuroraFadeInStart": "",
"fAuroraFadeOutStart": "",
"fAutoAimMaxDegrees3rdPerson": "",
"fAutoAimMaxDegreesMelee": "",
"fAutoAimMaxDegreesVATS": "",
"fAutoAimMaxDegrees": "",
"fAutoAimMaxDistance": "",
"fAutoAimScreenPercentage": "",
"fAutomaticWeaponBurstCooldownTime": "",
"fAutomaticWeaponBurstFireTime": "",
"fAutoraFadeIn": "",
"fAutoraFadeOut": "",
"fAvoidPlayerDistance": "",
"fBarterBuyMin": "",
"fBarterMax": "",
"fBarterMin": "",
"fBarterSellMax": "",
"fBeamWidthDefault": "",
"fBigBumpSpeed": "",
"fBleedoutCheck": "",
"fBleedoutDefault": "",
"fBleedoutMin": "",
"fBleedoutRate": "",
"fBleedoutRecover": "",
"fBlinkDelayMax": "",
"fBlinkDelayMin": "",
"fBlinkDownTime": "",
"fBlinkUpTime": "",
"fBlockAmountHandToHandMult": "",
"fBlockAmountWeaponMult": "",
"fBlockMax": "",
"fBlockPowerAttackMult": "",
"fBlockScoreNoShieldMult": "",
"fBlockSkillBase": "",
"fBlockSkillMult": "",
"fBlockWeaponBase": "",
"fBlockWeaponScaling": "",
"fBloodSplatterCountBase": "",
"fBloodSplatterCountDamageBase": "",
"fBloodSplatterCountDamageMult": "",
"fBloodSplatterCountRandomMargin": "",
"fBloodSplatterDuration": "",
"fBloodSplatterFadeStart": "",
"fBloodSplatterFlareMult": "",
"fBloodSplatterFlareOffsetScale": "",
"fBloodSplatterFlareSize": "",
"fBloodSplatterMaxOpacity2": "",
"fBloodSplatterMaxOpacity": "",
"fBloodSplatterMaxSize": "",
"fBloodSplatterMinOpacity2": "",
"fBloodSplatterMinOpacity": "",
"fBloodSplatterMinSize": "",
"fBloodSplatterOpacityChance": "",
"fBowDrawTime": "",
"fBowHoldTimer": "",
"fBowNPCSpreadAngle": "",
"fBowZoomStaminaDrainMult": "",
"fBowZoomStaminaRegenDelay": "",
"fBribeBase": "",
"fBribeCostCurve": "",
"fBribeMoralityMult": "",
"fBribeMult": "",
"fBribeNPCLevelMult": "",
"fBribeScale": "",
"fBribeSpeechcraftMult": "",
"fBumpReactionIdealMoveDist": "",
"fBumpReactionMinMoveDist": "",
"fBumpReactionSmallDelayTime": "",
"fBumpReactionSmallWaitTimer": "",
"fBuoyancyMultBody": "",
"fBuoyancyMultExtremity": "",
"fCameraShakeDistFadeDelta": "",
"fCameraShakeDistFadeStart": "",
"fCameraShakeDistMin": "",
"fCameraShakeExplosionDistMult": "",
"fCameraShakeFadeTime": "",
"fCameraShakeMultMin": "",
"fCameraShakeTime": "",
"fChaseDetectionTimerSetting": "",
"fCheckDeadBodyTimer": "",
"fCheckPositionFallDistance": "",
"fClosetoPlayerDistance": "",
"fClothingArmorBase": "",
"fClothingArmorScale": "",
"fClothingBase": "",
"fClothingClassScale": "",
"fClothingJewelryBase": "",
"fClothingJewelryScale": "",
"fCombatAbsoluteMaxRangeMult": "",
"fCombatAcquirePickupAnimationDelay": "",
"fCombatAcquireWeaponAmmoMinimumScoreMult": "",
"fCombatAcquireWeaponAvoidTargetRadius": "",
"fCombatAcquireWeaponCloseDistanceMax": "",
"fCombatAcquireWeaponCloseDistanceMin": "",
"fCombatAcquireWeaponDisarmedAcquireTime": "",
"fCombatAcquireWeaponDisarmedDistanceMax": "",
"fCombatAcquireWeaponDisarmedDistanceMin": "",
"fCombatAcquireWeaponDisarmedTime": "",
"fCombatAcquireWeaponEnchantmentChargeMult": "",
"fCombatAcquireWeaponFindAmmoDistance": "",
"fCombatAcquireWeaponMeleeScoreMult": "",
"fCombatAcquireWeaponMinimumScoreMult": "",
"fCombatAcquireWeaponMinimumTargetDistance": "",
"fCombatAcquireWeaponRangedDistanceMax": "",
"fCombatAcquireWeaponRangedDistanceMin": "",
"fCombatAcquireWeaponReachDistance": "",
"fCombatAcquireWeaponScoreCostMult": "",
"fCombatAcquireWeaponScoreRatioMax": "",
"fCombatAcquireWeaponSearchFailedDelay": "",
"fCombatAcquireWeaponSearchRadiusBuffer": "",
"fCombatAcquireWeaponSearchSuccessDelay": "",
"fCombatAcquireWeaponTargetDistanceCheck": "",
"fCombatAcquireWeaponUnarmedDistanceMax": "",
"fCombatAcquireWeaponUnarmedDistanceMin": "",
"fCombatActiveCombatantAttackRangeDistance": "",
"fCombatActiveCombatantLastSeenTime": "",
"fCombatAdvanceInnerRadiusMax": "",
"fCombatAdvanceInnerRadiusMid": "",
"fCombatAdvanceInnerRadiusMin": "",
"fCombatAdvanceLastDamagedThreshold": "",
"fCombatAdvanceNormalAttackChance": "",
"fCombatAdvanceOuterRadiusMax": "",
"fCombatAdvanceOuterRadiusMid": "",
"fCombatAdvanceOuterRadiusMin": "",
"fCombatAdvancePathRetryTime": "",
"fCombatAdvanceRadiusStaggerMult": "",
"fCombatAimDeltaThreshold": "",
"fCombatAimLastSeenLocationTimeLimit": "",
"fCombatAimMeleeHighPriorityUpdateTime": "",
"fCombatAimMeleeUpdateTime": "",
"fCombatAimProjectileBlockedTime": "",
"fCombatAimProjectileBlockedTime": "",
"fCombatAimProjectileGroundMinRadius": "",
"fCombatAimProjectileRandomOffset": "",
"fCombatAimProjectileUpdateTime": "",
"fCombatAimTrackTargetUpdateTime": "",
"fCombatAngleTolerance": "",
"fCombatAnticipatedLocationCheckDistance": "",
"fCombatAnticipateTime": "",
"fCombatApproachTargetSlowdownDecelerationMult": "",
"fCombatApproachTargetSlowdownDistance": "",
"fCombatApproachTargetSlowdownUpdateTime": "",
"fCombatApproachTargetSlowdownVelocityAngle": "",
"fCombatApproachTargetSprintStopMovingRange": "",
"fCombatApproachTargetSprintStopRange": "",
"fCombatApproachTargetUpdateTime": "",
"fCombatAreaHoldPositionMinimumRadius": "",
"fCombatAreaStandardAttackedRadius": "",
"fCombatAreaStandardAttackedTime": "",
"fCombatAreaStandardCheckViewConeDistanceMax": "",
"fCombatAreaStandardCheckViewConeDistanceMin": "",
"fCombatAreaStandardFlyingRadiusMult": "",
"fCombatAreaStandardRadius": "",
"fCombatAttackAllowedOverrunDistance": "",
"fCombatAttackAnimationDrivenDelayTime": "",
"fCombatAttackAnticipatedDistanceMin": "",
"fCombatAttackChanceBlockingMultMax": "",
"fCombatAttackChanceBlockingMultMin": "",
"fCombatAttackChanceBlockingSwingMult": "",
"fCombatAttackChanceLastAttackBonusTime": "",
"fCombatAttackChanceLastAttackBonus": "",
"fCombatAttackChanceMax": "",
"fCombatAttackChanceMin": "",
"fCombatAttackCheckTargetRangeDistance": "",
"fCombatAttackMovingAttackDistance": "",
"fCombatAttackMovingAttackReachMult": "",
"fCombatAttackMovingStrikeAngleMult": "",
"fCombatAttackPlayerAnticipateMult": "",
"fCombatAttackStationaryAttackDistance": "",
"fCombatAttackStrikeAngleMult": "",
"fCombatAvoidThreatsChance": "",
"fCombatBackoffChance": "",
"fCombatBackoffMinDistanceMult": "",
"fCombatBashChanceMax": "",
"fCombatBashChanceMin": "",
"fCombatBashReach": "",
"fCombatBashTargetBlockingMult": "",
"fCombatBetweenAdvanceTimer": "",
"fCombatBlockAttackChanceMax": "",
"fCombatBlockAttackChanceMin": "",
"fCombatBlockAttackReachMult": "",
"fCombatBlockAttackStrikeAngleMult": "",
"fCombatBlockChanceMax": "",
"fCombatBlockChanceMin": "",
"fCombatBlockChanceWeaponMult": "",
"fCombatBlockMaxTargetRetreatVelocity": "",
"fCombatBlockStartDistanceMax": "",
"fCombatBlockStartDistanceMin": "",
"fCombatBlockStopDistanceMax": "",
"fCombatBlockStopDistanceMin": "",
"fCombatBlockTimeMax": "",
"fCombatBlockTimeMid": "",
"fCombatBlockTimeMin": "",
"fCombatBoundWeaponDPSBonus": "",
"fCombatBuffMaxTimer": "",
"fCombatBuffStandoffTimer": "",
"fCombatCastConcentrationOffensiveMagicCastTimeMax": "",
"fCombatCastConcentrationOffensiveMagicCastTimeMin": "",
"fCombatCastConcentrationOffensiveMagicChanceMax": "",
"fCombatCastConcentrationOffensiveMagicChanceMin": "",
"fCombatCastConcentrationOffensiveMagicWaitTimeMax": "",
"fCombatCastConcentrationOffensiveMagicWaitTimeMin": "",
"fCombatCastImmediateOffensiveMagicChanceMax": "",
"fCombatCastImmediateOffensiveMagicChanceMin": "",
"fCombatCastImmediateOffensiveMagicHoldTimeAbsoluteMin": "",
"fCombatCastImmediateOffensiveMagicHoldTimeMax": "",
"fCombatCastImmediateOffensiveMagicHoldTimeMinDistance": "",
"fCombatCastImmediateOffensiveMagicHoldTimeMin": "",
"fCombatChangeProcessFaceTargetDistance": "",
"fCombatCircleAngleMax": "",
"fCombatCircleAngleMin": "",
"fCombatCircleAnglePlayerMult": "",
"fCombatCircleChanceMax": "",
"fCombatCircleChanceMin": "",
"fCombatCircleDistanceMax": "",
"fCombatCircleDistantChanceMax": "",
"fCombatCircleDistantChanceMin": "",
"fCombatCircleMinDistanceMult": "",
"fCombatCircleMinDistanceRadiusMult": "",
"fCombatCircleMinMovementDistance": "",
"fCombatCircleViewConeAngle": "",
"fCombatCloseRangeTrackTargetDistance": "",
"fCombatClusterUpdateTime": "",
"fCombatCollectAlliesTimer": "",
"fCombatConfidenceModifierMax": "",
"fCombatConfidenceModifierMin": "",
"fCombatCoverAttackMaxWaitTime": "",
"fCombatCoverAttackOffsetDistance": "",
"fCombatCoverAttackTimeMax": "",
"fCombatCoverAttackTimeMid": "",
"fCombatCoverAttackTimeMin": "",
"fCombatCoverAvoidTargetRadius": "",
"fCombatCoverCheckCoverHeightMin": "",
"fCombatCoverCheckCoverHeightOffset": "",
"fCombatCoverEdgeOffsetDistance": "",
"fCombatCoverLedgeOffsetDistance": "",
"fCombatCoverMaxRangeMult": "",
"fCombatCoverMidPointMaxRangeBuffer": "",
"fCombatCoverMinimumActiveRange": "",
"fCombatCoverMinimumRange": "",
"fCombatCoverObstacleMovedTime": "",
"fCombatCoverRangeMaxActiveMult": "",
"fCombatCoverRangeMaxBufferDistance": "",
"fCombatCoverRangeMinActiveMult": "",
"fCombatCoverRangeMinBufferDistance": "",
"fCombatCoverReservationWidthMult": "",
"fCombatCoverSearchDistanceMax": "",
"fCombatCoverSearchDistanceMin": "",
"fCombatCoverSearchFailedDelay": "",
"fCombatCoverSecondaryThreatLastSeenTime": "",
"fCombatCoverSecondaryThreatMinDistance": "",
"fCombatCoverWaitLookOffsetDistance": "",
"fCombatCoverWaitTimeMax": "",
"fCombatCoverWaitTimeMid": "",
"fCombatCoverWaitTimeMin": "",
"fCombatCurrentWeaponAbsoluteMaxRangeMult": "",
"fCombatDamageBonusMeleeSneakingMult": "",
"fCombatDamageBonusSneakingMult": "",
"fCombatDamageScale": "",
"fCombatDeadActorHitConeMult": "",
"fCombatDetectionDialogueIdleMaxElapsedTime": "",
"fCombatDetectionDialogueIdleMinElapsedTime": "",
"fCombatDetectionDialogueMaxElapsedTime": "",
"fCombatDetectionDialogueMinElapsedTime": "",
"fCombatDetectionFleeingLostRemoveTime": "",
"fCombatDetectionLostCheckNoticedDistance": "",
"fCombatDetectionLostRemoveDistanceTime": "",
"fCombatDetectionLostRemoveDistance": "",
"fCombatDetectionLostRemoveTime": "",
"fCombatDetectionLostTimeLimit": "",
"fCombatDetectionLowDetectionDistance": "",
"fCombatDetectionLowPriorityDistance": "",
"fCombatDetectionNoticedDistanceLimit": "",
"fCombatDetectionNoticedTimeLimit": "",
"fCombatDetectionVeryLowPriorityDistance": "",
"fCombatDialogueAllyKilledDistanceMult": "",
"fCombatDialogueAllyKilledMaxElapsedTime": "",
"fCombatDialogueAllyKilledMinElapsedTime": "",
"fCombatDialogueAttackDistanceMult": "",
"fCombatDialogueAttackMaxElapsedTime": "",
"fCombatDialogueAttackMinElapsedTime": "",
"fCombatDialogueAvoidThreatDistanceMult": "",
"fCombatDialogueAvoidThreatMaxElapsedTime": "",
"fCombatDialogueAvoidThreatMinElapsedTime": "",
"fCombatDialogueBashDistanceMult": "",
"fCombatDialogueBleedoutDistanceMult": "",
"fCombatDialogueBleedOutMaxElapsedTime": "",
"fCombatDialogueBleedOutMinElapsedTime": "",
"fCombatDialogueBlockDistanceMult": "",
"fCombatDialogueDeathDistanceMult": "",
"fCombatDialogueFleeDistanceMult": "",
"fCombatDialogueFleeMaxElapsedTime": "",
"fCombatDialogueFleeMinElapsedTime": "",
"fCombatDialogueGroupStrategyDistanceMult": "",
"fCombatDialogueHitDistanceMult": "",
"fCombatDialoguePowerAttackDistanceMult": "",
"fCombatDialogueTauntDistanceMult": "",
"fCombatDialogueTauntMaxElapsedTime": "",
"fCombatDialogueTauntMinElapsedTime": "",
"fCombatDisarmedFindBetterWeaponInitialTime": "",
"fCombatDisarmedFindBetterWeaponTime": "",
"fCombatDismemberedLimbVelocity": "",
"fCombatDistanceMin": "",
"fCombatDistance": "",
"fCombatDiveBombChanceMax": "",
"fCombatDiveBombChanceMin": "",
"fCombatDiveBombOffsetPercent": "",
"fCombatDiveBombSlowDownDistance": "",
"fCombatDodgeAccelerationMult": "",
"fCombatDodgeAcceptableThreatScoreMult": "",
"fCombatDodgeAnticipateThreatTime": "",
"fCombatDodgeBufferDistance": "",
"fCombatDodgeChanceMax": "",
"fCombatDodgeChanceMin": "",
"fCombatDodgeDecelerationMult": "",
"fCombatDodgeMovingReactionTime": "",
"fCombatDodgeReactionTime": "",
"fCombatDPSBowSpeedMult": "",
"fCombatDPSMeleeSpeedMult": "",
"fCombatEffectiveDistanceAnticipateTime": "",
"fCombatEnvironmentBloodChance": "",
"fCombatFallbackChanceMax": "",
"fCombatFallbackChanceMin": "",
"fCombatFallbackDistanceMax": "",
"fCombatFallbackDistanceMin": "",
"fCombatFallbackMaxAngle": "",
"fCombatFallbackMinMovementDistance": "",
"fCombatFallbackWaitTimeMax": "",
"fCombatFallbackWaitTimeMin": "",
"fCombatFindAllyAttackLocationAllyRadius": "",
"fCombatFindAllyAttackLocationDistanceMax": "",
"fCombatFindAllyAttackLocationDistanceMin": "",
"fCombatFindAttackLocationAvoidTargetRadius": "",
"fCombatFindAttackLocationDistance": "",
"fCombatFindAttackLocationKeyAngle": "",
"fCombatFindAttackLocationKeyHeight": "",
"fCombatFindBetterWeaponTime": "",
"fCombatFindLateralAttackLocationDistance": "",
"fCombatFindLateralAttackLocationIntervalMax": "",
"fCombatFindLateralAttackLocationIntervalMin": "",
"fCombatFiringArcStationaryTurnMult": "",
"fCombatFlankingAngleOffsetCostMult": "",
"fCombatFlankingAngleOffsetMax": "",
"fCombatFlankingAngleOffset": "",
"fCombatFlankingDirectionDistanceMult": "",
"fCombatFlankingDirectionGoalAngleOffset": "",
"fCombatFlankingDirectionOffsetCostMult": "",
"fCombatFlankingDirectionRotateAngleOffset": "",
"fCombatFlankingDistanceMax": "",
"fCombatFlankingDistanceMin": "",
"fCombatFlankingGoalAngleFarMaxDistance": "",
"fCombatFlankingGoalAngleFarMax": "",
"fCombatFlankingGoalAngleFarMinDistance": "",
"fCombatFlankingGoalAngleFarMin": "",
"fCombatFlankingGoalAngleNear": "",
"fCombatFlankingGoalCheckDistanceMax": "",
"fCombatFlankingGoalCheckDistanceMin": "",
"fCombatFlankingGoalCheckDistanceMult": "",
"fCombatFlankingLocationGridSize": "",
"fCombatFlankingMaxTurnAngleGoal": "",
"fCombatFlankingMaxTurnAngle": "",
"fCombatFlankingNearDistance": "",
"fCombatFlankingRotateAngle": "",
"fCombatFlankingStalkRange": "",
"fCombatFlankingStalkTimeMax": "",
"fCombatFlankingStalkTimeMin": "",
"fCombatFlankingStepDistanceMax": "",
"fCombatFlankingStepDistanceMin": "",
"fCombatFlankingStepDistanceMult": "",
"fCombatFleeAllyDistanceMax": "",
"fCombatFleeAllyDistanceMin": "",
"fCombatFleeAllyRadius": "",
"fCombatFleeCoverMinDistance": "",
"fCombatFleeCoverSearchRadius": "",
"fCombatFleeDistanceExterior": "",
"fCombatFleeDistanceInterior": "",
"fCombatFleeDoorDistanceMax": "",
"fCombatFleeDoorTargetCheckDistance": "",
"fCombatFleeInitialDoorRestrictChance": "",
"fCombatFleeLastDoorRestrictTime": "",
"fCombatFleeTargetAvoidRadius": "",
"fCombatFleeTargetGatherRadius": "",
"fCombatFleeUseDoorChance": "",
"fCombatFleeUseDoorRestrictTime": "",
"fCombatFlightEffectiveDistance": "",
"fCombatFlightMinimumRange": "",
"fCombatFlyingAttackChanceMax": "",
"fCombatFlyingAttackChanceMin": "",
"fCombatFlyingAttackTargetDistanceThreshold": "",
"fCombatFollowRadiusBase": "",
"fCombatFollowRadiusMin": "",
"fCombatFollowRadiusMult": "",
"fCombatFollowSneakFollowRadius": "",
"fCombatForwardAttackChance": "",
"fCombatGiantCreatureReachMult": "",
"fCombatGrenadeBounceTimeMax": "",
"fCombatGrenadeBounceTimeMin": "",
"fCombatGroundAttackChanceMax": "",
"fCombatGroundAttackChanceMin": "",
"fCombatGroundAttackTimeMax": "",
"fCombatGroundAttackTimeMin": "",
"fCombatGroupCombatStrengthUpdateTime": "",
"fCombatGroupOffensiveMultMin": "",
"fCombatGuardFollowBufferDistance": "",
"fCombatGuardRadiusMin": "",
"fCombatGuardRadiusMult": "",
"fCombatHealthRegenRateMult": "",
"fCombatHideCheckViewConeDistanceMax": "",
"fCombatHideCheckViewConeDistanceMin": "",
"fCombatHideFailedTargetDistance": "",
"fCombatHideFailedTargetLOSDistance": "",
"fCombatHitConeAngle": "",
"fCombatHoverAngleLimit": "",
"fCombatHoverAngleMax": "",
"fCombatHoverAngleMin": "",
"fCombatHoverChanceMax": "",
"fCombatHoverChanceMin": "",
"fCombatHoverTimeMax": "",
"fCombatHoverTimeMin": "",
"fCombatInTheWayTimer": "",
"fCombatInventoryDesiredRangeScoreMultMax": "",
"fCombatInventoryDesiredRangeScoreMultMid": "",
"fCombatInventoryDesiredRangeScoreMultMin": "",
"fCombatInventoryDualWieldScorePenalty": "",
"fCombatInventoryEquipmentMinScoreMult": "",
"fCombatInventoryEquippedScoreBonus": "",
"fCombatInventoryMaxRangeEquippedBonus": "",
"fCombatInventoryMaxRangeScoreMult": "",
"fCombatInventoryMeleeEquipRange": "",
"fCombatInventoryMinEquipTimeBlock": "",
"fCombatInventoryMinEquipTimeDefault": "",
"fCombatInventoryMinEquipTimeMagic": "",
"fCombatInventoryMinEquipTimeShout": "",
"fCombatInventoryMinEquipTimeStaff": "",
"fCombatInventoryMinEquipTimeTorch": "",
"fCombatInventoryMinEquipTimeWeapon": "",
"fCombatInventoryMinRangeScoreMult": "",
"fCombatInventoryMinRangeUnequippedBonus": "",
"fCombatInventoryOptimalRangePercent": "",
"fCombatInventoryRangedScoreMult": "",
"fCombatInventoryResourceCurrentRequiredMult": "",
"fCombatInventoryResourceDesiredRequiredMult": "",
"fCombatInventoryResourceRegenTime": "",
"fCombatInventoryShieldEquipRange": "",
"fCombatInventoryShoutMaxRecoveryTime": "",
"fCombatInventoryTorchEquipRange": "",
"fCombatInventoryUpdateTimer": "",
"fCombatIronSightsDistance": "",
"fCombatIronSightsRangeMult": "",
"fCombatItemBuffTimer": "",
"fCombatItemRestoreTimer": "",
"fCombatKillMoveDamageMult": "",
"fCombatLandingAvoidActorRadius": "",
"fCombatLandingSearchDistance": "",
"fCombatLandingZoneDistance": "",
"fCombatLineOfSightTimer": "",
"fCombatLocationTargetRadiusMin": "",
"fCombatLowFleeingTargetHitPercent": "",
"fCombatLowMaxAttackDistance": "",
"fCombatLowTargetHitPercent": "",
"fCombatMagicArmorDistanceMax": "",
"fCombatMagicArmorDistanceMin": "",
"fCombatMagicArmorMinCastTime": "",
"fCombatMagicBoundItemDistance": "",
"fCombatMagicBuffDuration": "",
"fCombatMagicCloakDistanceMax": "",
"fCombatMagicCloakDistanceMin": "",
"fCombatMagicCloakMinCastTime": "",
"fCombatMagicConcentrationAimVariance": "",
"fCombatMagicConcentrationFiringArcMult": "",
"fCombatMagicConcentrationMinCastTime": "",
"fCombatMagicConcentrationScoreDuration": "",
"fCombatMagicDefaultLongDuration": "",
"fCombatMagicDefaultMinCastTime": "",
"fCombatMagicDefaultShortDuration": "",
"fCombatMagicDisarmDistance": "",
"fCombatMagicDisarmRestrictTime": "",
"fCombatMagicDrinkPotionWaitTime": "",
"fCombatMagicDualCastChance": "",
"fCombatMagicDualCastInterruptTime": "",
"fCombatMagicImmediateAimVariance": "",
"fCombatMagicInvisibilityDistance": "",
"fCombatMagicInvisibilityMinCastTime": "",
"fCombatMagickaRegenRateMult": "",
"fCombatMagicLightMinCastTime": "",
"fCombatMagicOffensiveMinCastTime": "",
"fCombatMagicParalyzeDistance": "",
"fCombatMagicParalyzeMinCastTime": "",
"fCombatMagicParalyzeRestrictTime": "",
"fCombatMagicProjectileFiringArc": "",
"fCombatMagicReanimateDistance": "",
"fCombatMagicReanimateMinCastTime": "",
"fCombatMagicReanimateRestrictTime": "",
"fCombatMagicStaggerDistance": "",
"fCombatMagicSummonMinCastTime": "",
"fCombatMagicSummonRestrictTime": "",
"fCombatMagicTargetEffectMinCastTime": "",
"fCombatMagicWardAttackRangeDistance": "",
"fCombatMagicWardAttackReachMult": "",
"fCombatMagicWardCooldownTime": "",
"fCombatMagicWardMagickaCastLimit": "",
"fCombatMagicWardMagickaEquipLimit": "",
"fCombatMagicWardMinCastTime": "",
"fCombatMaintainOptimalDistanceMaxAngle": "",
"fCombatMaintainRangeDistanceMin": "",
"fCombatMaxHoldScore": "",
"fCombatMaximumOptimalRangeMax": "",
"fCombatMaximumOptimalRangeMid": "",
"fCombatMaximumOptimalRangeMin": "",
"fCombatMaximumProjectileRange": "",
"fCombatMaximumRange": "",
"fCombatMeleeTrackTargetDistanceMax": "",
"fCombatMeleeTrackTargetDistanceMin": "",
"fCombatMinEngageDistance": "",
"fCombatMissileImpaleDepth": "",
"fCombatMissileStickDepth": "",
"fCombatMonitorBuffsTimer": "",
"fCombatMoveToActorBufferDistance": "",
"fCombatMusicGroupThreatRatioMax": "",
"fCombatMusicGroupThreatRatioMin": "",
"fCombatMusicGroupThreatRatioTimer": "",
"fCombatMusicNearCombatInnerRadius": "",
"fCombatMusicNearCombatOuterRadius": "",
"fCombatMusicPlayerCombatStrengthCap": "",
"fCombatMusicPlayerNearStrengthMult": "",
"fCombatMusicPlayerTargetedThreatRatio": "",
"fCombatMusicStopTime": "",
"fCombatMusicUpdateTime": "",
"fCombatOffensiveBashChanceMax": "",
"fCombatOffensiveBashChanceMin": "",
"fCombatOptimalRangeMaxBufferDistance": "",
"fCombatOptimalRangeMinBufferDistance": "",
"fCombatOrbitDistance": "",
"fCombatOrbitTimeMax": "",
"fCombatOrbitTimeMin": "",
"fCombatParalyzeTacticalDuration": "",
"fCombatPathingAccelerationMult": "",
"fCombatPathingCurvedPathSmoothingMult": "",
"fCombatPathingDecelerationMult": "",
"fCombatPathingGoalRayCastPathDistance": "",
"fCombatPathingIncompletePathMinDistance": "",
"fCombatPathingLocationCenterOffsetMult": "",
"fCombatPathingLookAheadDelta": "",
"fCombatPathingNormalizedRotationSpeed": "",
"fCombatPathingRefLocationUpdateDistance": "",
"fCombatPathingRefLocationUpdateTimeDistanceMax": "",
"fCombatPathingRefLocationUpdateTimeDistanceMin": "",
"fCombatPathingRefLocationUpdateTimeMax": "",
"fCombatPathingRefLocationUpdateTimeMin": "",
"fCombatPathingRetryWaitTime": "",
"fCombatPathingRotationAccelerationMult": "",
"fCombatPathingStartRayCastPathDistance": "",
"fCombatPathingStraightPathCheckDistance": "",
"fCombatPathingStraightRayCastPathDistance": "",
"fCombatPathingUpdatePathCostMult": "",
"fCombatPerchAttackChanceMax": "",
"fCombatPerchAttackChanceMin": "",
"fCombatPerchAttackTimeMax": "",
"fCombatPerchAttackTimeMin": "",
"fCombatPerchMaxTargetAngle": "",
"fCombatPlayerBleedoutHealthDamageMult": "",
"fCombatPlayerLimbDamageMult": "",
"fCombatProjectileMaxRangeMult": "",
"fCombatProjectileMaxRangeOptimalMult": "",
"fCombatRadiusMinMult": "",
"fCombatRangedAimVariance": "",
"fCombatRangedAttackChanceLastAttackBonusTime": "",
"fCombatRangedAttackChanceLastAttackBonus": "",
"fCombatRangedAttackChanceMax": "",
"fCombatRangedAttackChanceMin": "",
"fCombatRangedAttackHoldTimeAbsoluteMin": "",
"fCombatRangedAttackHoldTimeMax": "",
"fCombatRangedAttackHoldTimeMinDistance": "",
"fCombatRangedAttackHoldTimeMin": "",
"fCombatRangedAttackMaximumHoldTime": "",
"fCombatRangedDistance": "",
"fCombatRangedMinimumRange": "",
"fCombatRangedProjectileFiringArc": "",
"fCombatRangedStandoffTimer": "",
"fCombatRelativeDamageMod": "",
"fCombatRestoreHealthPercentMax": "",
"fCombatRestoreHealthPercentMin": "",
"fCombatRestoreHealthRestrictTime": "",
"fCombatRestoreMagickaPercentMax": "",
"fCombatRestoreMagickaPercentMin": "",
"fCombatRestoreMagickaRestrictTime": "",
"fCombatRestoreStopCastThreshold": "",
"fCombatRoundAmount": "",
"fCombatSearchAreaUpdateTime": "",
"fCombatSearchCenterRadius": "",
"fCombatSearchCheckDestinationDistanceMax": "",
"fCombatSearchCheckDestinationDistanceMid": "",
"fCombatSearchCheckDestinationDistanceMin": "",
"fCombatSearchCheckDestinationTime": "",
"fCombatSearchDoorDistanceLow": "",
"fCombatSearchDoorDistance": "",
"fCombatSearchDoorSearchRadius": "",
"fCombatSearchExteriorRadiusMax": "",
"fCombatSearchExteriorRadiusMin": "",
"fCombatSearchIgnoreLocationRadius": "",
"fCombatSearchInteriorRadiusMax": "",
"fCombatSearchInteriorRadiusMin": "",
"fCombatSearchInvestigateTime": "",
"fCombatSearchLocationCheckDistance": "",
"fCombatSearchLocationCheckTime": "",
"fCombatSearchLocationInitialCheckTime": "",
"fCombatSearchLocationInvestigateDistance": "",
"fCombatSearchLocationRadius": "",
"fCombatSearchLookTime": "",
"fCombatSearchRadiusBufferDistance": "",
"fCombatSearchRadiusMemberDistance": "",
"fCombatSearchSightRadius": "",
"fCombatSearchStartWaitTime": "",
"fCombatSearchUpdateTime": "",
"fCombatSearchWanderDistance": "",
"fCombatSelectTargetSwitchUpdateTime": "",
"fCombatSelectTargetUpdateTime": "",
"fCombatShoutHeadTrackingAngleMovingMult": "",
"fCombatShoutHeadTrackingAngleMult": "",
"fCombatShoutLongRecoveryTime": "",
"fCombatShoutMaxHeadTrackingAngle": "",
"fCombatShoutReleaseTime": "",
"fCombatShoutShortRecoveryTime": "",
"fCombatSneakAttackBonusMult": "",
"fCombatSpeakAttackChance": "",
"fCombatSpeakHitChance": "",
"fCombatSpeakHitThreshold": "",
"fCombatSpeakPowerAttackChance": "",
"fCombatSpeakTauntChance": "",
"fCombatSpecialAttackChanceMax": "",
"fCombatSpecialAttackChanceMin": "",
"fCombatSplashDamageMaxSpeed": "",
"fCombatSplashDamageMinDamage": "",
"fCombatSplashDamageMinRadius": "",
"fCombatStaffTimer": "",
"fCombatStaminaRegenRateMult": "",
"fCombatStealthPointAttackedMaxValue": "",
"fCombatStealthPointDetectedEventMaxValue": "",
"fCombatStealthPointDrainMult": "",
"fCombatStealthPointMax": "",
"fCombatStealthPointRegenAlertWaitTime": "",
"fCombatStealthPointRegenAttackedWaitTime": "",
"fCombatStealthPointRegenDetectedEventWaitTime": "",
"fCombatStealthPointRegenLostWaitTime": "",
"fCombatStealthPointRegenMin": "",
"fCombatStealthPointRegenMult": "",
"fCombatStepAdvanceDistance": "",
"fCombatStrafeChanceMax": "",
"fCombatStrafeChanceMin": "",
"fCombatStrafeDistanceMax": "",
"fCombatStrafeDistanceMin": "",
"fCombatStrafeMinDistanceRadiusMult": "",
"fCombatStrengthUpdateTime": "",
"fCombatSurroundDistanceMax": "",
"fCombatSurroundDistanceMin": "",
"fCombatTargetEngagedLastSeenTime": "",
"fCombatTargetLocationAvoidNodeRadiusOffset": "",
"fCombatTargetLocationCurrentReservationDistanceMult": "",
"fCombatTargetLocationMaxDistance": "",
"fCombatTargetLocationMinDistanceMult": "",
"fCombatTargetLocationPathingRadius": "",
"fCombatTargetLocationRadiusSizeMult": "",
"fCombatTargetLocationRepositionAngleMult": "",
"fCombatTargetLocationSwimmingOffset": "",
"fCombatTargetLocationWidthMax": "",
"fCombatTargetLocationWidthMin": "",
"fCombatTargetLocationWidthSizeMult": "",
"fCombatTeammateFollowRadiusBase": "",
"fCombatTeammateFollowRadiusMin": "",
"fCombatTeammateFollowRadiusMult": "",
"fCombatThreatAnticipateTime": "",
"fCombatThreatAvoidCost": "",
"fCombatThreatBufferRadius": "",
"fCombatThreatCacheVelocityTime": "",
"fCombatThreatDangerousObjectHealth": "",
"fCombatThreatExplosiveObjectThreatTime": "",
"fCombatThreatExtrudeTime": "",
"fCombatThreatExtrudeVelocityThreshold": "",
"fCombatThreatNegativeExtrudeTime": "",
"fCombatThreatProximityExplosionAvoidTime": "",
"fCombatThreatRatioUpdateTime": "",
"fCombatThreatSignificantScore": "",
"fCombatThreatTimedExplosionLength": "",
"fCombatThreatUpdateTimeMax": "",
"fCombatThreatUpdateTimeMin": "",
"fCombatThreatViewCone": "",
"fCombatUnarmedCritDamageMult": "",
"fCombatUnreachableTargetCheckTime": "",
"fCombatVulnerabilityMod": "",
"fCombatYieldRetryTime": "",
"fCombatYieldTime": "",
"fCommentOnPlayerActionsTimer": "",
"fCommentOnPlayerKnockingThings": "",
"fConcussionTimer": "",
"fConeProjectileEnvironmentDistance": "",
"fConeProjectileEnvironmentTimer": "",
"fConeProjectileForceBase": "",
"fConeProjectileForceMultAngular": "",
"fConeProjectileForceMultLinear": "",
"fConeProjectileForceMult": "",
"fConeProjectileWaterScaleMult": "",
"fCoveredAdvanceMinAdvanceDistanceMax": "",
"fCoveredAdvanceMinAdvanceDistanceMin": "",
"fCoverEvaluationLastSeenExpireTime": "",
"fCoverFiredProjectileExpireTime": "",
"fCoverFiringReloadClipPercent": "",
"fCoverWaitReloadClipPercent": "",
"fCreatureDefaultTurningSpeed": "",
"fCreditsScrollSpeed": "",
"fCrimeAlarmRespMult": "",
"fCrimeDispAttack": "",
"fCrimeDispMurder": "",
"fCrimeDispPersonal": "",
"fCrimeDispPickpocket": "",
"fCrimeDispSteal": "",
"fCrimeDispTresspass": "",
"fCrimeFavorMult": "",
"fCrimeGoldSkillPenaltyMult": "",
"fCrimeGoldSteal": "",
"fCrimePersonalRegardMult": "",
"fCrimeRegardMult": "",
"fCrimeSoundBase": "",
"fCrimeSoundMult": "",
"fCrimeWitnessRegardMult": "",
"fDamageArmConditionBase": "",
"fDamageArmConditionMult": "",
"fDamagedAVRegenDelay": "",
"fDamagedHealthRegenDelay": "",
"fDamagedMagickaRegenDelay": "",
"fDamagedStaminaRegenDelay": "",
"fDamageGunWeapCondBase": "",
"fDamageGunWeapCondMult": "",
"fDamageMeleeWeapCondBase": "",
"fDamageMeleeWeapCondMult": "",
"fDamagePCSkillMax": "",
"fDamagePCSkillMin": "",
"fDamageSkillMax": "",
"fDamageSkillMin": "",
"fDamageSneakAttackMult": "",
"fDamageStrengthBase": "",
"fDamageStrengthMult": "",
"fDamageToArmorPercentage": "",
"fDamageToWeaponEnergyMult": "",
"fDamageToWeaponGunMult": "",
"fDamageToWeaponLauncherMult": "",
"fDamageToWeaponMeleeMult": "",
"fDamageUnarmedPenalty": "",
"fDamageWeaponMult": "",
"fDangerousObjectExplosionDamage": "",
"fDangerousObjectExplosionRadius": "",
"fDangerousProjectileExplosionDamage": "",
"fDangerousProjectileExplosionRadius": "",
"fDaytimeColorExtension": "",
"fDeadReactionDistance": "",
"fDeathForceDamageMax": "",
"fDeathForceDamageMin": "",
"fDeathForceForceMax": "",
"fDeathForceForceMin": "",
"fDeathForceMassBase": "",
"fDeathForceMassMult": "",
"fDeathForceRangedDamageMax": "",
"fDeathForceRangedDamageMin": "",
"fDeathForceRangedForceMax": "",
"fDeathForceRangedForceMin": "",
"fDeathForceSpellImpactMult": "",
"fDeathSoundMaxDistance": "",
"fDebrisFadeTime": "",
"fDecapitateBloodTime": "",
"fDefaultAngleTolerance": "",
"fDefaultBowSpeedBonus": "",
"fDemandBase": "",
"fDemandMult": "",
"fDetectEventDistanceNPC": "",
"fDetectEventDistancePlayer": "",
"fDetectEventDistanceVeryLoudMult": "",
"fDetectEventSneakDistanceVeryLoud": "",
"fDetectionActionTimer": "",
"fDetectionCombatNonTargetDistanceMult": "",
"fDetectionCommentTimer": "",
"fDetectionEventExpireTime": "",
"fDetectionLargeActorSizeMult": "",
"fDetectionLOSDistanceAngle": "",
"fDetectionLOSDistanceMultExterior": "",
"fDetectionLOSDistanceMultInterior": "",
"fDetectionNightEyeBonus": "",
"fDetectionSneakLightMod": "",
"fDetectionStateExpireTime": "",
"fDetectionUpdateTimeMaxComplex": "",
"fDetectionUpdateTimeMax": "",
"fDetectionUpdateTimeMinComplex": "",
"fDetectionUpdateTimeMin": "",
"fDetectionViewCone": "",
"fDetectProjectileDistanceNPC": "",
"fDetectProjectileDistancePlayer": "",
"fDialogFocalDepthRange": "",
"fDialogFocalDepthStrength": "",
"fDialogSpeechDelaySeconds": "",
"fDialogZoomInSeconds": "",
"fDialogZoomOutSeconds": "",
"fDifficultyDamageMultiplier": "",
"fDifficultyDefaultValue": "",
"fDifficultyMaxValue": "",
"fDifficultyMinValue": "",
"fDiffMultHPByPCE": "",
"fDiffMultHPByPCH": "",
"fDiffMultHPByPCL": "",
"fDiffMultHPByPCN": "",
"fDiffMultHPByPCVE": "",
"fDiffMultHPByPCVH": "",
"fDiffMultHPToPCE": "",
"fDiffMultHPToPCH": "",
"fDiffMultHPToPCL": "",
"fDiffMultHPToPCN": "",
"fDiffMultHPToPCVE": "",
"fDiffMultHPToPCVH": "",
"fDiffMultXPH": "",
"fDiffMultXPVH": "",
"fDisarmedPickupWeaponDistanceMult": "",
"fDisenchantSkillUse": "",
"fDistanceAutomaticallyActivateDoor": "",
"fDistanceExteriorReactCombat": "",
"fDistanceFadeActorAutoLoadDoor": "",
"fDistanceInteriorReactCombat": "",
"fDistanceProjectileExplosionDetection": "",
"fDistancetoPlayerforConversations": "",
"fDOFDistanceMult": "",
"fDrinkRepeatRate": "",
"fDyingTimer": "",
"fEmbeddedWeaponSwitchChance": "",
"fEmbeddedWeaponSwitchTime": "",
"fEnchantingCostExponent": "",
"fEnchantingSkillCostBase": "",
"fEnchantingSkillCostMult": "",
"fEnchantingSkillCostScale": "",
"fEnchantingSkillFactor": "",
"fEnchantmentEffectPointsMult": "",
"fEnchantmentGoldMult": "",
"fEnchantmentPointsMult": "",
"fEnemyHealthBarTimer": "",
"fEssentialDeathTime": "",
"fEssentialDownCombatHealthRegenMult": "",
"fEssentialHealthPercentReGain": "",
"fEssentialNonCombatHealRateBonus": "",
"fEssentialNPCMinimumHealth": "",
"fEvaluatePackageTimer": "",
"fEvaluateProcedureTimer": "",
"fExplodeLimbRemovalDelayVATS": "",
"fExplodeLimbRemovalDelay": "",
"fExplosionForceClutterUpBias": "",
"fExplosionForceKnockdownMinimum": "",
"fExplosionForceMultAngular": "",
"fExplosionForceMultLinear": "",
"fExplosionImageSpaceSwapPower": "",
"fExplosionKnockStateExplodeDownTime": "",
"fExplosionLOSBufferDistance": "",
"fExplosionLOSBuffer": "",
"fExplosionMaxImpulse": "",
"fExplosionSourceRefMult": "",
"fExplosionSplashRadius": "",
"fExplosionWaterRadiusRatio": "",
"fExplosiveProjectileBlockedResetTime": "",
"fExplosiveProjectileBlockedWaitTime": "",
"fExpressionChangePerSec": "",
"fExpressionStrengthAdd": "",
"fEyeHeadingMaxOffsetEmotionAngry": "",
"fEyeHeadingMaxOffsetEmotionFear": "",
"fEyeHeadingMaxOffsetEmotionHappy": "",
"fEyeHeadingMaxOffsetEmotionNeutral": "",
"fEyeHeadingMaxOffsetEmotionSad": "",
"fEyeHeadingMinOffsetEmotionAngry": "",
"fEyeHeadingMinOffsetEmotionFear": "",
"fEyeHeadingMinOffsetEmotionHappy": "",
"fEyeHeadingMinOffsetEmotionNeutral": "",
"fEyeHeadingMinOffsetEmotionSad": "",
"fEyePitchMaxOffsetEmotionAngry": "",
"fEyePitchMaxOffsetEmotionFear": "",
"fEyePitchMaxOffsetEmotionHappy": "",
"fEyePitchMaxOffsetEmotionNeutral": "",
"fEyePitchMaxOffsetEmotionSad": "",
"fEyePitchMinOffsetEmotionAngry": "",
"fEyePitchMinOffsetEmotionFear": "",
"fEyePitchMinOffsetEmotionHappy": "",
"fEyePitchMinOffsetEmotionNeutral": "",
"fEyePitchMinOffsetEmotionSad": "",
"fFallLegDamageMult": "",
"fFastTravelSpeedMult": "",
"fFastWalkInterpolationBetweenWalkAndRun": "",
"fFavorCostActivator": "",
"fFavorCostAttackCrimeMult": "",
"fFavorCostAttack": "",
"fFavorCostLoadDoor": "",
"fFavorCostNonLoadDoor": "",
"fFavorCostOwnedDoorMult": "",
"fFavorCostStealContainerCrime": "",
"fFavorCostStealContainerMult": "",
"fFavorCostStealObjectMult": "",
"fFavorCostTakeObject": "",
"fFavorCostUnlockContainer": "",
"fFavorCostUnlockDoor": "",
"fFavorEventStopDistance": "",
"fFavorEventTriggerDistance": "",
"fFavorRequestPickDistance": "",
"fFavorRequestRadius": "",
"fFavorRequestWaitTimer": "",
"fFleeDistanceExterior": "",
"fFleeDistanceInterior": "",
"fFleeDoneDistanceExterior": "",
"fFleeDoneDistanceInterior": "",
"fFleeIsSafeTimer": "",
"fFloatQuestMarkerFloatHeight": "",
"fFloatQuestMarkerMaxDistance": "",
"fFloatQuestMarkerMinDistance": "",
"fFlyingActorDefaultTurningSpeed": "",
"fFollowerSpacingAtDoors": "",
"fFollowExtraCatchUpSpeedMult": "",
"fFollowMatchSpeedZoneWidth": "",
"fFollowRunMaxSpeedupMultiplier": "",
"fFollowRunMinSlowdownMultiplier": "",
"fFollowSlowdownZoneWidth": "",
"fFollowSpaceBetweenFollowers": "",
"fFollowStartSprintDistance": "",
"fFollowStopZoneMinMult": "",
"fFollowWalkMaxSpeedupMultiplier": "",
"fFollowWalkMinSlowdownMultiplier": "",
"fFollowWalkZoneMult": "",
"fFriendHitTimer": "",
"fFriendMinimumLastHitTime": "",
"fFurnitureMarkerAngleTolerance": "",
"fFurnitureScaleAnimDurationNPC": "",
"fFurnitureScaleAnimDurationPlayer": "",
"fGameplayImpulseMinMass": "",
"fGameplayImpulseMultBiped": "",
"fGameplayImpulseMultClutter": "",
"fGameplayImpulseMultDebrisLarge": "",
"fGameplayImpulseMultProp": "",
"fGameplayImpulseMultTrap": "",
"fGameplayImpulseScale": "",
"fGameplayiSpeakingEmotionMaxDeltaChange": "",
"fGameplayiSpeakingEmotionMinDeltaChange": "",
"fGameplaySpeakingEmotionMaxChangeValue": "",
"fGameplaySpeakingEmotionMinChangeValue": "",
"fGameplayVoiceFilePadding": "",
"fGetHitPainMult": "",
"fGrabMaxWeightRunning": "",
"fGrabMaxWeightWalking": "",
"fGrenadeAgeMax": "",
"fGrenadeFriction": "",
"fGrenadeHighArcSpeedPercentage": "",
"fGrenadeRestitution": "",
"fGrenadeThrowHitFractionThreshold": "",
"fGuardPackageAttackRadiusMult": "",
"fGunDecalCameraDistance": "",
"fGunParticleCameraDistance": "",
"fGunReferenceSkill": "",
"fGunShellCameraDistance": "",
"fGunShellDirectionRandomize": "",
"fGunShellEjectSpeed": "",
"fGunShellLifetime": "",
"fGunShellRotateRandomize": "",
"fGunShellRotateSpeed": "",
"fGunSpreadArmBase": "",
"fGunSpreadArmMult": "",
"fGunSpreadCondBase": "",
"fGunSpreadCondMult": "",
"fGunSpreadCrouchBase": "",
"fGunSpreadCrouchMult": "",
"fGunSpreadDriftBase": "",
"fGunSpreadDriftMult": "",
"fGunSpreadHeadBase": "",
"fGunSpreadHeadMult": "",
"fGunSpreadIronSightsBase": "",
"fGunSpreadIronSightsMult": "",
"fGunSpreadNPCArmBase": "",
"fGunSpreadNPCArmMult": "",
"fGunSpreadRunBase": "",
"fGunSpreadRunMult": "",
"fGunSpreadSkillBase": "",
"fGunSpreadSkillMult": "",
"fGunSpreadWalkBase": "",
"fGunSpreadWalkMult": "",
"fHandDamageSkillBase": "",
"fHandDamageSkillMult": "",
"fHandDamageStrengthBase": "",
"fHandDamageStrengthMult": "",
"fHandHealthMax": "",
"fHandHealthMin": "",
"fHandReachDefault": "",
"fHazardDropMaxDistance": "",
"fHazardMaxWaitTime": "",
"fHazardSpacingMult": "",
"fHeadingMarkerAngleTolerance": "",
"fHeadTrackSpeedMaxAngle": "",
"fHeadTrackSpeedMax": "",
"fHeadTrackSpeedMinAngle": "",
"fHeadTrackSpeedMin": "",
"fHealthRegenDelayMax": "",
"fHitCasterSizeLarge": "",
"fHitCasterSizeSmall": "",
"fHorseMountOffsetX": "",
"fHorseMountOffsetY": "",
"fHostileActorExteriorDistance": "",
"fHostileActorInteriorDistance": "",
"fHostileFlyingActorExteriorDistance": "",
"fHUDCompassLocationMaxDist": "",
"fIdleChatterCommentTimerMax": "",
"fIdleChatterCommentTimer": "",
"fIdleMarkerAngleTolerance": "",
"fImpactShaderMaxDistance": "",
"fImpactShaderMaxMagnitude": "",
"fImpactShaderMinMagnitude": "",
"fIntimidateConfidenceMultAverage": "",
"fIntimidateConfidenceMultBrave": "",
"fIntimidateConfidenceMultCautious": "",
"fIntimidateConfidenceMultCowardly": "",
"fIntimidateConfidenceMultFoolhardy": "",
"fIntimidateSpeechcraftCurve": "",
"fIronSightsDOFDistance": "",
"fIronSightsDOFRange": "",
"fIronSightsDOFStrengthCap": "",
"fIronSightsDOFSwitchSeconds": "",
"fIronSightsFOVTimeChange": "",
"fIronSightsGunMotionBlur": "",
"fIronSightsMotionBlur": "",
"fItemPointsMult": "",
"fItemRepairCostMult": "",
"fJogInterpolationBetweenWalkAndRun": "",
"fJumpDoubleMult": "",
"fJumpFallHeightExponentNPC": "",
"fJumpFallHeightExponent": "",
"fJumpFallHeightMinNPC": "",
"fJumpFallHeightMin": "",
"fJumpFallHeightMultNPC": "",
"fJumpFallHeightMult": "",
"fJumpFallRiderMult": "",
"fJumpFallSkillBase": "",
"fJumpFallSkillMult": "",
"fJumpFallVelocityMin": "",
"fJumpHeightMin": "",
"fJumpMoveBase": "",
"fJumpMoveMult": "",
"fJumpSwimmingMult": "",
"fKarmaModKillingEvilActor": "",
"fKarmaModMurderingNonEvilCreature": "",
"fKarmaModMurderingNonEvilNPC": "",
"fKarmaModStealing": "",
"fKillCamBaseOdds": "",
"fKillCamLevelBias": "",
"fKillCamLevelFactor": "",
"fKillCamLevelMaxBias": "",
"fKillMoveMaxDuration": "",
"fKillWitnessesTimerSetting": "",
"fKnockbackAgilBase": "",
"fKnockbackAgilMult": "",
"fKnockbackDamageBase": "",
"fKnockbackDamageMult": "",
"fKnockbackForceMax": "",
"fKnockbackTime": "",
"fKnockdownAgilBase": "",
"fKnockdownAgilMult": "",
"fKnockdownBaseHealthThreshold": "",
"fKnockdownChance": "",
"fKnockdownCurrentHealthThreshold": "",
"fKnockdownDamageBase": "",
"fKnockdownDamageMult": "",
"fLargeProjectilePickBufferSize": "",
"fLargeProjectileSize": "",
"fLevelUpCarryWeightMod": "",
"fLightRecalcTimerPlayer": "",
"fLightRecalcTimer": "",
"fLoadingWheelScale": "",
"fLockLevelBase": "",
"fLockLevelMult": "",
"fLockpickBreakAdept": "",
"fLockpickBreakApprentice": "",
"fLockPickBreakBase": "",
"fLockpickBreakExpert": "",
"fLockpickBreakMaster": "",
"fLockPickBreakMult": "",
"fLockpickBreakNovice": "",
"fLockpickBreakSkillBase": "",
"fLockpickBreakSkillMult": "",
"fLockpickBrokenPicksMult": "",
"fLockPickQualityBase": "",
"fLockPickQualityMult": "",
"fLockpickSkillPartialPickBase": "",
"fLockpickSkillPartialPickMult": "",
"fLockpickSkillSweetSpotBase": "",
"fLockpickSkillSweetSpotMult": "",
"fLockSkillBase": "",
"fLockSkillMult": "",
"fLockTrapGoOffBase": "",
"fLockTrapGoOffMult": "",
"fLookDownDisableBlinkingAmt": "",
"fLowHealthTutorialPercentage": "",
"fLowLevelNPCBaseHealthMult": "",
"fLowMagickaTutorialPercentage": "",
"fLowStaminaTutorialPercentage": "",
"fMagicAbsorbDistanceReachMult": "",
"fMagicAbsorbVisualTimer": "",
"fMagicAccumulatingModifierEffectHoldDuration": "",
"fMagicAreaBaseCostMult": "",
"fMagicAreaScaleMax": "",
"fMagicAreaScaleMin": "",
"fMagicAreaScale": "",
"fMagicBarrierDepth": "",
"fMagicBarrierHeight": "",
"fMagicBarrierSpacing": "",
"fMagicBoltDuration": "",
"fMagicBoltSegmentLength": "",
"fMagicCasterPCSkillCostBase": "",
"fMagicCasterPCSkillCostMult": "",
"fMagicCasterSkillCostBase": "",
"fMagicCasterSkillCostMult": "",
"fMagicCEEnchantMagOffset": "",
"fMagicChainExplosionEffectivenessDelta": "",
"fMagicCloudAreaMin": "",
"fMagicCloudDurationMin": "",
"fMagicCloudFindTargetTime": "",
"fMagicCloudLifeScale": "",
"fMagicCloudSizeScale": "",
"fMagicCloudSlowdownRate": "",
"fMagicCloudSpeedBase": "",
"fMagicCloudSpeedScale": "",
"fMagicCostScale": "",
"fMagicDefaultAccumulatingModifierEffectRate": "",
"fMagicDefaultTouchDistance": "",
"fMagicDiseaseTransferBase": "",
"fMagicDiseaseTransferMult": "",
"fMagicDispelMagnitudeMult": "",
"fMagicDualCastingCostBase": "",
"fMagicDualCastingCostMult": "",
"fMagicDualCastingEffectivenessBase": "",
"fMagicDualCastingEffectivenessMult": "",
"fMagicDualCastingTimeBase": "",
"fMagicDualCastingTimeMult": "",
"fMagicDurMagBaseCostMult": "",
"fMagicEnchantmentChargeBase": "",
"fMagicEnchantmentChargeMult": "",
"fMagicEnchantmentDrainBase": "",
"fMagicEnchantmentDrainMult": "",
"fMagicExplosionAgilityMult": "",
"fMagicExplosionClutterMult": "",
"fMagicExplosionIncorporealMult": "",
"fMagicExplosionIncorporealTime": "",
"fMagicExplosionPowerBase": "",
"fMagicExplosionPowerMax": "",
"fMagicExplosionPowerMin": "",
"fMagicExplosionPowerMult": "",
"fMagicGuideSpacing": "",
"fMagickaRegenDelayMax": "",
"fMagickaReturnBase": "",
"fMagickaReturnMult": "",
"fMagicLightForwardOffset": "",
"fMagicLightHeightOffset": "",
"fMagicLightRadiusBase": "",
"fMagicLightSideOffset": "",
"fMagicNightEyeAmbient": "",
"fMagicPCSkillCostScale": "",
"fMagicPlayerMinimumInvisibility": "",
"fMagicPostDrawCastDelay": "",
"fMagicProjectileMaxDistance": "",
"fMagicRangeTargetCostMult": "",
"fMagicResistActorSkillBase": "",
"fMagicResistActorSkillMult": "",
"fMagicResistTargetWillpowerBase": "",
"fMagicResistTargetWillpowerMult": "",
"fMagicSkillCostScale": "",
"fMagicSummonMaxAppearTime": "",
"fMagicTelekinesiDistanceMult": "",
"fMagicTelekinesisBaseDistance": "",
"fMagicTelekinesisComplexMaxForce": "",
"fMagicTelekinesisComplexObjectDamping": "",
"fMagicTelekinesisComplexSpringDamping": "",
"fMagicTelekinesisComplexSpringElasticity": "",
"fMagicTelekinesisDamageBase": "",
"fMagicTelekinesisDamageMult": "",
"fMagicTelekinesisDistanceMin": "",
"fMagicTelekinesisDualCastDamageMult": "",
"fMagicTelekinesisDualCastThrowMult": "",
"fMagicTelekinesisLiftPowerMult": "",
"fMagicTelekinesisMaxForce": "",
"fMagicTelekinesisMoveAccelerate": "",
"fMagicTelekinesisMoveBase": "",
"fMagicTelekinesisMoveMax": "",
"fMagicTelekinesisObjectDamping": "",
"fMagicTelekinesisSpringDamping": "",
"fMagicTelekinesisSpringElasticity": "",
"fMagicTelekinesisThrowAccelerate": "",
"fMagicTelekinesisThrowMax": "",
"fMagicTelekinesisThrow": "",
"fMagicTrackingLimitComplex": "",
"fMagicTrackingLimit": "",
"fMagicTrackingMultBall": "",
"fMagicTrackingMultBolt": "",
"fMagicTrackingMultFog": "",
"fMagicUnitsPerFoot": "",
"fMagicVACNoPartTargetedMult": "",
"fMagicVACPartTargetedMult": "",
"fMagicWardPowerMaxBase": "",
"fMagicWardPowerMaxMult": "",
"fMapMarkerMaxPercentSize": "",
"fMapMarkerMinFadeAlpha": "",
"fMapMarkerMinPercentSize": "",
"fMapQuestMarkerMaxPercentSize": "",
"fMapQuestMarkerMinFadeAlpha": "",
"fMapQuestMarkerMinPercentSize": "",
"fMasserAngleFadeEnd": "",
"fMasserAngleFadeStart": "",
"fMasserAngleShadowEarlyFade": "",
"fMasserSpeed": "",
"fMasserZOffset": "",
"fMaxArmorRating": "",
"fMaximumWind": "",
"fMaxSandboxRescanSeconds": "",
"fMaxSellMult": "",
"fMeleeMovementRestrictionsUpdateTime": "",
"fMeleeSweepViewAngleMult": "",
"fMinBuyMult": "",
"fMinDistanceUseHorse": "",
"fMineAgeMax": "",
"fMineExteriorRadiusMult": "",
"fMinesBlinkFast": "",
"fMinesBlinkMax": "",
"fMinesBlinkSlow": "",
"fMinesDelayMin": "",
"fMinSandboxRescanSeconds": "",
"fModelReferenceEffectMaxWaitTime": "",
"fModifiedTargetAttackRange": "",
"fMotionBlur": "",
"fMountedMaxLookingDown": "",
"fMoveCharRunBase": "",
"fMoveCharWalkBase": "",
"fMoveEncumEffectNoWeapon": "",
"fMoveEncumEffect": "",
"fMoveFlyRunMult": "",
"fMoveFlyWalkMult": "",
"fMovementNearTargetAvoidCost": "",
"fMovementNearTargetAvoidRadius": "",
"fMovementTargetAvoidCost": "",
"fMovementTargetAvoidRadiusMult": "",
"fMovementTargetAvoidRadius": "",
"fMoveSprintMult": "",
"fMoveSwimMult": "",
"fMoveWeightMax": "",
"fMoveWeightMin": "",
"fNPCAttributeHealthMult": "",
"fNPCBaseMagickaMult": "",
"fNPCHealthLevelBonus": "",
"fObjectHitH2HReach": "",
"fObjectHitTwoHandReach": "",
"fObjectHitWeaponReach": "",
"fObjectMotionBlur": "",
"fObjectWeightPickupDetectionMult": "",
"fOutOfBreathStaminaRegenDelay": "",
"fPainDelay": "",
"fPartialPickAverage": "",
"fPartialPickEasy": "",
"fPartialPickHard": "",
"fPartialPickVeryEasy": "",
"fPartialPickVeryHard": "",
"fPCBaseHealthMult": "",
"fPCBaseMagickaMult": "",
"fPCHealthLevelBonus": "",
"fPerceptionMult": "",
"fPerkHeavyArmorExpertSpeedMult": "",
"fPerkHeavyArmorJourneymanDamageMult": "",
"fPerkHeavyArmorMasterSpeedMult": "",
"fPerkHeavyArmorNoviceDamageMult": "",
"fPerkHeavyArmorSinkGravityMult": "",
"fPerkLightArmorExpertSpeedMult": "",
"fPerkLightArmorJourneymanDamageMult": "",
"fPerkLightArmorMasterRatingMult": "",
"fPerkLightArmorNoviceDamageMult": "",
"fPersAdmireAggr": "",
"fPersAdmireConf": "",
"fPersAdmireEner": "",
"fPersAdmireIntel": "",
"fPersAdmirePers": "",
"fPersAdmireResp": "",
"fPersAdmireStre": "",
"fPersAdmireWillp": "",
"fPersBoastAggr": "",
"fPersBoastConf": "",
"fPersBoastEner": "",
"fPersBoastIntel": "",
"fPersBoastPers": "",
"fPersBoastResp": "",
"fPersBoastWillp": "",
"fPersBullyAggr": "",
"fPersBullyConf": "",
"fPersBullyEner": "",
"fPersBullyIntel": "",
"fPersBullyPers": "",
"fPersBullyResp": "",
"fPersBullyStre": "",
"fPersBullyWillp": "",
"fPersJokeAggr": "",
"fPersJokeConf": "",
"fPersJokeEner": "",
"fPersJokeIntel": "",
"fPersJokePers": "",
"fPersJokeResp": "",
"fPersJokeStre": "",
"fPersJokeWillp": "",
"fPersuasionAccuracyMaxDisposition": "",
"fPersuasionAccuracyMaxSelect": "",
"fPersuasionAccuracyMinDispostion": "",
"fPersuasionAccuracyMinSelect": "",
"fPersuasionBaseValueMaxDisposition": "",
"fPersuasionBaseValueMaxSelect": "",
"fPersuasionBaseValueMinDispostion": "",
"fPersuasionBaseValueMinSelect": "",
"fPersuasionBaseValueShape": "",
"fPersuasionMaxDisposition": "",
"fPersuasionMaxInput": "",
"fPersuasionMaxSelect": "",
"fPersuasionMinDispostion": "",
"fPersuasionMinInput": "",
"fPersuasionMinPercentCircle": "",
"fPersuasionMinSelect": "",
"fPersuasionShape": "",
"fPhysicsDamage1Damage": "",
"fPhysicsDamage1Mass": "",
"fPhysicsDamage2Damage": "",
"fPhysicsDamage2Mass": "",
"fPhysicsDamage3Damage": "",
"fPhysicsDamage3Mass": "",
"fPhysicsDamageSpeedBase": "",
"fPhysicsDamageSpeedMin": "",
"fPhysicsDamageSpeedMult": "",
"fPickLevelBase": "",
"fPickLevelMult": "",
"fPickNumBase": "",
"fPickNumMult": "",
"fPickPocketActorSkillBase": "",
"fPickPocketActorSkillMult": "",
"fPickPocketAmountBase": "",
"fPickPocketAmountMult": "",
"fPickPocketDetected": "",
"fPickPocketMaxChance": "",
"fPickPocketMinChance": "",
"fPickpocketSkillUsesCurve": "",
"fPickPocketTargetSkillBase": "",
"fPickPocketTargetSkillMult": "",
"fPickPocketWeightBase": "",
"fPickPocketWeightMult": "",
"fPickSpring1": "",
"fPickSpring2": "",
"fPickSpring3": "",
"fPickSpring4": "",
"fPickSpring5": "",
"fPickupItemDistanceFudge": "",
"fPickUpWeaponDelay": "",
"fPickupWeaponDistanceMinMaxDPSMult": "",
"fPickupWeaponMeleeDistanceMax": "",
"fPickupWeaponMeleeDistanceMin": "",
"fPickupWeaponMeleeWeaponDPSMult": "",
"fPickupWeaponMinDPSImprovementPercent": "",
"fPickupWeaponRangedDistanceMax": "",
"fPickupWeaponRangedDistanceMin": "",
"fPickupWeaponRangedMeleeDPSRatioThreshold": "",
"fPickupWeaponTargetUnreachableDistanceMult": "",
"fPickupWeaponUnarmedDistanceMax": "",
"fPickupWeaponUnarmedDistanceMin": "",
"fPlayerDeathReloadTime": "",
"fPlayerDetectActorValue": "",
"fPlayerDetectionSneakBase": "",
"fPlayerDetectionSneakMult": "",
"fPlayerDropDistance": "",
"fPlayerHealthHeartbeatFast": "",
"fPlayerHealthHeartbeatSlow": "",
"fPlayerMaxResistance": "",
"fPlayerTargetCombatDistance": "",
"fPlayerTeleportFadeSeconds": "",
"fPotionGoldValueMult": "",
"fPotionMortPestleMult": "",
"fPotionT1AleDurMult": "",
"fPotionT1AleMagMult": "",
"fPotionT1CalDurMult": "",
"fPotionT1CalMagMult": "",
"fPotionT1MagMult": "",
"fPotionT1RetDurMult": "",
"fPotionT1RetMagMult": "",
"fPotionT2AleDurMult": "",
"fPotionT2CalDurMult": "",
"fPotionT2RetDurMult": "",
"fPotionT3AleMagMult": "",
"fPotionT3CalMagMult": "",
"fPotionT3RetMagMult": "",
"fPowerAttackCoolDownTime": "",
"fPowerAttackDefaultBonus": "",
"fPowerAttackStaminaPenalty": "",
"fPrecipWindMult": "",
"fProjectileCollisionImpulseScale": "",
"fProjectileDefaultTracerRange": "",
"fProjectileDeflectionTime": "",
"fProjectileInventoryGrenadeFreakoutTime": "",
"fProjectileInventoryGrenadeTimer": "",
"fProjectileKnockMinMass": "",
"fProjectileKnockMultBiped": "",
"fProjectileKnockMultClutter": "",
"fProjectileKnockMultProp": "",
"fProjectileKnockMultTrap": "",
"fProjectileMaxDistance": "",
"fProjectileReorientTracerMin": "",
"fQuestCinematicCharacterFadeInDelay": "",
"fQuestCinematicCharacterFadeIn": "",
"fQuestCinematicCharacterFadeOut": "",
"fQuestCinematicCharacterRemain": "",
"fQuestCinematicObjectiveFadeInDelay": "",
"fQuestCinematicObjectiveFadeIn": "",
"fQuestCinematicObjectiveFadeOut": "",
"fQuestCinematicObjectivePauseTime": "",
"fQuestCinematicObjectiveScrollTime": "",
"fRandomSceneAgainMaxTime": "",
"fRandomSceneAgainMinTime": "",
"fRechargeGoldMult": "",
"fReEquipArmorTime": "",
"fReflectedAbsorbChanceReduction": "",
"fRelationshipBase": "",
"fRelationshipMult": "",
"fRemoteCombatMissedAttack": "",
"fRemoveExcessComplexDeadTime": "",
"fRemoveExcessDeadTime": "",
"fRepairMax": "",
"fRepairMin": "",
"fRepairScavengeMult": "",
"fRepairSkillBase": "",
"fRepairSkillMax": "",
"fReservationExpirationSeconds": "",
"fResistArrestTimer": "",
"fRockitDamageBonusWeightMin": "",
"fRockitDamageBonusWeightMult": "",
"fRoomLightingTransitionDuration": "",
"fRumbleBlockStrength": "",
"fRumbleBlockTime": "",
"fRumbleHitBlockedStrength": "",
"fRumbleHitBlockedTime": "",
"fRumbleHitStrength": "",
"fRumbleHitTime": "",
"fRumblePainStrength": "",
"fRumblePainTime": "",
"fRumbleShakeRadiusMult": "",
"fRumbleShakeTimeMult": "",
"fRumbleStruckStrength": "",
"fRumbleStruckTime": "",
"fSandboxBreakfastMax": "",
"fSandboxBreakfastMin": "",
"fSandboxCylinderBottom": "",
"fSandboxCylinderTop": "",
"fSandBoxDelayEvalSeconds": "",
"fSandboxDinnerMax": "",
"fSandboxDinnerMin": "",
"fSandboxDurationBase": "",
"fSandboxDurationMultEatSitting": "",
"fSandboxDurationMultEatStanding": "",
"fSandboxDurationMultFurniture": "",
"fSandboxDurationMultIdleMarker": "",
"fSandboxDurationMultSitting": "",
"fSandboxDurationMultSleeping": "",
"fSandboxDurationMultWandering": "",
"fSandboxDurationRangeMult": "",
"fSandboxEnergyMultEatSitting": "",
"fSandboxEnergyMultEatStanding": "",
"fSandboxEnergyMultFurniture": "",
"fSandboxEnergyMultIdleMarker": "",
"fSandboxEnergyMultSitting": "",
"fSandboxEnergyMultSleeping": "",
"fSandboxEnergyMultWandering": "",
"fSandboxEnergyMult": "",
"fSandBoxExtraDialogueRange": "",
"fSandBoxInterMarkerMinDist": "",
"fSandboxLunchMax": "",
"fSandboxLunchMin": "",
"fSandboxMealDurationMax": "",
"fSandboxMealDurationMin": "",
"fSandBoxRadiusHysteresis": "",
"fSandBoxSearchRadius": "",
"fSandboxSleepDurationMax": "",
"fSandboxSleepDurationMin": "",
"fSandboxSleepStartMax": "",
"fSandboxSleepStartMin": "",
"fSayOncePerDayInfoTimer": "",
"fScrollCostMult": "",
"fSecondsBetweenWindowUpdate": "",
"fSecundaAngleFadeEnd": "",
"fSecundaAngleFadeStart": "",
"fSecundaAngleShadowEarlyFade": "",
"fSecundaSpeed": "",
"fSecundaZOffset": "",
"fShieldBaseFactor": "",
"fShieldBashMax": "",
"fShieldBashMin": "",
"fShieldBashPCMax": "",
"fShieldBashPCMin": "",
"fShieldBashSkillUseBase": "",
"fShieldBashSkillUseMult": "",
"fShieldScalingFactor": "",
"fShockBoltGrowWidth": "",
"fShockBoltsLength": "",
"fShockBoltSmallWidth": "",
"fShockBoltsRadiusStrength": "",
"fShockBoltsRadius": "",
"fShockBranchBoltsRadiusStrength": "",
"fShockBranchBoltsRadius": "",
"fShockBranchLifetime": "",
"fShockBranchSegmentLength": "",
"fShockBranchSegmentVariance": "",
"fShockCastVOffset": "",
"fShockCoreColorB": "",
"fShockCoreColorG": "",
"fShockCoreColorR": "",
"fShockGlowColorB": "",
"fShockGlowColorG": "",
"fShockGlowColorR": "",
"fShockSegmentLength": "",
"fShockSegmentVariance": "",
"fShockSubSegmentVariance": "",
"fShoutTime1": "",
"fShoutTime2": "",
"fShoutTimeout": "",
"fSittingMaxLookingDown": "",
"fSkillUsageLockPickAverage": "",
"fSkillUsageLockPickBroken": "",
"fSkillUsageLockPickEasy": "",
"fSkillUsageLockPickHard": "",
"fSkillUsageLockPickVeryEasy": "",
"fSkillUsageLockPickVeryHard": "",
"fSkillUsageRechargeMult": "",
"fSkillUsageSneakHidden": "",
"fSkillUsageSneakPerSecond": "",
"fSkillUseCurve": "",
"fSmallBumpSpeed": "",
"fSmithingArmorMax": "",
"fSmithingConditionFactor": "",
"fSmithingWeaponMax": "",
"fSneakActionMult": "",
"fSneakAlertMod": "",
"fSneakAmbushNonTargetMod": "",
"fSneakAmbushTargetMod": "",
"fSneakAttackSkillUsageMelee": "",
"fSneakAttackSkillUsageRanged": "",
"fSneakCombatMod": "",
"fSneakDetectionSizeLarge": "",
"fSneakDetectionSizeNormal": "",
"fSneakDetectionSizeSmall": "",
"fSneakDetectionSizeVeryLarge": "",
"fSneakDistanceAttenuationExponent": "",
"fSneakEquippedWeightBase": "",
"fSneakEquippedWeightMult": "",
"fSneakExteriorDistanceMult": "",
"fSneakFlyingDistanceMult": "",
"fSneakLightExteriorMult": "",
"fSneakLightMoveMult": "",
"fSneakLightMult": "",
"fSneakLightRunMult": "",
"fSneakMaxDistance": "",
"fSneakNoticeMin": "",
"fSneakPerceptionSkillMax": "",
"fSneakPerceptionSkillMin": "",
"fSneakRunningMult": "",
"fSneakSizeBase": "",
"fSneakSkillMult": "",
"fSneakSleepBonus": "",
"fSneakSleepMod": "",
"fSneakSoundLosMult": "",
"fSneakSoundsMult": "",
"fSneakStealthBoyMult": "",
"fSortActorDistanceListTimer": "",
"fSpeechCraftBase": "",
"fSpeechcraftFavorMax": "",
"fSpeechcraftFavorMin": "",
"fSpeechCraftMult": "",
"fSpeechDelay": "",
"fSpellCastingDetectionHitActorMod": "",
"fSpellCastingDetectionMod": "",
"fSpellmakingGoldMult": "",
"fSplashScale1": "",
"fSplashScale2": "",
"fSplashScale3": "",
"fSplashSoundHeavy": "",
"fSplashSoundLight": "",
"fSplashSoundMedium": "",
"fSplashSoundOutMult": "",
"fSplashSoundTimer": "",
"fSplashSoundVelocityMult": "",
"fSprintEncumbranceMult": "",
"fSprintStaminaDrainMult": "",
"fSprintStaminaWeightBase": "",
"fSprintStaminaWeightMult": "",
"fStagger1WeapMult": "",
"fStagger2WeapMult": "",
"fStaggerAttackBase": "",
"fStaggerAttackMult": "",
"fStaggerBlockAttackBase": "",
"fStaggerBlockAttackMult": "",
"fStaggerBlockAttackShieldBase": "",
"fStaggerBlockAttackShieldMult": "",
"fStaggerBlockBase": "",
"fStaggerBlockingMult": "",
"fStaggerBlockMult": "",
"fStaggerMassBase": "",
"fStaggerMassMult": "",
"fStaggerMassOffsetBase": "",
"fStaggerMassOffsetMult": "",
"fStaggerMaxDuration": "",
"fStaggerMin": "",
"fStaggerPlayerMassMult": "",
"fStaggerRecoilingMult": "",
"fStaggerRunningMult": "",
"fStaggerShieldMult": "",
"fStaminaAttackWeaponBase": "",
"fStaminaAttackWeaponMult": "",
"fStaminaBashBase": "",
"fStaminaBlockBase": "",
"fStaminaBlockDmgMult": "",
"fStaminaBlockStaggerMult": "",
"fStaminaPowerBashBase": "",
"fStaminaRegenDelayMax": "",
"fStarsRotateDays": "",
"fStarsRotateXAxis": "",
"fStarsRotateYAxis": "",
"fStarsRotateZAxis": "",
"fStatsCameraFOV": "",
"fStatsCameraNearDistance": "",
"fStatsHealthLevelMult": "",
"fStatsHealthStartMult": "",
"fStatsLineScale": "",
"fStatsRotationRampTime": "",
"fStatsRotationSpeedMax": "",
"fStatsSkillsLookAtX": "",
"fStatsSkillsLookAtY": "",
"fStatsSkillsLookAtZ": "",
"fStatsStarCameraOffsetX": "",
"fStatsStarCameraOffsetY": "",
"fStatsStarCameraOffsetZ": "",
"fStatsStarLookAtX": "",
"fStatsStarLookAtY": "",
"fStatsStarLookAtZ": "",
"fStatsStarScale": "",
"fStatsStarXIncrement": "",
"fStatsStarYIncrement": "",
"fStatsStarZIncrement": "",
"fStatsStarZInitialOffset": "",
"fSubmergedAngularDamping": "",
"fSubmergedLinearDampingH": "",
"fSubmergedLinearDampingV": "",
"fSubmergedLODDistance": "",
"fSubmergedMaxSpeed": "",
"fSubmergedMaxWaterDistance": "",
"fSubSegmentVariance": "",
"fSubtitleSpeechDelay": "",
"fSummonDistanceCheckThreshold": "",
"fSummonedCreatureFadeOutSeconds": "",
"fSummonedCreatureMaxFollowDist": "",
"fSummonedCreatureMinFollowDist": "",
"fSummonedCreatureSearchRadius": "",
"fSunAlphaTransTime": "",
"fSunDirXExtreme": "",
"fSunMinimumGlareScale": "",
"fSunReduceGlareSpeed": "",
"fSunXExtreme": "",
"fSunYExtreme": "",
"fSunZExtreme": "",
"fSweetSpotAverage": "",
"fSweetSpotEasy": "",
"fSweetSpotHard": "",
"fSweetSpotVeryEasy": "",
"fSweetSpotVeryHard": "",
"fTakeBackTimerSetting": "",
"fTargetMovedCoveredMoveRepathLength": "",
"fTargetMovedRepathLengthLow": "",
"fTargetMovedRepathLength": "",
"fTeammateAggroOnDistancefromPlayer": "",
"fTeleportDoorActivateDelayTimer": "",
"fTemperingSkillUseMult": "",
"fTimerForPlayerFurnitureEnter": "",
"fTipImpulse": "",
"fTorchEvaluationTimer": "",
"fTorchLightLevelInterior": "",
"fTorchLightLevelMorning": "",
"fTorchLightLevelNight": "",
"fTrackDeadZoneXY": "",
"fTrackDeadZoneZ": "",
"fTrackEyeXY": "",
"fTrackEyeZ": "",
"fTrackFudgeXY": "",
"fTrackFudgeZ": "",
"fTrackJustAcquiredDuration": "",
"fTrackMaxZ": "",
"fTrackMinZ": "",
"fTrackSpeed": "",
"fTrackXY": "",
"fTrainingBaseCost": "",
"fTrainingMultCost": "",
"fTrapHitEventDelayMS": "",
"fTriggerAvoidPlayerDistance": "",
"fUnarmedCreatureDPSMult": "",
"fUnarmedDamageMult": "",
"fUnarmedNPCDPSMult": "",
"fUnderwaterFullDepth": "",
"fValueofItemForNoOwnership": "",
"fVATSAutomaticMeleeDamageMult": "",
"fVATSCameraMinTime": "",
"fVATSCamTransRBDownStart": "",
"fVATSCamTransRBRampDown": "",
"fVATSCamTransRBRampup": "",
"fVATSCamTransRBStart": "",
"fVATSCamTransRBStrengthCap": "",
"fVATSCamZoomInTime": "",
"fVATSChanceHitMult": "",
"fVATSCriticalChanceBonus": "",
"fVATSDamageToWeaponMult": "",
"fVATSDestructibleMult": "",
"fVATSDistanceFactor": "",
"fVATSDOFRange": "",
"fVATSDOFStrengthCap": "",
"fVATSDOFSwitchSeconds": "",
"fVATSGrenadeChanceMult": "",
"fVATSGrenadeDistAimZMult": "",
"fVATSGrenadeRangeMin": "",
"fVATSGrenadeRangeMult": "",
"fVATSGrenadeSkillFactor": "",
"fVATSGrenadeSuccessExplodeTimer": "",
"fVATSGrenadeSuccessMaxDistance": "",
"fVATSGrenadeTargetArea": "",
"fVATSGrenadeTargetMelee": "",
"fVATSH2HWarpDistanceMult": "",
"fVATSImageSpaceTransitionTime": "",
"fVATSLimbSelectCamPanTime": "",
"fVATSMaxChance": "",
"fVATSMaxEngageDistance": "",
"fVATSMeleeArmConditionBase": "",
"fVATSMeleeArmConditionMult": "",
"fVATSMeleeChanceMult": "",
"fVATSMeleeMaxDistance": "",
"fVATSMeleeReachMult": "",
"fVATSMeleeWarpDistanceMult": "",
"fVATSMoveCameraLimbMult": "",
"fVATSMoveCameraLimbPercent": "",
"fVATSMoveCameraMaxSpeed": "",
"fVATSMoveCameraXPercent": "",
"fVATSMoveCameraYPercent": "",
"fVATSParalyzePalmChance": "",
"fVATSPlaybackDelay": "",
"fVATSPlayerDamageMult": "",
"fVATSPlayerMagicTimeSlowdownMult": "",
"fVATSPlayerTimeUpdateMult": "",
"fVATSRadialRampup": "",
"fVATSRadialStart": "",
"fVATSRadialStrength": "",
"fVATSRangeSpreadMax": "",
"fVATSRangeSpreadUncertainty": "",
"fVATSScreenPercentFactor": "",
"fVATSShotBurstTime": "",
"fVatsShotgunSpreadRatio": "",
"fVATSShotLongBurstTime": "",
"fVATSSkillFactor": "",
"fVATSSmartCameraCheckHeight": "",
"fVATSSmartCameraCheckStepCount": "",
"fVATSSmartCameraCheckStepDistance": "",
"fVATSSpreadMult": "",
"fVATSStealthMult": "",
"fVATSStrangerDistance": "",
"fVATSStrangerOdds": "",
"fVATSTargetActorHeightPanMult": "",
"fVATSTargetActorZMultFarDist": "",
"fVATSTargetActorZMultFar": "",
"fVATSTargetActorZMultNear": "",
"fVATSTargetFOVMinDist": "",
"fVATSTargetFOVMinFOV": "",
"fVATSTargetFOVMultFarDist": "",
"fVATSTargetFOVMultFar": "",
"fVATSTargetFOVMultNear": "",
"fVATSTargetRotateMult": "",
"fVATSTargetScanRotateMult": "",
"fVATSTargetSelectCamPanTime": "",
"fVATSTargetTimeUpdateMult": "",
"fVATSThrownWeaponRangeMult": "",
"fVoiceRateBase": "",
"fWardAngleForExplosions": "",
"fWarningTimer": "",
"fWaterKnockdownSizeLarge": "",
"fWaterKnockdownSizeNormal": "",
"fWaterKnockdownSizeSmall": "",
"fWaterKnockdownSizeVeryLarge": "",
"fWaterKnockdownVelocity": "",
"fWeaponBashMax": "",
"fWeaponBashMin": "",
"fWeaponBashPCMax": "",
"fWeaponBashPCMin": "",
"fWeaponBashSkillUseBase": "",
"fWeaponBashSkillUseMult": "",
"fWeaponBlockSkillUseBase": "",
"fWeaponBlockSkillUseMult": "",
"fWeaponClutterKnockBipedScale": "",
"fWeaponClutterKnockMaxWeaponMass": "",
"fWeaponClutterKnockMinClutterMass": "",
"fWeaponClutterKnockMult": "",
"fWeaponConditionCriticalChanceMult": "",
"fWeaponConditionJam1": "",
"fWeaponConditionJam2": "",
"fWeaponConditionJam3": "",
"fWeaponConditionJam4": "",
"fWeaponConditionJam5": "",
"fWeaponConditionJam6": "",
"fWeaponConditionJam7": "",
"fWeaponConditionJam8": "",
"fWeaponConditionJam9": "",
"fWeaponConditionJam10": "",
"fWeaponConditionRateOfFire1": "",
"fWeaponConditionRateOfFire2": "",
"fWeaponConditionRateOfFire3": "",
"fWeaponConditionRateOfFire4": "",
"fWeaponConditionRateOfFire5": "",
"fWeaponConditionRateOfFire6": "",
"fWeaponConditionRateOfFire7": "",
"fWeaponConditionRateOfFire8": "",
"fWeaponConditionRateOfFire9": "",
"fWeaponConditionRateOfFire10": "",
"fWeaponConditionReloadJam1": "",
"fWeaponConditionReloadJam2": "",
"fWeaponConditionReloadJam3": "",
"fWeaponConditionReloadJam4": "",
"fWeaponConditionReloadJam5": "",
"fWeaponConditionReloadJam6": "",
"fWeaponConditionReloadJam7": "",
"fWeaponConditionReloadJam8": "",
"fWeaponConditionReloadJam9": "",
"fWeaponConditionReloadJam10": "",
"fWeaponConditionSpread1": "",
"fWeaponConditionSpread2": "",
"fWeaponConditionSpread3": "",
"fWeaponConditionSpread4": "",
"fWeaponConditionSpread5": "",
"fWeaponConditionSpread6": "",
"fWeaponConditionSpread7": "",
"fWeaponConditionSpread8": "",
"fWeaponConditionSpread9": "",
"fWeaponConditionSpread10": "",
"fWeaponTwoHandedAnimationSpeedMult": "",
"fWeatherFlashAmbient": "",
"fWeatherFlashDirectional": "",
"fWeatherFlashDuration": "",
"fWeatherTransAccel": "",
"fWeatherTransMax": "",
"fWeatherTransMin": "",
"fWortalchmult": "",
"fWortcraftChanceIntDenom": "",
"fWortcraftChanceLuckDenom": "",
"fWortcraftStrChanceDenom": "",
"fWortcraftStrCostDenom": "",
"fWortFailSkillUseMagnitude": "",
"fWortStrMult": "",
"fXPLevelUpBase": "",
"fXPLevelUpMult": "",
"fXPPerSkillRank": "",
"fZKeyComplexHelperMinDistance": "",
"fZKeyComplexHelperScale": "",
"fZKeyComplexHelperWeightMax": "",
"fZKeyComplexHelperWeightMin": "",
"fZKeyHeavyWeight": "",
"fZKeyMaxContactDistance": "",
"fZKeyMaxContactMassRatio": "",
"fZKeyMaxForceScaleHigh": "",
"fZKeyMaxForceScaleLow": "",
"fZKeyMaxForceWeightHigh": "",
"fZKeyMaxForceWeightLow": "",
"fZKeyMaxForce": "",
"fZKeyObjectDamping": "",
"fZKeySpringDamping": "",
"fZKeySpringElasticity": ""
}
return items
class SublimePapyrusSkyrimIntegerGameSettingNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"iActivatePickLength": "",
"iActorKeepTurnDegree": "",
"iActorLuckSkillBase": "",
"iActorTorsoMaxRotation": "",
"iAICombatMaxAllySummonCount": "",
"iAICombatMinDetection": "",
"iAICombatRestoreHealthPercentage": "",
"iAICombatRestoreMagickaPercentage": "",
"iAIFleeMaxHitCount": "",
"iAIMaxSocialDistanceToTriggerEvent": "",
"iAimingNumIterations": "",
"iAINPCRacePowerChance": "",
"iAINumberActorsComplexScene": "",
"iAINumberDaysToStayBribed": "",
"iAINumberDaysToStayIntimidated": "",
"iAISocialDistanceToTriggerEvent": "",
"iAlertAgressionMin": "",
"iAllowAlchemyDuringCombat": "",
"iAllowRechargeDuringCombat": "",
"iAllowRepairDuringCombat": "",
"iAllyHitCombatAllowed": "",
"iAllyHitNonCombatAllowed": "",
"iArmorBaseSkill": "",
"iArmorDamageBootsChance": "",
"iArmorDamageCuirassChance": "",
"iArmorDamageGauntletsChance": "",
"iArmorDamageGreavesChance": "",
"iArmorDamageHelmChance": "",
"iArmorDamageShieldChance": "",
"iArrestOnSightNonViolent": "",
"iArrestOnSightViolent": "",
"iArrowInventoryChance": "",
"iArrowMaxCount": "",
"iAttackOnSightNonViolent": "",
"iAttackOnSightViolent": "",
"iAttractModeIdleTime": "",
"iAVDAutoCalcSkillMax": "",
"iAVDhmsLevelup": "",
"iAVDSkillsLevelUp": "",
"iAVDSkillStart": "",
"iAvoidHurtingNonTargetsResponsibility": "",
"iBallisticProjectilePathPickSegments": "",
"iBloodSplatterMaxCount": "",
"iBoneLODDistMult": "",
"iClassAcrobat": "",
"iClassAgent": "",
"iClassArcher": "",
"iClassAssassin": "",
"iClassBarbarian": "",
"iClassBard": "",
"iClassBattlemage": "",
"iClassCharactergenClass": "",
"iClassCrusader": "",
"iClassHealer": "",
"iClassKnight": "",
"iClassMage": "",
"iClassMonk": "",
"iClassNightblade": "",
"iClassPilgrim": "",
"iClassPriest": "",
"iClassRogue": "",
"iClassScout": "",
"iClassSorcerer": "",
"iClassSpellsword": "",
"iClassThief": "",
"iClassWarrior": "",
"iClassWitchhunter": "",
"iCombatAimMaxIterations": "",
"iCombatCastDrainMinimumValue": "",
"iCombatCrippledTorsoHitStaggerChance": "",
"iCombatDismemberPartChance": "",
"iCombatExplodePartChance": "",
"iCombatFlankingAngleOffsetCount": "",
"iCombatFlankingAngleOffsetGoalCount": "",
"iCombatFlankingDirectionOffsetCount": "",
"iCombatHighPriorityModifier": "",
"iCombatHoverLocationCount": "",
"iCombatSearchDoorFailureMax": "",
"iCombatStealthPointDetectionThreshold": "",
"iCombatStealthPointSneakDetectionThreshold": "",
"iCombatTargetLocationCount": "",
"iCombatTargetPlayerSoftCap": "",
"iCombatUnloadedActorLastSeenTimeLimit6": "",
"iCommonSoulActorLevel": "",
"iCrimeAlarmLowRecDistance": "",
"iCrimeAlarmRecDistance": "",
"iCrimeCommentNumber": "",
"iCrimeDaysInPrisonMod": "",
"iCrimeEnemyCoolDownTimer": "",
"iCrimeFavorBaseValue": "",
"iCrimeGoldAttack": "",
"iCrimeGoldEscape": "",
"iCrimeGoldMinValue": "",
"iCrimeGoldMurder": "",
"iCrimeGoldPickpocket": "",
"iCrimeGoldStealHorse": "",
"iCrimeGoldTrespass": "",
"iCrimeGoldWerewolf": "",
"iCrimeMaxNumberofDaysinJail": "",
"iCrimeRegardBaseValue": "",
"iCrimeValueAttackValue": "",
"iCurrentTargetBonus": "",
"iDeathDropWeaponChance": "",
"iDebrisMaxCount": "",
"iDetectEventLightLevelExterior": "",
"iDetectEventLightLevelInterior": "",
"iDialogueDispositionFriendValue": "",
"iDismemberBloodDecalCount": "",
"iDispKaramMax": "",
"iDistancetoAttackedTarget": "",
"iFallLegDamageChance": "",
"iFavorAllyValue": "",
"iFavorConfidantValue": "",
"iFavorFriendValue": "",
"iFavorLoverValue": "",
"iFavorPointsRestore": "",
"iFriendHitCombatAllowed": "",
"iFriendHitNonCombatAllowed": "",
"iGameplayiSpeakingEmotionDeltaChange": "",
"iGameplayiSpeakingEmotionListenValue": "",
"iGrandSoulActorLevel": "",
"iGreaterSoulActorLevel": "",
"iGuardWarnings": "",
"iHairColor00": "",
"iHairColor01": "",
"iHairColor02": "",
"iHairColor03": "",
"iHairColor04": "",
"iHairColor05": "",
"iHairColor06": "",
"iHairColor07": "",
"iHairColor08": "",
"iHairColor09": "",
"iHairColor10": "",
"iHairColor11": "",
"iHairColor12": "",
"iHairColor13": "",
"iHairColor14": "",
"iHairColor15": "",
"iHorseTurnDegreesPerSecond": "",
"iHorseTurnDegreesRampUpPerSecond": "",
"iInventoryAskQuantityAt": "",
"iKarmaMax": "",
"iKarmaMin": "",
"iKillCamLevelOffset": "",
"iLargeProjectilePickCount": "",
"iLesserSoulActorLevel": "",
"iLevelUpReminder": "",
"iLightLevelExteriorMod": "",
"iLightLevelInteriorMod": "",
"iLightLevelMax": "",
"iLowLevelNPCMaxLevel": "",
"iMagicGuideWaypoints": "",
"iMagicLightMaxCount": "",
"iMapMarkerFadeStartDistance": "",
"iMapMarkerRevealDistance": "",
"iMapMarkerVisibleDistance": "",
"iMasserSize": "",
"iMaxAttachedArrows": "",
"iMaxCharacterLevel": "",
"iMaxPlayerRunes": "",
"iMaxSummonedCreatures": "",
"iMessCrippledLimbExplodeBonus": "",
"iMessIntactLimbDismemberChance": "",
"iMessTargetedLimbExplodeBonus": "",
"iMessTorsoExplodeChance": "",
"iMinClipSizeToAddReloadDelay": "",
"iMineDisarmExperience": "",
"iMoodFaceValue": "",
"iNPCBasePerLevelHealthMult": "",
"iNumberActorsAllowedToFollowPlayer": "",
"iNumberActorsGoThroughLoadDoorInCombat": "",
"iNumberActorsInCombatPlayer": "",
"iNumberGuardsCrimeResponse": "",
"iNumExplosionDecalCDPoint": "",
"iPCStartSpellSkillLevel": "",
"iPerkAttackDisarmChance": "",
"iPerkBlockDisarmChance": "",
"iPerkBlockStaggerChance": "",
"iPerkHandToHandBlockRecoilChance": "",
"iPerkHeavyArmorJumpSum": "",
"iPerkHeavyArmorSinkSum": "",
"iPerkLightArmorMasterMinSum": "",
"iPerkMarksmanKnockdownChance": "",
"iPerkMarksmanParalyzeChance": "",
"iPersuasionAngleMax": "",
"iPersuasionAngleMin": "",
"iPersuasionBribeCrime": "",
"iPersuasionBribeGold": "",
"iPersuasionBribeRefuse": "",
"iPersuasionBribeScale": "",
"iPersuasionDemandDisposition": "",
"iPersuasionDemandGold": "",
"iPersuasionDemandRefuse": "",
"iPersuasionDemandScale": "",
"iPersuasionInner": "",
"iPersuasionMiddle": "",
"iPersuasionOuter": "",
"iPersuasionPower1": "",
"iPersuasionPower2": "",
"iPersuasionPower3": "",
"iPickPocketWarnings": "",
"iPlayerCustomClass": "",
"iPlayerHealthHeartbeatFadeMS": "",
"iProjectileMaxRefCount": "",
"iProjectileMineShooterCanTrigger": "",
"iQuestReminderPipboyDisabledTime": "",
"iRelationshipAcquaintanceValue": "",
"iRelationshipAllyValue": "",
"iRelationshipArchnemesisValue": "",
"iRelationshipConfidantValue": "",
"iRelationshipEnemyValue": "",
"iRelationshipFoeValue": "",
"iRelationshipFriendValue": "",
"iRelationshipLoverValue": "",
"iRelationshipRivalValue": "",
"iRemoveExcessDeadComplexCount": "",
"iRemoveExcessDeadComplexTotalActorCount": "",
"iRemoveExcessDeadCount": "",
"iRemoveExcessDeadTotalActorCount": "",
"iSecondsToSleepPerUpdate": "",
"iSecundaSize": "",
"iShockBranchNumBolts": "",
"iShockBranchSegmentsPerBolt": "",
"iShockDebug": "",
"iShockNumBolts": "",
"iShockSegmentsPerBolt": "",
"iShockSubSegments": "",
"iSkillPointsTagSkillMult": "",
"iSkillUsageSneakFullDetection": "",
"iSkillUsageSneakMinDetection": "",
"iSneakSkillUseDistance": "",
"iSoundLevelLoud": "",
"iSoundLevelNormal": "",
"iSoundLevelSilent": "",
"iSoundLevelVeryLoud": "",
"iSpeechChallengeDifficultyAverage": "",
"iSpeechChallengeDifficultyEasy": "",
"iSpeechChallengeDifficultyHard": "",
"iSpeechChallengeDifficultyVeryEasy": "",
"iSpeechChallengeDifficultyVeryHard": "",
"iStaggerAttackChance": "",
"iStealWarnings": "",
"iTrainingExpertCost": "",
"iTrainingExpertSkill": "",
"iTrainingJourneymanCost": "",
"iTrainingJourneymanSkill": "",
"iTrainingMasterCost": "",
"iTrainingMasterSkill": "",
"iTrainingNumAllowedPerLevel": "",
"iTrespassWarnings": "",
"iVATSCameraHitDist": "",
"iVATSConcentratedFireBonus": "",
"iVATSStrangerMaxHP": "",
"iVoicePointsDefault": "",
"iWeaponCriticalHitDropChance": "",
"iXPBase": "",
"iXPBumpBase": "",
"iXPRewardDiscoverMapMarker": "",
"iXPRewardDiscoverSecretArea": "",
"iXPRewardHackComputer": "",
"iXPRewardKillOpponent": "",
"iXPRewardPickLock": ""
}
return items
class SublimePapyrusSkyrimStringGameSettingNameSuggestionsCommand(SublimePapyrus.SublimePapyrusShowSuggestionsCommand):
def get_items(self, **args):
items = {
"sAccept": "",
"sActionMapping": "",
"sActivateCreatureCalmed": "",
"sActivateNPCCalmed": "",
"sActivate": "",
"sActivationChoiceMessage": "",
"sActiveEffects": "",
"sActiveMineDescription": "",
"sActorFade": "",
"sAddCrimeGold": "",
"sAddedEffects": "",
"sAddedNote": "",
"sAddItemtoInventory": "",
"sAddItemtoSpellList": "",
"sAdd": "",
"sAlchemyMenuDescription": "",
"sAlchemy": "",
"sAllegiance": "",
"sAllItems": "",
"sAlreadyKnown": "",
"sAlreadyPlacedMine": "",
"sAlteration": "",
"sAmber": "",
"sAnimationCanNotEquipArmor": "",
"sAnimationCanNotEquipWeapon": "",
"sAnimationCanNotUnequip": "",
"sApparel": "",
"sAreaText": "",
"sArmorEnchantments": "",
"sArmorRating": "",
"sArmorSmithing": "",
"sArmor": "",
"sAttack": "",
"sAttributeDamaged": "",
"sAttributeDrained": "",
"sAttributesCount": "",
"sAttributesTitle": "",
"sAutoLoading": "",
"sAutosaveAbbrev": "",
"sAutoSaveDisabledDueToLackOfSpace": "",
"sAutoSavingLong": "",
"sAutoSaving": "",
"sBack": "",
"sBleedingOutMessage": "",
"sBloodParticleDefault": "",
"sBloodParticleMeleeDefault": "",
"sBloodSplatterAlpha01OPTFilename": "",
"sBloodSplatterColor01OPTFilename": "",
"sBloodSplatterFlare01Filename": "",
"sBloodTextureDefault": "",
"sBooks": "",
"sBountyStatString": "",
"sBounty": "",
"sBrightness": "",
"sBroken": "",
"sButtonLocked": "",
"sButton": "",
"sCameraPitch": "",
"sCancel": "",
"sCanNotEquipWornEnchantment": "",
"sCanNotReadBook": "",
"sCanNotTrainAnymore": "",
"sCanNotTrainHigher": "",
"sCantChangeResolution": "",
"sCantEquipBrokenItem": "",
"sCantEquipGeneric": "",
"sCantEquipPowerArmor": "",
"sCantHotkeyItem": "",
"sCantQuickLoad": "",
"sCantQuickSave": "",
"sCantRemoveWornItem": "",
"sCantRepairPastMax": "",
"sCantSaveNow": "",
"sCantUnequipGeneric": "",
"sChangeItemSelection": "",
"sCharGenControlsDisabled": "",
"sChemsAddicted": "",
"sChemsWithdrawal": "",
"sChemsWornOff": "",
"sChooseSoulGem": "",
"sChoose": "",
"sCleared": "",
"sClearSelections": "",
"sClose": "",
"sCombatCannotActivate": "",
"sConfirmAttribute": "",
"sConfirmContinue": "",
"sConfirmDelete": "",
"sConfirmDisenchant": "",
"sConfirmLoad": "",
"sConfirmNew": "",
"sConfirmSave": "",
"sConfirmSpendSoul": "",
"sConfirmWarning": "",
"sConjuration": "",
"sConstructibleMenuConfirm": "",
"sConstructibleMenuDescription": "",
"sContainerItemsTitle": "",
"sContainerPlaceChance": "",
"sContainerStealChance": "",
"sContinue": "",
"sContractedDisease": "",
"sControllerOption": "",
"sCorruptContentMessage": "",
"sCraft": "",
"sCreatedPoisonNamePrefix": "",
"sCreatedPotionNamePrefix": "",
"sCreated": "",
"sCreate": "",
"sCriticalStrike": "",
"sCrosshair": "",
"sCurrentLocation": "",
"sCurrentObjective": "",
"sCursorFilename": "",
"sDaedric": "",
"sDamage": "",
"sDefaultMessage": "",
"sDefaultPlayerName": "",
"sDeleteSaveGame": "",
"sDeleteSuccessful": "",
"sDestruction": "",
"sDeviceRemoved": "",
"sDevice": "",
"sDialogSubtitles": "",
"sDifficulty": "",
"sDisableHelp": "",
"sDisableXBoxController": "",
"sDiscoveredEffects": "",
"sDiscoveredIngredientEffectEating": "",
"sDiscoveredText": "",
"sDisenchant": "",
"sDismemberParticleDefault": "",
"sDismemberRobotParticleDefault": "",
"sDone": "",
"sDownloadsAvailable": "",
"sDownloadsNotAvail": "",
"sDragonSoulAcquired": "",
"sDragon": "",
"sDraugr": "",
"sDropEquippedItemWarning": "",
"sDropQuestItemWarning": "",
"sDungeonCleared": "",
"sDurationText": "",
"sDwarven": "",
"sEbony": "",
"sEffectAlreadyAdded": "",
"sEffectsListDisplayHours": "",
"sEffectsListDisplayHour": "",
"sEffectsListDisplayMins": "",
"sEffectsListDisplayMin": "",
"sEffectsListDisplaySecs": "",
"sEffectsListDisplaySec": "",
"sEffectsVolume": "",
"sElven": "",
"sEmpty": "",
"sEnableHelp": "",
"sEnchantArmorIncompatible": "",
"sEnchantDeconstructMenuDescription": "",
"sEnchanting": "",
"sEnchantInsufficientCharge": "",
"sEnchantItem": "",
"sEnchantmentKnown": "",
"sEnchantmentsLearned": "",
"sEnchantment": "",
"sEnchantMenuDescription": "",
"sEnchantMustChooseItems": "",
"sEnterItemName": "",
"sEnterName": "",
"sEquipItemOnPlayer": "",
"sEssentialCharacterDown": "",
"sExitGameAffirm": "",
"sExit": "",
"sExpert": "",
"sExplosionSplashParticles": "",
"sFailedActivation": "",
"sFailShouting": "",
"sFailSpendSoul": "",
"sFalmer": "",
"sFastTravelConfirm": "",
"sFastTravelNoTravelHealthDamage": "",
"sFavorites": "",
"sFileNotFound": "",
"sFindingContentMessage": "",
"sFirstPersonSkeleton": "",
"sFood": "",
"sFootstepsVolume": "",
"sFor": "",
"sFullHealth": "",
"sFurnitureSleep": "",
"sGeneralSubtitles": "",
"sGFWLive": "",
"sGlass": "",
"sGold": "",
"sGotAwayWithStealing": "",
"sGrassFade": "",
"sHairColor0": "",
"sHairColor1": "",
"sHairColor2": "",
"sHairColor3": "",
"sHairColor4": "",
"sHairColor5": "",
"sHairColor6": "",
"sHairColor7": "",
"sHairColor8": "",
"sHairColor9": "",
"sHairColor10": "",
"sHairColor11": "",
"sHairColor12": "",
"sHairColor13": "",
"sHairColor14": "",
"sHairColor15": "",
"sHarvest": "",
"sHealth": "",
"sHeavyArmorNoJump": "",
"sHeavyArmorSink": "",
"sHelp": "",
"sHide_": "",
"sHigh": "",
"sHold": "",
"sHUDArmorRating": "",
"sHUDColor": "",
"sHUDCompleted": "",
"sHUDDamage": "",
"sHUDFailed": "",
"sHUDOpacity": "",
"sHUDStarted": "",
"sIllusion": "",
"sImpactParticleConcreteDefault": "",
"sImpactParticleMetalDefault": "",
"sImpactParticleWoodDefault": "",
"sImperial": "",
"sImpossibleLock": "",
"sImprovement": "",
"sInaccessible": "",
"sIngredientFail": "",
"sIngredients": "",
"sIngredient": "",
"sInsufficientGoldToTrain": "",
"sInvalidPickpocket": "",
"sIron": "",
"sItemFade": "",
"sItemTooExpensive": "",
"sItemTooHeavy": "",
"sItem": "",
"sJewelry": "",
"sJourneyman": "",
"sJunk": "",
"sKeyLocked": "",
"sKeys": "",
"sKnownEffects": "",
"sLackRequiredPerksToImprove": "",
"sLackRequiredPerkToImproveMagical": "",
"sLackRequiredSkillToImprove": "",
"sLackRequiredToCreate": "",
"sLackRequiredToImprove": "",
"sLarge": "",
"sLearningEnchantments": "",
"sLearn": "",
"sLeather": "",
"sLeaveMarker": "",
"sLevelAbbrev": "",
"sLevelProgress": "",
"sLevelUpAvailable": "",
"sLightFade": "",
"sLoadFromMainMenu": "",
"sLoadingArea": "",
"sLoadingContentMessage": "",
"sLoadingLOD": "",
"sLoading": "",
"sLoadWhilePlaying": "",
"sLockBroken": "",
"sLocked": "",
"sLockpickInsufficientPerks": "",
"sLostController": "",
"sLow": "",
"sMagicEffectNotApplied": "",
"sMagicEffectResisted": "",
"sMagicEnhanceWeaponNoWeapon": "",
"sMagicEnhanceWeaponWeaponEnchanted": "",
"sMagicGuideNoMarker": "",
"sMagicGuideNoPath": "",
"sMagicTelekinesisNoRecast": "",
"sMagnitudeIsLevelText": "",
"sMagnitudeText": "",
"sMainMenu": "",
"sMakeDefaults": "",
"sMapMarkerAdded": "",
"sMasterVolume": "",
"sMaster": "",
"sMedium": "",
"sMenuDisplayAutosaveName": "",
"sMenuDisplayDayString": "",
"sMenuDisplayLevelString": "",
"sMenuDisplayNewSave": "",
"sMenuDisplayNoSaves": "",
"sMenuDisplayPlayTime": "",
"sMenuDisplayQuicksaveName": "",
"sMenuDisplaySave": "",
"sMenuDisplayShortXBoxSaveMessage": "",
"sMenuDisplayUnknownLocationString": "",
"sMenuDisplayXBoxSaveMessage": "",
"sMiscConstantEffect": "",
"sMiscPlayerDeadLoadOption": "",
"sMiscPlayerDeadMenuOption": "",
"sMiscPlayerDeadMessage": "",
"sMiscQuestDescription": "",
"sMiscQuestName": "",
"sMiscUnknownEffect": "",
"sMisc": "",
"sMissingImage": "",
"sMissingName": "",
"sMouseSensitivity": "",
"sMoveMarkerQuestion": "",
"sMoveMarker": "",
"sMultipleDragonSoulCount": "",
"sMusicVolume": "",
"sMustRestart": "",
"sName": "",
"sNeutral": "",
"sNewSave": "",
"sNext": "",
"sNoArrows": "",
"sNoChargeItems_": "",
"sNoChildUse": "",
"sNoDeviceSelected": "",
"sNoEatQuestItem": "",
"sNoFastTravelAlarm": "",
"sNoFastTravelCell": "",
"sNoFastTravelCombat": "",
"sNoFastTravelDefault": "",
"sNoFastTravelHostileActorsNear": "",
"sNoFastTravelInAir": "",
"sNoFastTravelOverencumbered": "",
"sNoFastTravelScriptBlock": "",
"sNoFastTravelUndiscovered": "",
"sNoItemsToRepair": "",
"sNoJumpWarning": "",
"sNoKeyDropWarning": "",
"sNoLockPickIfCrimeAlert": "",
"sNoMoreFollowers": "",
"sNone": "",
"sNoPickPocketAgain": "",
"sNoProfileSelected": "",
"sNoRepairHostileActorsNear": "",
"sNoRepairInCombat": "",
"sNoRestart": "",
"sNormalWeaponsResisted": "",
"sNormal": "",
"sNoSaves": "",
"sNoSitOnOwnedFurniture": "",
"sNoSleepDefault": "",
"sNoSleepHostileActorsNear": "",
"sNoSleepInAir": "",
"sNoSleepInCell": "",
"sNoSleepInOwnedBed": "",
"sNoSleepTakingHealthDamage": "",
"sNoSleepTrespass": "",
"sNoSleepWarnToLeave": "",
"sNoSleepWhileAlarm": "",
"sNoSpareParts": "",
"sNoTalkFleeing": "",
"sNoTalkUnConscious": "",
"sNotAllowedToUseAutoDoorsWhileonHorse": "",
"sNotEnoughRoomWarning": "",
"sNotEnoughVendorGold": "",
"sNoWaitDefault": "",
"sNoWaitHostileActorsNear": "",
"sNoWaitInAir": "",
"sNoWaitInCell": "",
"sNoWaitTakingHealthDamage": "",
"sNoWaitTrespass": "",
"sNoWaitWarnToLeave": "",
"sNoWaitWhileAlarm": "",
"sNo": "",
"sNumberAbbrev": "",
"sObjectFade": "",
"sObjectInUse": "",
"sObjectLODFade": "",
"sOff": "",
"sOf": "",
"sOk": "",
"sOldDownloadsAvailable": "",
"sOn": "",
"sOpenedContainer": "",
"sOpenWithKey": "",
"sOpen": "",
"sOptional": "",
"sOrcish": "",
"sOr": "",
"sOutOfLockpicks": "",
"sOverEncumbered": "",
"sOwned": "",
"sPauseText": "",
"sPCControlsTextNone": "",
"sPCControlsTextPrefix": "",
"sPCControlsTriggerPrefix": "",
"sPCRelationshipNegativeChangeText": "",
"sPCRelationshipPositiveChangeText": "",
"sPickpocketFail": "",
"sPickpocket": "",
"sPipboyColor": "",
"sPlaceMarkerUndiscovered": "",
"sPlaceMarker": "",
"sPlayerDisarmedMessage": "",
"sPlayerLeavingBorderRegion": "",
"sPlayerSetMarkerName": "",
"sPlayTime": "",
"sPleaseStandBy": "",
"sPoisonAlreadyPoisonedMessage": "",
"sPoisonBowConfirmMessage": "",
"sPoisonConfirmMessage": "",
"sPoisoned": "",
"sPoisonNoWeaponMessage": "",
"sPoisonUnableToPoison": "",
"sPotionCreationFailed": "",
"sPotions": "",
"sPowers": "",
"sPressControl": "",
"sPreviousSelection": "",
"sPrevious": "",
"sPrisoner": "",
"sQuantity": "",
"sQuestAddedText": "",
"sQuestCompletedText": "",
"sQuestFailed": "",
"sQuestUpdatedText": "",
"sQuickLoading": "",
"sQuicksaveAbbrev": "",
"sQuickSaving": "",
"sQuitAlchemy": "",
"sQuitEnchanting": "",
"sRadioSignalLost": "",
"sRadioStationDiscovered": "",
"sRadioVolume": "",
"sRangeText": "",
"sRanksText": "",
"sRead": "",
"sRemoteActivation": "",
"sRemoveCrimeGold": "",
"sRemoveItemFromInventory": "",
"sRemoveMarker": "",
"sRemove": "",
"sRenameItem": "",
"sRepairAllItems": "",
"sRepairCost": "",
"sRepairItem": "",
"sRepairServicesTitle": "",
"sRepairSkillTooLow": "",
"sRepairSkill": "",
"sRepair": "",
"sRequirementsText": "",
"sRequirements": "",
"sResetToDefaults": "",
"sResolution": "",
"sResource": "",
"sRestartBecauseContentRemoved": "",
"sRestartSignedOut": "",
"sRestartToUseNewContent": "",
"sRestartToUseProfileContent": "",
"sRestoration": "",
"sReturn": "",
"sRewardXPIcon": "",
"sRewardXP": "",
"sRide": "",
"sRSMAge": "",
"sRSMBody": "",
"sRSMBrowForward": "",
"sRSMBrowHeight": "",
"sRSMBrowTypes": "",
"sRSMBrowWidth": "",
"sRSMBrow": "",
"sRSMCheekboneHeight": "",
"sRSMCheekboneWidth": "",
"sRSMCheekColorLower": "",
"sRSMCheekColor": "",
"sRSMChinColor": "",
"sRSMChinForward": "",
"sRSMChinLength": "",
"sRSMChinWidth": "",
"sRSMComplexionColor": "",
"sRSMComplexion": "",
"sRSMConfirmDestruction": "",
"sRSMConfirm": "",
"sRSMDirtColor": "",
"sRSMDirt": "",
"sRSMEyeColor": "",
"sRSMEyeDepth": "",
"sRSMEyeHeight": "",
"sRSMEyelinerColor": "",
"sRSMEyeSocketLowerColor": "",
"sRSMEyeSocketUpperColor": "",
"sRSMEyes": "",
"sRSMEyeTypes": "",
"sRSMEyeWidth": "",
"sRSMFace": "",
"sRSMFacialHairColorPresets": "",
"sRSMFacialHairPresets": "",
"sRSMForeheadColor": "",
"sRSMHairColorPresets": "",
"sRSMHairPresets": "",
"sRSMHair": "",
"sRSMHeadPresets": "",
"sRSMHead": "",
"sRSMJawForward": "",
"sRSMJawHeight": "",
"sRSMJawWidth": "",
"sRSMLaughLines": "",
"sRSMLipColor": "",
"sRSMMouthForward": "",
"sRSMMouthHeight": "",
"sRSMMouthTypes": "",
"sRSMMouth": "",
"sRSMNameWarning": "",
"sRSMName": "",
"sRSMNeckColor": "",
"sRSMNoseColor": "",
"sRSMNoseHeight": "",
"sRSMNoseLength": "",
"sRSMNoseTypes": "",
"sRSMPaintColor": "",
"sRSMPaint": "",
"sRSMRace": "",
"sRSMScars": "",
"sRSMSex": "",
"sRSMSkinColor": "",
"sRSMTone": "",
"sRSMWeight": "",
"sRumble": "",
"sSaveFailed": "",
"sSaveGameContentIsMissing": "",
"sSaveGameCorruptMenuMessage": "",
"sSaveGameCorrupt": "",
"sSaveGameDeviceError": "",
"sSaveGameIsCorrupt": "",
"sSaveGameNoLongerAvailable": "",
"sSaveGameNoMasterFilesFound": "",
"sSaveGameOldVersion": "",
"sSaveGameOutOfDiskSpace": "",
"sSaveNotAvailable": "",
"sSaveOnRest": "",
"sSaveOnTravel": "",
"sSaveOnWait": "",
"sSaveOverSaveGame": "",
"sSaveSuccessful": "",
"sSceneBlockingActorActivation": "",
"sScrollEquipped": "",
"sScrolls": "",
"sSearch": "",
"sSelectItemToRepair": "",
"sSelect": "",
"sSelfRange": "",
"sServeSentenceQuestion": "",
"sServeTimeQuestion": "",
"sSexFemalePossessive": "",
"sSexFemalePronoun": "",
"sSexFemale": "",
"sSexMalePossessive": "",
"sSexMalePronoun": "",
"sSexMale": "",
"sShadowFade": "",
"sShoutAdded": "",
"sShouts": "",
"sSingleDragonSoulCount": "",
"sSit": "",
"sSkillIncreasedNum": "",
"sSkillIncreased": "",
"sSkillsCount": "",
"sSkillsTitle": "",
"sSmall": "",
"sSmithingConfirm": "",
"sSmithingMenuDescription": "",
"sSneakAttack": "",
"sSneakCaution": "",
"sSneakDanger": "",
"sSneakDetected": "",
"sSneakHidden": "",
"sSortMethod": "",
"sSoulCaptured": "",
"sSoulGems": "",
"sSoulGemTooSmall": "",
"sSoulGem": "",
"sSoulLevel": "",
"sSpace": "",
"sSpecularityFade": "",
"sSpeechChallengeFailure": "",
"sSpeechChallengeSuccess": "",
"sSpellAdded": "",
"sSplashParticles": "",
"sStatsMustSelectPerk": "",
"sStatsNextRank": "",
"sStatsPerkConfirm": "",
"sStealFrom": "",
"sStealHorse": "",
"sSteal": "",
"sSteel": "",
"sStormcloak": "",
"sStudded": "",
"sSuccessfulSneakAttackEnd": "",
"sSuccessfulSneakAttackMain": "",
"sTakeAll": "",
"sTake": "",
"sTalk": "",
"sTargetRange": "",
"sTeammateCantGiveOutfit": "",
"sTeammateCantTakeOutfit": "",
"sTeammateOverencumbered": "",
"sTextureSize": "",
"sStormcloak": "",
"sTouchRange": "",
"sTo": "",
"sTraitsCount": "",
"sTraitsTitle": "",
"sTreeLODFade": "",
"sTweenDisabledMessage": "",
"sUnequipItemOnPlayer": "",
"sUnlock": "",
"sValue": "",
"sVatsAimed": "",
"sVatsAiming": "",
"sVatsBodyPart": "",
"sVATSMessageLowAP": "",
"sVATSMessageNoAmmo": "",
"sVATSMessageZeroChance": "",
"sVatsSelect": "",
"sVatsTarget": "",
"sVDSGManual": "",
"sVDSGPlate": "",
"sVideoChange": "",
"sViewDistance": "",
"sVoiceVolume": "",
"sWaitHere": "",
"sWeaponBreak": "",
"sWeaponEnchantments": "",
"sWeaponSmithing": "",
"sWeapons": "",
"sWeight": "",
"sWhite": "",
"sWitnessKilled": "",
"sWood": "",
"sXSensitivity": "",
"sYesRestart": "",
"sYes": "",
"sYour": "",
"sYSensitivity": ""
}
return items
| {
"repo_name": "Kapiainen/SublimePapyrus",
"path": "Source/Modules/Skyrim/Plugin.py",
"copies": "1",
"size": "170027",
"license": "mit",
"hash": 1783732215646973400,
"line_mean": 34.1731485312,
"line_max": 231,
"alpha_frac": 0.6760102807,
"autogenerated": false,
"ratio": 2.8612031973075305,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8745175949534361,
"avg_score": 0.058407505694633884,
"num_lines": 4834
} |
"""API for backpopulating the db from reddit"""
from datetime import datetime, timezone
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from channels import api, utils
from channels.constants import (
LINK_TYPE_LINK,
LINK_TYPE_SELF,
EXTENDED_POST_TYPE_ARTICLE,
DELETED_COMMENT_OR_POST_TEXT,
)
User = get_user_model()
log = logging.getLogger()
def backpopulate_post(*, post, submission):
"""
Backpopulates a post with values from a submission
Args:
post (channels.models.Post): the post to backpopulate
submission (Submission): the reddit submission to source data from
"""
if not submission.is_self:
post.post_type = LINK_TYPE_LINK
post.url = submission.url
if post.link_meta is None and settings.EMBEDLY_KEY:
post.link_meta = utils.get_or_create_link_meta(submission.url)
elif getattr(post, "article", None):
post.post_type = EXTENDED_POST_TYPE_ARTICLE
else:
post.post_type = LINK_TYPE_SELF
post.text = submission.selftext
try:
if submission.author:
post.author = User.objects.get(username=submission.author.name)
except User.DoesNotExist:
log.warning(
"Unable to find author '%s'' for submission '%s'",
submission.author.name,
submission.id,
)
post.title = submission.title
post.score = submission.ups
post.num_comments = submission.num_comments
post.edited = submission.edited if submission.edited is False else True
post.removed = submission.banned_by is not None
# this already has a values, but it's incorrect for records prior to the creation of the Post model
post.created_on = datetime.fromtimestamp(submission.created, tz=timezone.utc)
post.deleted = submission.selftext == DELETED_COMMENT_OR_POST_TEXT
post.save()
def backpopulate_comments(*, post, submission):
"""
Backpopulates a post's comments with values from a submission CommentTree
Args:
post (channels.models.Post): the post to backpopulate
submission (Submission): the reddit submission to source data from
Returns:
int: number of comments backpopulated
"""
submission.comments.replace_more(limit=None)
all_comments = submission.comments.list()
author_usernames = {
comment.author.name for comment in all_comments if comment.author
}
authors_by_username = User.objects.in_bulk(author_usernames, field_name="username")
update_count = 0
for comment in all_comments:
author = (
authors_by_username.get(comment.author.name) if comment.author else None
)
api.create_comment(post=post, comment=comment, author=author)
update_count += 1
return update_count
| {
"repo_name": "mitodl/open-discussions",
"path": "channels/backpopulate_api.py",
"copies": "1",
"size": "2848",
"license": "bsd-3-clause",
"hash": -2390468703220812300,
"line_mean": 31.3636363636,
"line_max": 103,
"alpha_frac": 0.6797752809,
"autogenerated": false,
"ratio": 4,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51797752809,
"avg_score": null,
"num_lines": null
} |
"""API for bootcamp applications app"""
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from applications.constants import (
AppStates,
REVIEW_STATUS_REJECTED,
REVIEW_STATUS_PENDING,
SUBMISSION_VIDEO,
)
from applications.models import (
ApplicationStepSubmission,
BootcampApplication,
BootcampRunApplicationStep,
VideoInterviewSubmission,
)
from applications.utils import check_eligibility_to_skip_steps
from applications import tasks
from jobma.api import create_interview_in_jobma
from jobma.models import Interview, Job
from profiles.api import is_user_info_complete
def get_or_create_bootcamp_application(user, bootcamp_run_id):
"""
Fetches a bootcamp application for a user if it exists. Otherwise, an application is created with the correct
state.
Args:
user (User): The user applying for the bootcamp run
bootcamp_run_id (int): The id of the bootcamp run to which the user is applying
Returns:
Tuple[BootcampApplication, bool]: The bootcamp application paired with a boolean indicating whether
or not a new application was created
"""
with transaction.atomic():
(
bootcamp_app,
created,
) = BootcampApplication.objects.select_for_update().get_or_create(
user=user, bootcamp_run_id=bootcamp_run_id
)
if created:
derived_state = derive_application_state(bootcamp_app)
bootcamp_app.state = derived_state
bootcamp_app.save()
if created:
if check_eligibility_to_skip_steps(bootcamp_app):
bootcamp_app.skip_application_steps()
bootcamp_app.save()
else:
tasks.populate_interviews_in_jobma.delay(bootcamp_app.id)
return bootcamp_app, created
def derive_application_state(
bootcamp_application,
): # pylint: disable=too-many-return-statements
"""
Returns the correct state that an application should be in based on the application object itself and related data
Args:
bootcamp_application (BootcampApplication): A bootcamp application
Returns:
str: The derived state of the bootcamp application based on related data
"""
if not is_user_info_complete(bootcamp_application.user):
return AppStates.AWAITING_PROFILE_COMPLETION.value
if not bootcamp_application.resume_file and not bootcamp_application.linkedin_url:
return AppStates.AWAITING_RESUME.value
submissions = list(bootcamp_application.submissions.all())
submission_review_statuses = [
submission.review_status for submission in submissions
]
if any([status == REVIEW_STATUS_REJECTED for status in submission_review_statuses]):
return AppStates.REJECTED.value
elif any(
[status == REVIEW_STATUS_PENDING for status in submission_review_statuses]
):
return AppStates.AWAITING_SUBMISSION_REVIEW.value
elif len(submissions) < bootcamp_application.bootcamp_run.application_steps.count():
return AppStates.AWAITING_USER_SUBMISSIONS.value
elif not bootcamp_application.is_paid_in_full:
return AppStates.AWAITING_PAYMENT.value
return AppStates.COMPLETE.value
def get_required_submission_type(application):
"""
Get the submission type of the first unsubmitted step for an application
Args:
application (BootcampApplication): The application to query
Returns:
str: The submission type
"""
submission_subquery = application.submissions.all()
return (
application.bootcamp_run.application_steps.exclude(
id__in=submission_subquery.values_list("run_application_step", flat=True)
)
.order_by("application_step__step_order")
.values_list("application_step__submission_type", flat=True)
.first()
)
def populate_interviews_in_jobma(application):
"""
Go over each ApplicationStep for the application and create the interviews in Jobma.
Args:
application (BootcampApplication): A bootcamp application
"""
for run_step in BootcampRunApplicationStep.objects.filter(
bootcamp_run=application.bootcamp_run,
application_step__submission_type=SUBMISSION_VIDEO,
):
# Job should be created by admin beforehand
job = Job.objects.get(run=application.bootcamp_run)
interview, _ = Interview.objects.get_or_create(
applicant=application.user, job=job
)
if not interview.interview_url:
create_interview_in_jobma(interview)
# Make sure a VideoInterviewSubmission & ApplicationStepSubmission exist
video_interview_submission, _ = VideoInterviewSubmission.objects.get_or_create(
interview=interview
)
ApplicationStepSubmission.objects.get_or_create(
bootcamp_application=application,
run_application_step=run_step,
defaults={
"object_id": video_interview_submission.id,
"content_type": ContentType.objects.get_for_model(
video_interview_submission
),
},
)
| {
"repo_name": "mitodl/bootcamp-ecommerce",
"path": "applications/api.py",
"copies": "1",
"size": "5227",
"license": "bsd-3-clause",
"hash": 3401688433125379600,
"line_mean": 34.801369863,
"line_max": 118,
"alpha_frac": 0.6850966137,
"autogenerated": false,
"ratio": 4.184947958366694,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5370044572066693,
"avg_score": null,
"num_lines": null
} |
""" API for center """
import datetime
import time
import grpc
import functools
from django.db import connection
from django.utils import timezone
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from application import restapi
from application.resource import ResourceMetaCommon, NoAuthorization
from center.models import Sensor, SensorResync, ConfigureSensorTask
from tastypie import resources
from tastypie.authentication import Authentication
from tastypie.authorization import ReadOnlyAuthorization, Authorization as RWAuthorization
from tastypie import fields
from receiver import api_pb2_grpc
from configurator import api_pb2 as cfg_pb2
class SensorAuthorization(ReadOnlyAuthorization):
def update_detail(self, object_list, bundle):
return bundle.request.user.is_superuser
def delete_detail(self, object_list, bundle):
return bundle.request.user.is_superuser
class SensorResource(resources.ModelResource):
valid = fields.BooleanField(null=True, readonly=True, help_text='Recent update status')
vcc = fields.FloatField(null=True, help_text='Power in battery in sensor')
rssi = fields.FloatField(null=True, help_text='RSSI of sensor')
lqi = fields.FloatField(null=True, help_text='Line Quality Indicator of sensor')
interval = fields.FloatField(null=True, help_text='Elapsed time since last report')
age = fields.FloatField(null=True, readonly=True)
server_time = fields.DateTimeField(readonly=True)
sensor_resync = fields.ForeignKey('center.restapi.SensorResyncResource', '', readonly=True, null=True)
thsensor = fields.ForeignKey('center.restapi.THSensorResource', '', readonly=True, null=True)
class Meta(ResourceMetaCommon):
queryset = Sensor.objects.all()
authorization = SensorAuthorization()
excludes = ('last_seq',)
ordering = (
'id',
)
def dehydrate(self, bundle):
bundle = super(SensorResource, self).dehydrate(bundle)
now = timezone.now()
bundle.data['thsensor'] = THSensorResourceInstance.get_resource_uri(bundle.obj)
bundle._cache = bundle.obj.get_cache()
if bundle._cache:
bundle.data['valid'] = bundle._cache.get('valid', None)
bundle.data['vcc'] = bundle._cache.get('Power', None)
bundle.data['rssi'] = bundle._cache.get('RSSI', None)
bundle.data['lqi'] = bundle._cache.get('LQI', None)
bundle.data['interval'] = bundle._cache.get('intvl', None)
bundle.data['last_tsf'] = bundle._cache.get('last_tsf', None)
if bundle.data['valid'] == False:
bundle.data['sensor_resync'] = SensorResyncResourceInstance.get_resource_uri(bundle.obj)
return bundle
class THSensorResource(SensorResource):
temperature = fields.FloatField(null=True)
humidity = fields.FloatField(null=True)
class Meta(SensorResource.Meta):
excludes = ('thsensor',)
def dehydrate(self, bundle):
bundle = super(THSensorResource, self).dehydrate(bundle)
if bundle._cache:
bundle.data['temperature'] = bundle._cache.get('Temperature', None)
bundle.data['humidity'] = bundle._cache.get('Humidity', None)
return bundle
THSensorResourceInstance = THSensorResource()
restapi.RestApi.register(SensorResource())
restapi.RestApi.register(THSensorResourceInstance)
class SensorResyncResource(resources.ModelResource):
sensor = fields.ToOneField(THSensorResource, 'sensor')
ts = fields.DateTimeField('ts', readonly=True)
class Meta(ResourceMetaCommon):
queryset = SensorResync.objects.all()
authorization = RWAuthorization()
detail_allowed_methods = ['get']
list_allowed_methods = ['get', 'post']
SensorResyncResourceInstance = SensorResyncResource()
restapi.RestApi.register(SensorResyncResourceInstance)
class ConfigureSensorTaskAuthorization(NoAuthorization):
def read_detail(self, object_list, bundle):
return bundle.request.user.is_superuser
def create_detail(self, object_list, bundle):
return bundle.request.user.is_superuser
class ConfigureSensorTaskResource(resources.ModelResource):
sensor_id = fields.IntegerField()
sensor_name = fields.CharField()
created = fields.DateTimeField('created', null=True, readonly=True)
started = fields.DateTimeField('started', null=True, readonly=True)
first_discovery = fields.DateTimeField('first_discovery', null=True, readonly=True)
last_discovery = fields.DateTimeField('last_discovery', null=True, readonly=True)
finished = fields.DateTimeField('finished', null=True, readonly=True)
error = fields.CharField('error', null=True, readonly=True)
class Meta(ResourceMetaCommon):
queryset = ConfigureSensorTask.objects.select_related('sensor')
authorization = ConfigureSensorTaskAuthorization()
detail_allowed_methods = ['get']
list_allowed_methods = ['post']
fields = ['id']
def obj_create(self, bundle, **kwargs):
if 'sensor_name' in bundle.data:
sensor_id = (set(range(1, 128)) - set([s.pk for s in Sensor.objects.all()])).pop()
sensor = Sensor.objects.create(
id=sensor_id,
name=bundle.data['sensor_name'],
)
else:
sensor = Sensor.objects.get(pk=bundle.data['sensor_id'])
return super().obj_create(bundle, sensor=sensor)
def dehydrate(self, bundle):
bundle.data['sensor_id'] = bundle.obj.sensor.id
bundle.data['sensor_name'] = bundle.obj.sensor.name
return bundle
ConfigureSensorTaskResourceInstance = ConfigureSensorTaskResource()
restapi.RestApi.register(ConfigureSensorTaskResourceInstance)
@receiver(post_save, sender=ConfigureSensorTask)
def _receiver_handletask(sender, instance, created, **kwargs):
if created:
connection.on_commit(functools.partial(_receiver_handletask_real, instance))
def _receiver_handletask_real(instance):
channel = grpc.insecure_channel('{}:{}'.format(settings.RECEIVER_HOST, settings.RECEIVER_PORT))
receiver = api_pb2_grpc.ReceiverStub(channel)
receiver.HandleTask(cfg_pb2.Task(task_id=instance.id))
channel.close()
| {
"repo_name": "rkojedzinszky/thermo-center",
"path": "center/restapi.py",
"copies": "1",
"size": "6341",
"license": "bsd-3-clause",
"hash": 5363852612892150000,
"line_mean": 39.6474358974,
"line_max": 106,
"alpha_frac": 0.7019397571,
"autogenerated": false,
"ratio": 4.018377693282636,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5220317450382636,
"avg_score": null,
"num_lines": null
} |
"""API for channels"""
from django.contrib.auth.models import Group
from django.db import transaction
from guardian.core import ObjectPermissionChecker
from guardian.shortcuts import assign_perm, remove_perm
def create_channel_groups(channel_name):
"""
Create the moderator and contributor groups for a channel
Args:
channel_name (str):
the name of the channel
Returns:
tuple of (Group, Group): the created channel groups
"""
moderator_group, _ = Group.objects.get_or_create(name=f"Moderators: {channel_name}")
contributor_group, _ = Group.objects.get_or_create(
name=f"Contributors: {channel_name}"
)
return moderator_group, contributor_group
@transaction.atomic
def set_user_or_group_permissions(channel, user_or_group, perms):
"""
Sets the permissions for a user or group on a channel
Args:
channel(discussions.models.Channel):
the channel for which to set permissions
user_or_group (User or Group):
the user or group to add permissions for
perms (list of str):
the list of permissions
"""
checker = ObjectPermissionChecker(user_or_group)
# make a copy of the current permissions list to prepopulate which perms we need to remove
perms_to_remove = checker.get_perms(channel)[:]
for perm in perms:
if not checker.has_perm(perm, channel):
assign_perm(perm, user_or_group, channel)
if perm in perms_to_remove:
perms_to_remove.remove(perm)
for perm in perms_to_remove:
remove_perm(perm, user_or_group, channel)
@transaction.atomic
def set_channel_permissions(channel):
"""
Sets permissions for the users and groups of the channel
Args:
channel(discussions.models.Channel):
the channel for which to set permissions
"""
# moderator permissions
set_user_or_group_permissions(
channel, channel.moderator_group, ["change_channel", "view_channel"]
)
# contributor permissions
set_user_or_group_permissions(channel, channel.contributor_group, ["view_channel"])
| {
"repo_name": "mitodl/open-discussions",
"path": "discussions/api/channels.py",
"copies": "1",
"size": "2149",
"license": "bsd-3-clause",
"hash": -4819507895044230000,
"line_mean": 29.2676056338,
"line_max": 94,
"alpha_frac": 0.6728711028,
"autogenerated": false,
"ratio": 4.093333333333334,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5266204436133334,
"avg_score": null,
"num_lines": null
} |
"""API for choices that appear as parts of forms, in drop-dpwn menus."""
from google.appengine.ext import ndb
from protorpc import message_types
from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service
import base_api
import ndb_models
package = 'rooms'
class Site(messages.Message):
id = messages.IntegerField(1, required=True)
class Choice(messages.Message):
id = messages.IntegerField(1, required=True)
label = messages.StringField(2)
string_id = messages.StringField(3)
class Choices(messages.Message):
choice = messages.MessageField(Choice, 1, repeated=True)
class ChoicesApi(base_api.BaseApi):
"""Protorpc service implementing APIs that exist to populate
drop-down selections in UI. Used when you're editing a ROOM model
that has foreign keys.
"""
@remote.method(message_types.VoidMessage,
Choices)
def captain_choices_read(self, request):
self._authorize_staff()
choices = Choices()
for mdl in ndb_models.Captain.query().order(ndb_models.Captain.name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
@remote.method(Site, Choices)
def captain_for_site_choices_read(self, request):
self._authorize_user()
choices = Choices()
if self._user.staff:
for mdl in ndb_models.Captain.query().order(ndb_models.Captain.name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
sitecaptain_models = list(
ndb_models.SiteCaptain.query(ndb_models.SiteCaptain.site == ndb.Key(ndb_models.NewSite, request.id)))
captains = ndb.get_multi(set(m.captain for m in sitecaptain_models))
captains.sort(key=lambda c: c.name)
for mdl in captains:
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
@remote.method(message_types.VoidMessage,
Choices)
def supplier_choices_read(self, request):
self._authorize_user()
choices = Choices()
for mdl in ndb_models.Supplier.query(ndb_models.Supplier.active == 'Active').order(ndb_models.Supplier.name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
@remote.method(message_types.VoidMessage,
Choices)
def staffposition_choices_read(self, request):
self._authorize_user()
choices = Choices()
for mdl in ndb_models.StaffPosition.query().order(ndb_models.StaffPosition.position_name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.position_name))
return choices
@remote.method(message_types.VoidMessage,
Choices)
def jurisdiction_choices_read(self, request):
self._authorize_user()
choices = Choices()
for mdl in ndb_models.Jurisdiction.query().order(ndb_models.Jurisdiction.name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
@remote.method(message_types.VoidMessage,
Choices)
def ordersheet_choices_read(self, request):
self._authorize_user()
choices = Choices()
mdls = ndb_models.OrderSheet.query(ndb_models.OrderSheet.visibility != 'Inactive')
for mdl in sorted(mdls, key=lambda m: m.name):
choices.choice.append(Choice(id=mdl.key.integer_id(), label=mdl.name))
return choices
@remote.method(message_types.VoidMessage,
Choices)
def program_type_choices_read(self, request):
self._authorize_user()
choices = Choices()
for mdl in ndb_models.ProgramType.query().order(ndb_models.ProgramType.name):
choices.choice.append(Choice(id=0, string_id=mdl.key.string_id(), label=mdl.name)) # using 0 as ID since this model actually has a string key.
return choices
application = service.service_mapping(ChoicesApi, r'/choices_api')
| {
"repo_name": "babybunny/rebuildingtogethercaptain",
"path": "gae/room/choices_api.py",
"copies": "1",
"size": "3865",
"license": "apache-2.0",
"hash": 1756094793566068700,
"line_mean": 34.4587155963,
"line_max": 150,
"alpha_frac": 0.7042690815,
"autogenerated": false,
"ratio": 3.4355555555555557,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9587058612336447,
"avg_score": 0.010553204943821835,
"num_lines": 109
} |
"""API for communicating with twitch"""
from __future__ import absolute_import
import functools
import logging
import os
import threading
import m3u8
import oauthlib.oauth2
import requests
import requests.utils
import requests_oauthlib
from pytwitcherapi.chat import client
from . import constants, exceptions, models, oauth
__all__ = ['needs_auth', 'TwitchSession']
log = logging.getLogger(__name__)
TWITCH_KRAKENURL = 'https://api.twitch.tv/kraken/'
"""The baseurl for the twitch api"""
TWITCH_HEADER_ACCEPT = 'application/vnd.twitchtv.v3+json'
"""The header for the ``Accept`` key to tell twitch which api version it should use"""
TWITCH_USHERURL = 'http://usher.twitch.tv/api/'
"""The baseurl for the twitch usher api"""
TWITCH_APIURL = 'http://api.twitch.tv/api/'
"""The baseurl for the old twitch api"""
TWITCH_STATUSURL = 'http://twitchstatus.com/api/status?type=chat'
AUTHORIZATION_BASE_URL = 'https://api.twitch.tv/kraken/oauth2/authorize'
"""Authorisation Endpoint"""
CLIENT_ID = os.environ.get("PYTWITCHER_CLIENT_ID") or '642a2vtmqfumca8hmfcpkosxlkmqifb'
"""The client id of pytwitcher on twitch.
Use environment variable ``PYTWITCHER_CLIENT_ID`` or pytwitcher default value.
"""
SCOPES = ['user_read', 'chat_login']
"""The scopes that PyTwitcher needs"""
def needs_auth(meth):
"""Wraps a method of :class:`TwitchSession` and
raises an :class:`exceptions.NotAuthorizedError`
if before calling the method, the session isn't authorized.
:param meth:
:type meth:
:returns: the wrapped method
:rtype: Method
:raises: None
"""
@functools.wraps(meth)
def wrapped(*args, **kwargs):
if not args[0].authorized:
raise exceptions.NotAuthorizedError('Please login first!')
return meth(*args, **kwargs)
return wrapped
class OAuthSession(requests_oauthlib.OAuth2Session):
"""Session with oauth2 support.
You can still use http requests.
"""
def __init__(self):
"""Initialize a new oauth session
:raises: None
"""
client = oauth.TwitchOAuthClient(client_id=CLIENT_ID)
super(OAuthSession, self).__init__(client_id=CLIENT_ID,
client=client,
scope=SCOPES,
redirect_uri=constants.REDIRECT_URI)
self.login_server = None
"""The server that handles the login redirect"""
self.login_thread = None
"""The thread that serves the login server"""
def request(self, method, url, **kwargs):
"""Constructs a :class:`requests.Request`, prepares it and sends it.
Raises HTTPErrors by default.
:param method: method for the new :class:`Request` object.
:type method: :class:`str`
:param url: URL for the new :class:`Request` object.
:type url: :class:`str`
:param kwargs: keyword arguments of :meth:`requests.Session.request`
:returns: a resonse object
:rtype: :class:`requests.Response`
:raises: :class:`requests.HTTPError`
"""
if oauthlib.oauth2.is_secure_transport(url):
m = super(OAuthSession, self).request
else:
m = super(requests_oauthlib.OAuth2Session, self).request
log.debug("%s \"%s\" with %s", method, url, kwargs)
response = m(method, url, **kwargs)
response.raise_for_status()
return response
def start_login_server(self, ):
"""Start a server that will get a request from a user logging in.
This uses the Implicit Grant Flow of OAuth2. The user is asked
to login to twitch and grant PyTwitcher authorization.
Once the user agrees, he is redirected to an url.
This server will respond to that url and get the oauth token.
The server serves in another thread. To shut him down, call
:meth:`TwitchSession.shutdown_login_server`.
This sets the :data:`TwitchSession.login_server`,
:data:`TwitchSession.login_thread` variables.
:returns: The created server
:rtype: :class:`BaseHTTPServer.HTTPServer`
:raises: None
"""
self.login_server = oauth.LoginServer(session=self)
target = self.login_server.serve_forever
self.login_thread = threading.Thread(target=target)
self.login_thread.setDaemon(True)
log.debug('Starting login server thread.')
self.login_thread.start()
def shutdown_login_server(self, ):
"""Shutdown the login server and thread
:returns: None
:rtype: None
:raises: None
"""
log.debug('Shutting down the login server thread.')
self.login_server.shutdown()
self.login_server.server_close()
self.login_thread.join()
def get_auth_url(self, ):
"""Return the url for the user to authorize PyTwitcher
:returns: The url the user should visit to authorize PyTwitcher
:rtype: :class:`str`
:raises: None
"""
return self.authorization_url(AUTHORIZATION_BASE_URL)[0]
class TwitchSession(OAuthSession):
"""Session for making requests to the twitch api
Use :meth:`TwitchSession.kraken_request`,
:meth:`TwitchSession.usher_request`,
:meth:`TwitchSession.oldapi_request` to make easier calls to the api
directly.
To get authorization, the user has to grant PyTwitcher access.
The workflow goes like this:
1. Start the login server with :meth:`TwitchSession.start_login_server`.
2. User should visit :meth:`TwitchSession.get_auth_url` in his
browser and follow insturctions (e.g Login and Allow PyTwitcher).
3. Check if the session is authorized with :meth:`TwitchSession.authorized`.
4. Shut the login server down with :meth:`TwitchSession.shutdown_login_server`.
Now you can use methods that need authorization.
"""
def __init__(self):
"""Initialize a new TwitchSession
:raises: None
"""
super(TwitchSession, self).__init__()
self.baseurl = ''
"""The baseurl that gets prepended to every request url"""
self.current_user = None
"""The currently logined user."""
self._token = None
"""The oauth token"""
@property
def token(self, ):
"""Return the oauth token
:returns: the token
:rtype: :class:`dict`
:raises: None
"""
return self._token
@token.setter
def token(self, token):
"""Set the oauth token and the current_user
:param token: the oauth token
:type token: :class:`dict`
:returns: None
:rtype: None
:raises: None
"""
self._token = token
if token:
self.current_user = self.query_login_user()
def kraken_request(self, method, endpoint, **kwargs):
"""Make a request to one of the kraken api endpoints.
Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`.
Also the client id from :data:`CLIENT_ID` will be set.
The url will be constructed of :data:`TWITCH_KRAKENURL` and
the given endpoint.
:param method: the request method
:type method: :class:`str`
:param endpoint: the endpoint of the kraken api.
The base url is automatically provided.
:type endpoint: :class:`str`
:param kwargs: keyword arguments of :meth:`requests.Session.request`
:returns: a resonse object
:rtype: :class:`requests.Response`
:raises: :class:`requests.HTTPError`
"""
url = TWITCH_KRAKENURL + endpoint
headers = kwargs.setdefault('headers', {})
headers['Accept'] = TWITCH_HEADER_ACCEPT
headers['Client-ID'] = CLIENT_ID # https://github.com/justintv/Twitch-API#rate-limits
return self.request(method, url, **kwargs)
def usher_request(self, method, endpoint, **kwargs):
"""Make a request to one of the usher api endpoints.
The url will be constructed of :data:`TWITCH_USHERURL` and
the given endpoint.
:param method: the request method
:type method: :class:`str`
:param endpoint: the endpoint of the usher api.
The base url is automatically provided.
:type endpoint: :class:`str`
:param kwargs: keyword arguments of :meth:`requests.Session.request`
:returns: a resonse object
:rtype: :class:`requests.Response`
:raises: :class:`requests.HTTPError`
"""
url = TWITCH_USHERURL + endpoint
return self.request(method, url, **kwargs)
def oldapi_request(self, method, endpoint, **kwargs):
"""Make a request to one of the old api endpoints.
The url will be constructed of :data:`TWITCH_APIURL` and
the given endpoint.
:param method: the request method
:type method: :class:`str`
:param endpoint: the endpoint of the old api.
The base url is automatically provided.
:type endpoint: :class:`str`
:param kwargs: keyword arguments of :meth:`requests.Session.request`
:returns: a resonse object
:rtype: :class:`requests.Response`
:raises: :class:`requests.HTTPError`
"""
headers = kwargs.setdefault('headers', {})
headers['Client-ID'] = CLIENT_ID # https://github.com/justintv/Twitch-API#rate-limits
url = TWITCH_APIURL + endpoint
return self.request(method, url, **kwargs)
def fetch_viewers(self, game):
"""Query the viewers and channels of the given game and
set them on the object
:returns: the given game
:rtype: :class:`models.Game`
:raises: None
"""
r = self.kraken_request('GET', 'streams/summary',
params={'game': game.name}).json()
game.viewers = r['viewers']
game.channels = r['channels']
return game
def search_games(self, query, live=True):
"""Search for games that are similar to the query
:param query: the query string
:type query: :class:`str`
:param live: If true, only returns games that are live on at least one
channel
:type live: :class:`bool`
:returns: A list of games
:rtype: :class:`list` of :class:`models.Game` instances
:raises: None
"""
r = self.kraken_request('GET', 'search/games',
params={'query': query,
'type': 'suggest',
'live': live})
games = models.Game.wrap_search(r)
for g in games:
self.fetch_viewers(g)
return games
def top_games(self, limit=10, offset=0):
"""Return the current top games
:param limit: the maximum amount of top games to query
:type limit: :class:`int`
:param offset: the offset in the top games
:type offset: :class:`int`
:returns: a list of top games
:rtype: :class:`list` of :class:`models.Game`
:raises: None
"""
r = self.kraken_request('GET', 'games/top',
params={'limit': limit,
'offset': offset})
return models.Game.wrap_topgames(r)
def get_game(self, name):
"""Get the game instance for a game name
:param name: the name of the game
:type name: :class:`str`
:returns: the game instance
:rtype: :class:`models.Game` | None
:raises: None
"""
games = self.search_games(query=name, live=False)
for g in games:
if g.name == name:
return g
def get_channel(self, name):
"""Return the channel for the given name
:param name: the channel name
:type name: :class:`str`
:returns: the model instance
:rtype: :class:`models.Channel`
:raises: None
"""
r = self.kraken_request('GET', 'channels/' + name)
return models.Channel.wrap_get_channel(r)
def search_channels(self, query, limit=25, offset=0):
"""Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of channels
:rtype: :class:`list` of :class:`models.Channel` instances
:raises: None
"""
r = self.kraken_request('GET', 'search/channels',
params={'query': query,
'limit': limit,
'offset': offset})
return models.Channel.wrap_search(r)
def get_stream(self, channel):
"""Return the stream of the given channel
:param channel: the channel that is broadcasting.
Either name or models.Channel instance
:type channel: :class:`str` | :class:`models.Channel`
:returns: the stream or None, if the channel is offline
:rtype: :class:`models.Stream` | None
:raises: None
"""
if isinstance(channel, models.Channel):
channel = channel.name
r = self.kraken_request('GET', 'streams/' + channel)
return models.Stream.wrap_get_stream(r)
def get_streams(self, game=None, channels=None, limit=25, offset=0):
"""Return a list of streams queried by a number of parameters
sorted by number of viewers descending
:param game: the game or name of the game
:type game: :class:`str` | :class:`models.Game`
:param channels: list of models.Channels or channel names (can be mixed)
:type channels: :class:`list` of :class:`models.Channel` or :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of streams
:rtype: :class:`list` of :class:`models.Stream`
:raises: None
"""
if isinstance(game, models.Game):
game = game.name
channelnames = []
cparam = None
if channels:
for c in channels:
if isinstance(c, models.Channel):
c = c.name
channelnames.append(c)
cparam = ','.join(channelnames)
params = {'limit': limit,
'offset': offset,
'game': game,
'channel': cparam}
r = self.kraken_request('GET', 'streams', params=params)
return models.Stream.wrap_search(r)
def search_streams(self, query, hls=False, limit=25, offset=0):
"""Search for streams and return them
:param query: the query string
:type query: :class:`str`
:param hls: If true, only return streams that have hls stream
:type hls: :class:`bool`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of streams
:rtype: :class:`list` of :class:`models.Stream` instances
:raises: None
"""
r = self.kraken_request('GET', 'search/streams',
params={'query': query,
'hls': hls,
'limit': limit,
'offset': offset})
return models.Stream.wrap_search(r)
@needs_auth
def followed_streams(self, limit=25, offset=0):
"""Return the streams the current user follows.
Needs authorization ``user_read``.
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of streams
:rtype: :class:`list`of :class:`models.Stream` instances
:raises: :class:`exceptions.NotAuthorizedError`
"""
r = self.kraken_request('GET', 'streams/followed',
params={'limit': limit,
'offset': offset})
return models.Stream.wrap_search(r)
def get_user(self, name):
"""Get the user for the given name
:param name: The username
:type name: :class:`str`
:returns: the user instance
:rtype: :class:`models.User`
:raises: None
"""
r = self.kraken_request('GET', 'user/' + name)
return models.User.wrap_get_user(r)
@needs_auth
def query_login_user(self, ):
"""Query and return the currently logined user
:returns: The user instance
:rtype: :class:`models.User`
:raises: :class:`exceptions.NotAuthorizedError`
"""
r = self.kraken_request('GET', 'user')
return models.User.wrap_get_user(r)
def get_playlist(self, channel):
"""Return the playlist for the given channel
:param channel: the channel
:type channel: :class:`models.Channel` | :class:`str`
:returns: the playlist
:rtype: :class:`m3u8.M3U8`
:raises: :class:`requests.HTTPError` if channel is offline.
"""
if isinstance(channel, models.Channel):
channel = channel.name
token, sig = self.get_channel_access_token(channel)
params = {'token': token, 'sig': sig,
'allow_audio_only': True,
'allow_source': True}
r = self.usher_request(
'GET', 'channel/hls/%s.m3u8' % channel, params=params)
playlist = m3u8.loads(r.text)
return playlist
def get_quality_options(self, channel):
"""Get the available quality options for streams of the given channel
Possible values in the list:
* source
* high
* medium
* low
* mobile
* audio
:param channel: the channel or channel name
:type channel: :class:`models.Channel` | :class:`str`
:returns: list of quality options
:rtype: :class:`list` of :class:`str`
:raises: :class:`requests.HTTPError` if channel is offline.
"""
optionmap = {'chunked': 'source',
'high': 'high',
'medium': 'medium',
'low': 'low',
'mobile': 'mobile',
'audio_only': 'audio'}
p = self.get_playlist(channel)
options = []
for pl in p.playlists:
q = pl.media[0].group_id
options.append(optionmap[q])
return options
def get_channel_access_token(self, channel):
"""Return the token and sig for the given channel
:param channel: the channel or channel name to get the access token for
:type channel: :class:`channel` | :class:`str`
:returns: The token and sig for the given channel
:rtype: (:class:`unicode`, :class:`unicode`)
:raises: None
"""
if isinstance(channel, models.Channel):
channel = channel.name
r = self.oldapi_request(
'GET', 'channels/%s/access_token' % channel).json()
return r['token'], r['sig']
def get_chat_server(self, channel):
"""Get an appropriate chat server for the given channel
Usually the server is irc.twitch.tv. But because of the delicate
twitch chat, they use a lot of servers. Big events are on special
event servers. This method tries to find a good one.
:param channel: the channel with the chat
:type channel: :class:`models.Channel`
:returns: the server address and port
:rtype: (:class:`str`, :class:`int`)
:raises: None
"""
r = self.oldapi_request(
'GET', 'channels/%s/chat_properties' % channel.name)
json = r.json()
servers = json['chat_servers']
try:
r = self.get(TWITCH_STATUSURL)
except requests.HTTPError:
log.debug('Error getting chat server status. Using random one.')
address = servers[0]
else:
stats = [client.ChatServerStatus(**d) for d in r.json()]
address = self._find_best_chat_server(servers, stats)
server, port = address.split(':')
return server, int(port)
@staticmethod
def _find_best_chat_server(servers, stats):
"""Find the best from servers by comparing with the stats
:param servers: a list if server adresses, e.g. ['0.0.0.0:80']
:type servers: :class:`list` of :class:`str`
:param stats: list of server statuses
:type stats: :class:`list` of :class:`chat.ChatServerStatus`
:returns: the best server adress
:rtype: :class:`str`
:raises: None
"""
best = servers[0] # In case we sind no match with any status
stats.sort() # gets sorted for performance
for stat in stats:
for server in servers:
if server == stat:
# found a chatserver that has the same address
# than one of the chatserverstats.
# since the stats are sorted for performance
# the first hit is the best, thus break
best = server
break
if best:
# already found one, so no need to check the other
# statuses, which are worse
break
return best
def get_emote_picture(self, emote, size=1.0):
"""Return the picture for the given emote
:param emote: the emote object
:type emote: :class:`pytwitcherapi.chat.message.Emote`
:param size: the size of the picture.
Choices are: 1.0, 2.0, 3.0
:type size: :class:`float`
:returns: A string resembling the picturedata of the emote
:rtype: :class:`str`
:raises: None
"""
r = self.get('http://static-cdn.jtvnw.net/emoticons/v1/%s/%s' %
(emote.emoteid, size))
return r.content
| {
"repo_name": "Pytwitcher/pytwitcherapi",
"path": "src/pytwitcherapi/session.py",
"copies": "1",
"size": "22538",
"license": "bsd-3-clause",
"hash": 8644238967886432000,
"line_mean": 34.7179080824,
"line_max": 94,
"alpha_frac": 0.5796432691,
"autogenerated": false,
"ratio": 4.123307720453714,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000146240853547808,
"num_lines": 631
} |
"""API for converting notebooks between versions.
Authors:
* Jonathan Frederic
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import re
from .reader import get_version, versions
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
def convert(nb, to_version):
"""Convert a notebook node object to a specific version. Assumes that
all the versions starting from 1 to the latest major X are implemented.
In other words, there should never be a case where v1 v2 v3 v5 exist without
a v4. Also assumes that all conversions can be made in one step increments
between major versions and ignores minor revisions.
Parameters
----------
nb : NotebookNode
to_version : int
Major revision to convert the notebook to. Can either be an upgrade or
a downgrade.
"""
# Get input notebook version.
(version, version_minor) = get_version(nb)
# Check if destination is current version, if so return contents
if version == to_version:
return nb
# If the version exist, try to convert to it one step at a time.
elif to_version in versions:
# Get the the version that this recursion will convert to as a step
# closer to the final revision. Make sure the newer of the conversion
# functions is used to perform the conversion.
if to_version > version:
step_version = version + 1
convert_function = versions[step_version].upgrade
else:
step_version = version - 1
convert_function = versions[version].downgrade
# Convert and make sure version changed during conversion.
converted = convert_function(nb)
if converted.get('nbformat', 1) == version:
raise Exception("Cannot convert notebook from v%d to v%d. Operation" \
"failed silently." % (version, step_version))
# Recursively convert until target version is reached.
return convert(converted, to_version)
else:
raise Exception("Cannot convert notebook to v%d because that " \
"version doesn't exist" % (to_version))
| {
"repo_name": "omni5cience/django-inlineformfield",
"path": ".tox/py27/lib/python2.7/site-packages/IPython/nbformat/convert.py",
"copies": "5",
"size": "2732",
"license": "mit",
"hash": 1889385691755160800,
"line_mean": 36.9444444444,
"line_max": 83,
"alpha_frac": 0.5479502196,
"autogenerated": false,
"ratio": 5.223709369024856,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8271659588624856,
"avg_score": null,
"num_lines": null
} |
"""API for converting notebooks between versions."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from . import versions
from .reader import get_version
def convert(nb, to_version):
"""Convert a notebook node object to a specific version. Assumes that
all the versions starting from 1 to the latest major X are implemented.
In other words, there should never be a case where v1 v2 v3 v5 exist without
a v4. Also assumes that all conversions can be made in one step increments
between major versions and ignores minor revisions.
Parameters
----------
nb : NotebookNode
to_version : int
Major revision to convert the notebook to. Can either be an upgrade or
a downgrade.
"""
# Get input notebook version.
(version, version_minor) = get_version(nb)
# Check if destination is target version, if so return contents
if version == to_version:
return nb
# If the version exist, try to convert to it one step at a time.
elif to_version in versions:
# Get the the version that this recursion will convert to as a step
# closer to the final revision. Make sure the newer of the conversion
# functions is used to perform the conversion.
if to_version > version:
step_version = version + 1
convert_function = versions[step_version].upgrade
else:
step_version = version - 1
convert_function = versions[version].downgrade
# Convert and make sure version changed during conversion.
converted = convert_function(nb)
if converted.get('nbformat', 1) == version:
raise ValueError(
"Failed to convert notebook from v%d to v%d." % (version, step_version))
# Recursively convert until target version is reached.
return convert(converted, to_version)
else:
raise ValueError("Cannot convert notebook to v%d because that "
"version doesn't exist" % (to_version))
| {
"repo_name": "mattvonrocketstein/smash",
"path": "smashlib/ipy3x/nbformat/converter.py",
"copies": "1",
"size": "2089",
"license": "mit",
"hash": 1547452902976355600,
"line_mean": 36.9818181818,
"line_max": 88,
"alpha_frac": 0.6596457635,
"autogenerated": false,
"ratio": 4.6114790286975715,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5771124792197572,
"avg_score": null,
"num_lines": null
} |
"""API for creating a contract and configuring the mock service."""
from __future__ import unicode_literals
import fnmatch
import os
from subprocess import Popen
from .constants import BROKER_CLIENT_PATH
import logging
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class Broker():
"""PactBroker helper functions."""
def __init__(self, broker_base_url=None, broker_username=None, broker_password=None, broker_token=None):
"""
Create a Broker instance.
:param broker_base_url: URL of the pact broker that pacts will be
published to. Can also be supplied through the PACT_BROKER_BASE_URL
environment variable. Defaults to None.
:type broker_base_url: str
:param broker_username: Username to use when connecting to the pact
broker if authentication is required. Can also be supplied through
the PACT_BROKER_USERNAME environment variable. Defaults to None.
:type broker_username: str
:param broker_password: Password to use when connecting to the pact
broker if authentication is required. Strongly recommend supplying
this value through the PACT_BROKER_PASSWORD environment variable
instead. Defaults to None.
:type broker_password: str
:param broker_token: Authentication token to use when connecting to
the pact broker. Strongly recommend supplying this value through
the PACT_BROKER_TOKEN environment variable instead.
Defaults to None.
"""
self.broker_base_url = broker_base_url
self.broker_username = broker_username
self.broker_password = broker_password
self.broker_token = broker_token
def _get_broker_base_url(self):
return self.broker_base_url or os.environ["PACT_BROKER_BASE_URL"]
@staticmethod
def _normalize_consumer_name(name):
return name.lower().replace(' ', '_')
def publish(self, consumer_name, version, pact_dir=None,
tag_with_git_branch=None, consumer_tags=None):
"""Publish the generated pact files to the specified pact broker."""
if self.broker_base_url is None \
and "PACT_BROKER_BASE_URL" not in os.environ:
raise RuntimeError("No pact broker URL specified. "
+ "Did you expect the PACT_BROKER_BASE_URL "
+ "environment variable to be set?")
pact_files = fnmatch.filter(
os.listdir(pact_dir),
self._normalize_consumer_name(consumer_name) + '*.json'
)
pact_files = list(map(lambda pact_file: f'{pact_dir}/{pact_file}', pact_files))
command = [
BROKER_CLIENT_PATH,
'publish',
'--consumer-app-version={}'.format(version)]
command.append('--broker-base-url={}'.format(self._get_broker_base_url()))
if self.broker_username is not None:
command.append('--broker-username={}'.format(self.broker_username))
if self.broker_password is not None:
command.append('--broker-password={}'.format(self.broker_password))
if self.broker_token is not None:
command.append('--broker-token={}'.format(self.broker_token))
command.extend(pact_files)
if tag_with_git_branch:
command.append('--tag-with-git-branch')
if consumer_tags is not None:
for tag in consumer_tags:
command.extend(['-t', tag])
print(f"PactBroker command: {command}")
publish_process = Popen(command)
publish_process.wait()
if publish_process.returncode != 0:
url = self._get_broker_base_url()
raise RuntimeError(
f"There was an error while publishing to the pact broker at {url}.")
| {
"repo_name": "pact-foundation/pact-python",
"path": "pact/broker.py",
"copies": "1",
"size": "3886",
"license": "mit",
"hash": 4044650490175195600,
"line_mean": 39.9052631579,
"line_max": 108,
"alpha_frac": 0.6276376737,
"autogenerated": false,
"ratio": 4.27032967032967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.539796734402967,
"avg_score": null,
"num_lines": null
} |
"""API for creating a contract and configuring the mock service."""
from __future__ import unicode_literals
import json
import os
from subprocess import Popen
from .broker import Broker
from .constants import MESSAGE_PATH
class MessagePact(Broker):
"""
Represents a contract between a consumer and provider using messages.
Provides Python context handler to perform tests on a Python consumer. For example:
>>> from pact import MessageConsumer, Provider
>>> pact = MessageConsumer('MyMessageConsumer').has_pact_with(Provider('provider'))
>>> (pact
... .given({"name": "Test provider"}])
... .expects_to_receive('Test description')
... .with_content({'name': 'John', 'document_name': 'sample_document.doc'})
... .with_metadata({'contentType': 'application/json'}))
>>> with pact:
... handler(event, context)
"""
MANDATORY_FIELDS = {"providerStates", "description", "contents", "metaData"}
def __init__(
self,
consumer,
provider,
publish_to_broker=False,
broker_base_url=None,
broker_username=None,
broker_password=None,
broker_token=None,
pact_dir=None,
version='3.0.0',
file_write_mode="merge",
):
"""
Create a Pact instance using messages.
:param consumer: A consumer for this contract that uses messages.
:type consumer: pact.MessageConsumer
:param provider: The generic provider for this contract.
:type provider: pact.Provider
:param publish_to_broker: Flag to control automatic publishing of
pacts to a pact broker. Defaults to False.
:type publish_to_broker: bool
:param broker_base_url: URL of the pact broker that pacts will be
published to. Can also be supplied through the PACT_BROKER_BASE_URL
environment variable. Defaults to None.
:type broker_base_url: str
:param broker_username: Username to use when connecting to the pact
broker if authentication is required. Can also be supplied through
the PACT_BROKER_USERNAME environment variable. Defaults to None.
:type broker_username: str
:param broker_password: Password to use when connecting to the pact
broker if authentication is required. Strongly recommend supplying
this value through the PACT_BROKER_PASSWORD environment variable
instead. Defaults to None.
:type broker_password: str
:param broker_token: Authentication token to use when connecting to
the pact broker. Strongly recommend supplying this value through
the PACT_BROKER_TOKEN environment variable instead.
Defaults to None.
:type broker_token: str
:param pact_dir: Directory where the resulting pact files will be
written. Defaults to the current directory.
:type pact_dir: str
:param version: The Pact Specification version to use, defaults to
'3.0.0'.
:type version: str
:param file_write_mode: `overwrite` or `merge`. Use `merge` when
running multiple mock service instances in parallel for the same
consumer/provider pair. Ensure the pact file is deleted before
running tests when using this option so that interactions deleted
from the code are not maintained in the file. Defaults to
`merge`.
:type file_write_mode: str
"""
super().__init__(
broker_base_url, broker_username, broker_password, broker_token
)
self.consumer = consumer
self.file_write_mode = file_write_mode
self.pact_dir = pact_dir or os.getcwd()
self.provider = provider
self.publish_to_broker = publish_to_broker
self.version = version
self._process = None
self._messages = []
self._message_process = None
def given(self, provider_states):
"""
Define the provider state for this pact.
When the provider verifies this contract, they will use this field to
setup pre-defined data that will satisfy the response expectations.
:param provider_state: The short sentence that is unique to describe
the provider state for this contract.
:type provider_state: basestring
:rtype: Pact
"""
self._insert_message_if_complete()
state = [{"name": "{}".format(provider_states)}]
self._messages[0]['providerStates'] = state
return self
def with_metadata(self, metadata):
"""
Define metadata attached to the message.
:param metadata: dictionary of metadata attached to the message.
:type metadata: dict or None
:rtype: Pact
"""
self._insert_message_if_complete()
self._messages[0]['metaData'] = metadata
return self
def with_content(self, contents):
"""
Define message content (event) that will be use in the message.
:param contents: dictionary of dictionary used in the message.
:type metadata: dict
:rtype: Pact
"""
self._insert_message_if_complete()
self._messages[0]['contents'] = contents
return self
def expects_to_receive(self, description):
"""
Define the name of this contract (Same as upon_receiving in http pact implementation).
:param scenario: A unique name for this contract.
:type scenario: basestring
:rtype: Pact
"""
self._insert_message_if_complete()
self._messages[0]['description'] = description
return self
def write_to_pact_file(self):
"""
Create a pact file based on provided attributes in DSL.
Return 0 if success, 1 otherwise.
:rtype: int
"""
command = [
MESSAGE_PATH,
"update",
json.dumps(self._messages[0]),
"--pact-dir", self.pact_dir,
f"--pact-specification-version={self.version}",
"--consumer", f"{self.consumer.name}_message",
"--provider", f"{self.provider.name}_message",
]
self._message_process = Popen(command)
def _insert_message_if_complete(self):
"""
Insert a new message if current message is complete.
An interaction is complete if it has all the mandatory fields.
If there are no message, a new message will be added.
:rtype: None
"""
if not self._messages:
self._messages.append({})
elif all(field in self._messages[0] for field in self.MANDATORY_FIELDS):
self._messages.insert(0, {})
def __enter__(self):
"""Enter a Python context. This function is required for context manager to work."""
pass
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Exit a Python context.
Calls pact-message to write out the contracts to disk.
"""
if (exc_type, exc_val, exc_tb) != (None, None, None):
return
self.write_to_pact_file()
if self.publish_to_broker:
self.publish(
self.consumer.name,
self.consumer.version,
pact_dir=self.pact_dir,
tag_with_git_branch=self.consumer.tag_with_git_branch,
consumer_tags=self.consumer.tags,
)
| {
"repo_name": "pact-foundation/pact-python",
"path": "pact/message_pact.py",
"copies": "1",
"size": "7511",
"license": "mit",
"hash": -3083549231720489500,
"line_mean": 34.9377990431,
"line_max": 94,
"alpha_frac": 0.6113699907,
"autogenerated": false,
"ratio": 4.444378698224852,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003286968168109128,
"num_lines": 209
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.