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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ae4c9670b68771f35af5acc4c3578cfdcd7c4ef | 478422b7042926f243a6dcfa90d9c8640e37ec83 | /PyAlgoTradeCN/01_SamplesFromPyAlgoTradeCN/stratlib/thrSMA_live.py | 952ac0bff90d021982742eb2af5b50f33f4102fc | [
"MIT"
] | permissive | JohnnyDankseed/midProjects | c70e4c19680af50c1a3869726cca4e9ea2cd4de7 | ed6086e74f68b1b89f725abe0b270e67cf8993a8 | refs/heads/master | 2021-06-03T05:24:32.691310 | 2016-07-25T17:13:04 | 2016-07-25T17:13:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,764 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 03 13:06:56 2015
@author: Eunice
"""
if __name__ == '__main__':
import sys
sys.path.append("..")
from pyalgotrade import bar
from pyalgotrade import plotter
# 以上模块仅测试用
from pyalgotrade.broker.fillstrategy import DefaultStrategy
from pyalgotrade.broker.backtesting import TradePercentage
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
class thrSMA(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, short_l, mid_l, long_l, up_cum):
strategy.BacktestingStrategy.__init__(self, feed)
self.__instrument = instrument
self.getBroker().setFillStrategy(DefaultStrategy(None))
self.getBroker().setCommission(TradePercentage(0.001))
self.__position = None
self.__prices = feed[instrument].getPriceDataSeries()
self.__malength1 = int(short_l)
self.__malength2 = int(mid_l)
self.__malength3 = int(long_l)
self.__circ = int(up_cum)
self.__ma1 = ma.SMA(self.__prices, self.__malength1)
self.__ma2 = ma.SMA(self.__prices, self.__malength2)
self.__ma3 = ma.SMA(self.__prices, self.__malength3)
def getPrice(self):
return self.__prices
def getSMA(self):
return self.__ma1,self.__ma2, self.__ma3
def onEnterCanceled(self, position):
self.__position = None
def onEnterOK(self):
pass
def onExitOk(self, position):
self.__position = None
#self.info("long close")
def onExitCanceled(self, position):
self.__position.exitMarket()
def buyCon1(self):
if cross.cross_above(self.__ma1, self.__ma2) > 0:
return True
def buyCon2(self):
m1 = 0
m2 = 0
for i in range(self.__circ):
if self.__ma1[-i-1] > self.__ma3[-i-1]:
m1 += 1
if self.__ma2[-i-1] > self.__ma3[-i-1]:
m2 += 1
if m1 >= self.__circ and m2 >= self.__circ:
return True
def sellCon1(self):
if cross.cross_below(self.__ma1, self.__ma2) > 0:
return True
def onBars(self, bars):
# If a position was not opened, check if we should enter a long position.
if self.__ma2[-1]is None:
return
if self.__position is not None:
if not self.__position.exitActive() and cross.cross_below(self.__ma1, self.__ma2) > 0:
self.__position.exitMarket()
#self.info("sell %s" % (bars.getDateTime()))
if self.__position is None:
if self.buyCon1() and self.buyCon2():
shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice())
self.__position = self.enterLong(self.__instrument, shares)
print bars[self.__instrument].getDateTime(), bars[self.__instrument].getPrice()
#self.info("buy %s" % (bars.getDateTime()))
def runStratOnTushare(strat, paras, security_id, market, frequency):
import sys,os
path = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir,'tushare'))
sys.path.append(path)
from barfeed import TuShareLiveFeed
liveFeed = TuShareLiveFeed([security_id], frequency, 1024, 20)
strat = strat(liveFeed, security_id, *paras)
strat.run()
if __name__ == "__main__":
strat = thrSMA
security_id = '000001'
market = 'SZ'
frequency = bar.Frequency.MINUTE
paras = [2, 20, 60, 10]
runStratOnTushare(strat, paras, security_id, market, frequency)
| [
"upsea@upsea.cn"
] | upsea@upsea.cn |
83ab91127cfd012ac6082da0ab35a359b9d36368 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2535/60647/283667.py | 9ed53c7cab12facc604a276ec4facf9ffd08731e | [] | 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 | 534 | py | list=input()
#如果从这个数开始,每一个数都比前一个大, 则加一
def num(a,list):
for i in range(len(list)):
if int(list[i])<int(a):
return False
return True
max=0
list1=[]
res=1
for i in range(len(list)):
if int(list[i])>=max:
if i==len(list)-1:
res+=1
else:
max=int(list[i])
list1=[]
for j in range(i,len(list)):
list1.append(list[j])
if num(max,list1):
res+=1
print(res)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
b1e51b9190495225dce3a0f41da983608c9957cf | 5864e86954a221d52d4fa83a607c71bacf201c5a | /carbon/common/script/entities/Spawners/encounterSpawner.py | 4d5bb3f2a0bdebce0ec3d76e2e5daec0453da68f | [] | no_license | connoryang/1v1dec | e9a2303a01e5a26bf14159112b112be81a6560fd | 404f2cebf13b311e754d45206008918881496370 | refs/heads/master | 2021-05-04T02:34:59.627529 | 2016-10-19T08:56:26 | 2016-10-19T08:56:26 | 71,334,417 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | #Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\carbon\common\script\entities\Spawners\encounterSpawner.py
from carbon.common.script.entities.Spawners.runtimeSpawner import RuntimeSpawner
class EncounterSpawner(RuntimeSpawner):
__guid__ = 'cef.EncounterSpawner'
| [
"le02005@163.com"
] | le02005@163.com |
d00a29e77a591aa61625df863e903de88e36ea7c | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03213/s787167232.py | 875bd7ad591f6ef540a3b100a4dfaa4648a17478 | [] | 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 | 1,419 | py | #template
def inputlist(): return [int(k) for k in input().split()]
#template
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
N = int(input())
if N == 1:
print(0)
exit()
dp = [[0]*101 for _ in range(N+1)]
for i in range(2,N+1):
li = factorization(i)
n = len(li)
li0 = [0]*n
li1 = {}
for k in range(n):
li0[k] = li[k][0]
li1[li[k][0]] = li[k][1]
for j in range(2,101):
if j in li0:
dp[i][j] = dp[i-1][j] + li1[j]
continue
dp[i][j] = dp[i-1][j]
li = dp[N]
li.sort()
from bisect import bisect_right
indexa = bisect_right(li,0)
lia = li[indexa:]
na = len(lia)
c2 = 0
c4 = 0
c14 = 0
c24 = 0
c74 = 0
for i in range(na):
if lia[i] >= 2:
c2+=1
if lia[i] >= 4:
c4+=1
if lia[i] >= 14:
c14 +=1
if lia[i] >= 24:
c24+=1
if lia[i] >= 74:
c74+=1
d4_2 = c2-c4
d14_4 = c4 - c14
d24_2 = c2 - c24
def comb2(i):
return i*(i-1)//2
def comb3(i):
return i*(i-1)*(i-2)//6
ans = d4_2*comb2(c4) + 3*comb3(c4) + d14_4*c14 + 2*comb2(c14) + d24_2*c24 + 2*comb2(c24) +c74
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
f0e99347c8713ef9c69c0f8b8fe5543221c7f17f | e3b9aa9b17ebb55e53dbc4fa9d1f49c3a56c6488 | /red_canary/komand_red_canary/actions/create_activity_monitor/action.py | 73804a2de359e817432441c993f2c0436e600e90 | [
"MIT"
] | permissive | OSSSP/insightconnect-plugins | ab7c77f91c46bd66b10db9da1cd7571dfc048ab7 | 846758dab745170cf1a8c146211a8bea9592e8ff | refs/heads/master | 2023-04-06T23:57:28.449617 | 2020-03-18T01:24:28 | 2020-03-18T01:24:28 | 248,185,529 | 1 | 0 | MIT | 2023-04-04T00:12:18 | 2020-03-18T09:14:53 | null | UTF-8 | Python | false | false | 954 | py | import komand
from .schema import CreateActivityMonitorInput, CreateActivityMonitorOutput
# Custom imports below
class CreateActivityMonitor(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='create_activity_monitor',
description='Creates a new activity monitor',
input=CreateActivityMonitorInput(),
output=CreateActivityMonitorOutput())
def run(self, params={}):
activity_monitor = self.connection.api.create_activity_monitor(
params.get('name'),
params.get('type', 'file_modification'),
params.get('active', True),
params.get('file_modification_types_monitored', []),
params.get('file_paths_monitored', []),
params.get('usernames_matched', []),
params.get('usernames_excluded', []),
)
return {'activity_monitor': activity_monitor}
| [
"jonschipp@gmail.com"
] | jonschipp@gmail.com |
4b105aca2fcf5637f1b9c2ead4204f34d9ebdd74 | 9577a25e8dfca9d45942b739d9b24b1170dd8a0e | /groovebox/app.py | c115e123781f665800f5575ad0b3b7c5d53dac1a | [
"Apache-2.0"
] | permissive | ArchiveLabs/groovebox.org | 31a075dc55b2edc8d633b1bbe3e0017271cd808d | 62378347e7152eac68b9f6685e2e064f39c0a042 | refs/heads/master | 2021-01-18T02:08:49.728837 | 2015-10-22T00:01:33 | 2015-10-22T00:01:33 | 46,458,090 | 3 | 0 | null | 2015-11-19T01:05:43 | 2015-11-19T01:05:42 | CSS | UTF-8 | Python | false | false | 452 | py | #!/usr/bin/env python
# -*-coding: utf-8 -*-
"""
app.py
~~~~~~
:copyright: (c) 2015 by Mek
:license: see LICENSE for more details.
"""
from flask import Flask
from flask.ext.routing import router
import views
from configs import options
urls = ('/favicon.ico', views.Favicon,
'/<path:uri>', views.Base,
'/', views.Base
)
app = router(Flask(__name__), urls)
if __name__ == "__main__":
app.run(**options)
| [
"michael.karpeles@gmail.com"
] | michael.karpeles@gmail.com |
cde792f26d913f7e253f942c3f79c8b50cd05070 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03665/s533070063.py | 36f4b83274d20d183a9103fb57d80ae329081a87 | [] | 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 | 510 | py | from math import factorial
def combinations_count(n, r):
return factorial(n) // (factorial(n - r) * factorial(r))
n,p = map(int,input().split())
a = list(map(int,input().split()))
eve = 0
odd = 0
for i in range(n):
if a[i]%2==0:
eve += 1
else:
odd += 1
eve_cb = 2**eve
odd_cb1 = 0
odd_cb2 = 0
if p==1:
for i in range(1,odd+1)[::2]:
odd_cb1 += combinations_count(odd,i)
else:
for i in range(0,odd+1)[::2]:
odd_cb2 += combinations_count(odd,i)
print(eve_cb*(odd_cb1*p + odd_cb2*(1-p))) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
75b6137cb632fbf92961924ccf4818e4055d273e | 009d7750dc8636c31bd8da890bdf4be3770bfddd | /tmp/env/lib/python3.6/site-packages/tensorflow/_api/v1/compat/v1/train/experimental/__init__.py | c8952a33efd54ba1f9937e7d3a5c0e526da1988f | [
"Apache-2.0"
] | permissive | Nintendofan885/Detect_Cyberbullying_from_socialmedia | 241a5ae70405494ea5f7e393f9dac273ac2ff378 | 2f3d0a1eca0e3163565a17dcb35074e0808ed176 | refs/heads/master | 2022-11-25T18:56:27.253834 | 2020-08-03T13:16:16 | 2020-08-03T13:16:16 | 284,701,752 | 0 | 0 | NOASSERTION | 2020-08-03T13:02:06 | 2020-08-03T13:02:05 | null | UTF-8 | Python | false | false | 886 | py | # This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.train.experimental namespace.
"""
from __future__ import print_function as _print_function
from tensorflow.python.training.experimental.loss_scale import DynamicLossScale
from tensorflow.python.training.experimental.loss_scale import FixedLossScale
from tensorflow.python.training.experimental.loss_scale import LossScale
from tensorflow.python.training.experimental.loss_scale_optimizer import MixedPrecisionLossScaleOptimizer
from tensorflow.python.training.experimental.mixed_precision import disable_mixed_precision_graph_rewrite
from tensorflow.python.training.experimental.mixed_precision import enable_mixed_precision_graph_rewrite
from tensorflow.python.training.tracking.python_state import PythonState
del _print_function
| [
"e.fatma.e@gmail.com"
] | e.fatma.e@gmail.com |
bb36f1b7530eb689956bb608eb5bdb38787a27cc | 7437ecc0d856adef02ae0a84b51dd1db04fc7c79 | /matplot.py | fab461f597050c2a5afd30669263b1e5976c235b | [] | no_license | samarthdubey46/Matplotlib | 06c6e2ac1abbd125c1a3d8c0fbe6e57dce0a032b | 31fe567938a5cb5183860b723747675b3741d56b | refs/heads/master | 2022-11-18T13:57:23.610309 | 2020-07-18T11:17:14 | 2020-07-18T11:17:14 | 280,640,303 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,355 | py | from matplotlib import pyplot as plt
plt.style.use('dark_background')
#DATA
ages_x = [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]
py_dev_y = [20046, 17100, 20000, 24744, 30500, 37732, 41247, 45372, 48876, 53850, 57287, 63016, 65998, 70003, 70000, 71496, 75370, 83640, 84666,
84392, 78254, 85000, 87038, 91991, 100000, 94796, 97962, 93302, 99240, 102736, 112285, 100771, 104708, 108423, 101407, 112542, 122870, 120000]
js_dev_y = [16446, 16791, 18942, 21780, 25704, 29000, 34372, 37810, 43515, 46823, 49293, 53437, 56373, 62375, 66674, 68745, 68746, 74583, 79000,
78508, 79996, 80403, 83820, 88833, 91660, 87892, 96243, 90000, 99313, 91660, 102264, 100000, 100000, 91660, 99240, 108000, 105000, 104000]
dev_y = [17784, 16500, 18012, 20628, 25206, 30252, 34368, 38496, 42000, 46752, 49320, 53200, 56000, 62316, 64928, 67317, 68748, 73752, 77232,
78000, 78508, 79536, 82488, 88935, 90000, 90056, 95000, 90000, 91633, 91660, 98150, 98964, 100000, 98988, 100000, 108923, 105000, 103117]
plt.plot(ages_x,py_dev_y,color='b',label="Python")
plt.plot(ages_x,js_dev_y,color='r',label="JavaScript")
plt.plot(ages_x,dev_y,color='#f5c800',label="All_devs")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show() | [
"samarthdubey46@gmail.com"
] | samarthdubey46@gmail.com |
3ecba571246a2f523371be75f8e62af98fbc9f0f | bc54edd6c2aec23ccfe36011bae16eacc1598467 | /simscale_sdk/models/celllimited_gauss_linear_gradient_scheme.py | 29431b00d80dc5ff4282a783ef1a700d8721c50e | [
"MIT"
] | permissive | SimScaleGmbH/simscale-python-sdk | 4d9538d5efcadae718f12504fb2c7051bbe4b712 | 6fe410d676bf53df13c461cb0b3504278490a9bb | refs/heads/master | 2023-08-17T03:30:50.891887 | 2023-08-14T08:09:36 | 2023-08-14T08:09:36 | 331,949,105 | 17 | 5 | null | null | null | null | UTF-8 | Python | false | false | 5,471 | py | # coding: utf-8
"""
SimScale API
The version of the OpenAPI document: 0.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class CelllimitedGaussLinearGradientScheme(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_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.
"""
openapi_types = {
'type': 'str',
'limiter_coefficient': 'float'
}
attribute_map = {
'type': 'type',
'limiter_coefficient': 'limiterCoefficient'
}
def __init__(self, type='CELLLIMITED_GAUSS_LINEAR', limiter_coefficient=None, local_vars_configuration=None): # noqa: E501
"""CelllimitedGaussLinearGradientScheme - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._type = None
self._limiter_coefficient = None
self.discriminator = None
self.type = type
if limiter_coefficient is not None:
self.limiter_coefficient = limiter_coefficient
@property
def type(self):
"""Gets the type of this CelllimitedGaussLinearGradientScheme. # noqa: E501
Schema name: CelllimitedGaussLinearGradientScheme # noqa: E501
:return: The type of this CelllimitedGaussLinearGradientScheme. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this CelllimitedGaussLinearGradientScheme.
Schema name: CelllimitedGaussLinearGradientScheme # noqa: E501
:param type: The type of this CelllimitedGaussLinearGradientScheme. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and type is None: # noqa: E501
raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501
self._type = type
@property
def limiter_coefficient(self):
"""Gets the limiter_coefficient of this CelllimitedGaussLinearGradientScheme. # noqa: E501
This property defines a limiter coefficient for the scheme. 1 ensures boundedness while 0 applies no limiting. # noqa: E501
:return: The limiter_coefficient of this CelllimitedGaussLinearGradientScheme. # noqa: E501
:rtype: float
"""
return self._limiter_coefficient
@limiter_coefficient.setter
def limiter_coefficient(self, limiter_coefficient):
"""Sets the limiter_coefficient of this CelllimitedGaussLinearGradientScheme.
This property defines a limiter coefficient for the scheme. 1 ensures boundedness while 0 applies no limiting. # noqa: E501
:param limiter_coefficient: The limiter_coefficient of this CelllimitedGaussLinearGradientScheme. # noqa: E501
:type: float
"""
if (self.local_vars_configuration.client_side_validation and
limiter_coefficient is not None and limiter_coefficient > 1): # noqa: E501
raise ValueError("Invalid value for `limiter_coefficient`, must be a value less than or equal to `1`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
limiter_coefficient is not None and limiter_coefficient < 0): # noqa: E501
raise ValueError("Invalid value for `limiter_coefficient`, must be a value greater than or equal to `0`") # noqa: E501
self._limiter_coefficient = limiter_coefficient
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_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 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, CelllimitedGaussLinearGradientScheme):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, CelllimitedGaussLinearGradientScheme):
return True
return self.to_dict() != other.to_dict()
| [
"simscale"
] | simscale |
7b91548e9141af53338a31e7040127830dbfe2eb | b5ac4c1f7906bf6722ffab8b04e1aacde632b9d5 | /server/server/view.py | 174ca7df8d1faefbf616028cb5dc2c3f9c21d7df | [] | no_license | mportela/chrome_plugin | e661d4fbb26685683c067ffd0a6441d88f04766d | 2e84ba8c86e786b86d6ba8572ee28f9f3bb54f15 | refs/heads/master | 2021-01-10T06:10:57.730223 | 2016-03-15T16:40:53 | 2016-03-15T16:40:53 | 53,960,830 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 526 | py | import json
from django.http import HttpResponse
from server import models
def display(request):
return HttpResponse(models.UrlReached.objects.all().values('url','date_time'), content_type='application/json')
def process(request):
res_dict = {"true": 1}
name = str(request.GET.get('query')) # not used in this demo
current_url = str(request.GET.get('url'))
new_url = models.UrlReached(url=current_url)
new_url.save()
return HttpResponse(json.dumps(res_dict), content_type='application/json')
| [
"you@example.com"
] | you@example.com |
b5b3bdb6ee9ad2097b89fd0245c51af814711a6d | 3c4198d76240852d4abcf9b7c940927e217635b3 | /conanizer/template/test_package/conanfile.py | df0cf5cc551fc76ea950b35bd5579c4189adda39 | [
"MIT"
] | permissive | lasote/vcpkg | a3ba4b07936df4395709e4566859bea57cb4a754 | a92528a9ddf626ac640e80762e3b6dc00001812e | refs/heads/master | 2021-01-19T04:49:13.330532 | 2017-03-13T09:14:06 | 2017-03-13T09:14:06 | 69,260,019 | 3 | 2 | null | 2017-03-13T09:08:15 | 2016-09-26T14:43:08 | C++ | UTF-8 | Python | false | false | 1,459 | py | from conans import ConanFile, CMake
import os
channel = os.getenv("CONAN_CHANNEL", "vcpkg")
username = os.getenv("CONAN_USERNAME", "lasote")
class VcpkgwrapperTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "**NAME**/**VERSION**@%s/%s" % (username, channel)
generators = "cmake"
@property
def port(self):
return "**NAME**"
@property
def port_example(self):
possibles = [os.path.join("port_examples", "%s.cpp" % self.port),
os.path.join("port_examples", "%s.c" % self.port),]
for filename in possibles:
if os.path.exists(os.path.join(self.conanfile_directory, filename)):
return filename.replace("\\", "\\\\")
return None
def build(self):
cmake = CMake(self.settings)
if self.port_example:
self.run('cmake "%s" %s -DTEST_FILENAME=%s' % (self.conanfile_directory, cmake.command_line, self.port_example))
self.run("cmake --build . %s" % cmake.build_config)
else:
self.output.warn("NOT TEST PROGRAM PREPARED FOR PORT %s, please collaborate with some example in https://github.com/lasote/vcpkg" % self.port)
def imports(self):
self.copy("*.dll", "bin", "bin")
self.copy("*.dylib", "bin", "bin")
def test(self):
if self.port_example:
os.chdir("bin")
self.run(".%stest_exe.exe" % os.sep)
| [
"lasote@gmail.com"
] | lasote@gmail.com |
d9303ea004b2f1d96a416f13066197be0e531418 | 4b0c57dddf8bd98c021e0967b5d94563d15372e1 | /run_MatrixElement/test/emptyPSets/emptyPSet_STopT_T_JESDown_cfg.py | 042a3a7c8fdb4c02eb45821cf68f515dc5dea706 | [] | no_license | aperloff/TAMUWW | fea6ed0066f3f2cef4d44c525ee843c6234460ba | c18e4b7822076bf74ee919509a6bd1f3cf780e11 | refs/heads/master | 2021-01-21T14:12:34.813887 | 2018-07-23T04:59:40 | 2018-07-23T04:59:40 | 10,922,954 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 914 | py | import FWCore.ParameterSet.Config as cms
import os
#!
#! PROCESS
#!
process = cms.Process("MatrixElementProcess")
#!
#! SERVICES
#!
#process.load('Configuration.StandardSequences.Services_cff')
process.load('FWCore.MessageLogger.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 5000
process.load('CommonTools.UtilAlgos.TFileService_cfi')
process.TFileService.fileName=cms.string('STopT_T_JESDown.root')
#!
#! INPUT
#!
inputFiles = cms.untracked.vstring(
'root://cmsxrootd.fnal.gov//store/user/aperloff/MatrixElement/Summer12ME8TeV/MEInput/STopT_T_JESDown.root'
)
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(10))
process.source = cms.Source("PoolSource",
skipEvents = cms.untracked.uint32(0),
fileNames = inputFiles )
process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
| [
"aperloff@physics.tamu.edu"
] | aperloff@physics.tamu.edu |
3b9d08febc3ef5b0a1a002a405d4fddb1b6182df | 5a37472eae214d70dbe90b9dc61d03d01b8ccead | /accounts/models.py | 9e4d1366d3e2d05f7d54cc80f88b60c1a2695f51 | [] | no_license | Anuragjain20/ChatApp | 5e65d3264f27fe7bef5fdf8a9c5517220653d767 | 4db975c522a3f410a4e918e96087144e8abe7c06 | refs/heads/main | 2023-08-24T19:23:47.617916 | 2021-10-28T18:55:54 | 2021-10-28T18:55:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(User):
name = models.CharField(max_length=255)
is_verified = models.BooleanField(default=False)
def __str__(self):
return self.name | [
"anuragjain2rr@gmail.com"
] | anuragjain2rr@gmail.com |
dffdc0c909630a0d178787445594c46956598d25 | dcadfaaf6d5aca5a52b422df68a7ddef67b37ec1 | /pay-api/migrations/versions/7e51d3ce4005_statement_settings.py | 5f5f0dc12d331e69986fef93636af1629b78e6f6 | [
"Apache-2.0"
] | permissive | pwei1018/sbc-pay | ec161e2d2574272b52a7cad38a43cf68e105f855 | 137b64ab57316f0452c760488301e33be6e9bbe0 | refs/heads/development | 2022-06-08T17:36:20.226648 | 2021-04-07T17:00:42 | 2021-04-07T17:01:07 | 168,407,310 | 0 | 4 | Apache-2.0 | 2019-06-12T19:06:58 | 2019-01-30T20:05:36 | Python | UTF-8 | Python | false | false | 4,488 | py | """statement_settings
Revision ID: 7e51d3ce4005
Revises: 567df104d26c
Create Date: 2020-08-18 10:04:08.532357
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '7e51d3ce4005'
down_revision = '567df104d26c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('statement_settings',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('frequency', sa.String(length=50), nullable=True),
sa.Column('payment_account_id', sa.Integer(), nullable=True),
sa.Column('from_date', sa.Date(), nullable=False),
sa.Column('to_date', sa.Date(), nullable=False),
sa.ForeignKeyConstraint(['payment_account_id'], ['payment_account.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_statement_settings_frequency'), 'statement_settings', ['frequency'], unique=False)
op.create_index(op.f('ix_statement_settings_payment_account_id'), 'statement_settings', ['payment_account_id'],
unique=False)
op.add_column('statement', sa.Column('created_on', sa.Date(), nullable=False))
op.add_column('statement', sa.Column('statement_settings_id', sa.Integer(), nullable=True))
op.alter_column('statement', 'to_date',
existing_type=sa.DATE(),
nullable=False)
op.create_index(op.f('ix_statement_statement_settings_id'), 'statement', ['statement_settings_id'], unique=False)
op.drop_index('ix_statement_payment_account_id', table_name='statement')
op.drop_index('ix_statement_status', table_name='statement')
op.drop_constraint('statement_payment_account_id_fkey', 'statement', type_='foreignkey')
op.create_foreign_key(None, 'statement', 'statement_settings', ['statement_settings_id'], ['id'])
op.drop_column('statement', 'status')
op.drop_column('statement', 'payment_account_id')
op.add_column('statement_invoices', sa.Column('invoice_id', sa.Integer(), nullable=False))
op.drop_index('ix_statement_invoices_status', table_name='statement_invoices')
op.drop_constraint('statement_invoices_inovice_id_fkey', 'statement_invoices', type_='foreignkey')
op.create_foreign_key(None, 'statement_invoices', 'invoice', ['invoice_id'], ['id'])
op.drop_column('statement_invoices', 'status')
op.drop_column('statement_invoices', 'inovice_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('statement_invoices', sa.Column('inovice_id', sa.INTEGER(), autoincrement=False, nullable=False))
op.add_column('statement_invoices', sa.Column('status', sa.VARCHAR(length=50), autoincrement=False, nullable=True))
op.drop_constraint(None, 'statement_invoices', type_='foreignkey')
op.create_foreign_key('statement_invoices_inovice_id_fkey', 'statement_invoices', 'invoice', ['inovice_id'], ['id'])
op.create_index('ix_statement_invoices_status', 'statement_invoices', ['status'], unique=False)
op.drop_column('statement_invoices', 'invoice_id')
op.add_column('statement', sa.Column('payment_account_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.add_column('statement', sa.Column('status', sa.VARCHAR(length=50), autoincrement=False, nullable=True))
op.drop_constraint(None, 'statement', type_='foreignkey')
op.create_foreign_key('statement_payment_account_id_fkey', 'statement', 'payment_account', ['payment_account_id'],
['id'])
op.create_index('ix_statement_status', 'statement', ['status'], unique=False)
op.create_index('ix_statement_payment_account_id', 'statement', ['payment_account_id'], unique=False)
op.drop_index(op.f('ix_statement_statement_settings_id'), table_name='statement')
op.alter_column('statement', 'to_date',
existing_type=sa.DATE(),
nullable=True)
op.drop_column('statement', 'statement_settings_id')
op.drop_column('statement', 'created_on')
op.drop_index(op.f('ix_statement_settings_payment_account_id'), table_name='statement_settings')
op.drop_index(op.f('ix_statement_settings_frequency'), table_name='statement_settings')
op.drop_table('statement_settings')
# ### end Alembic commands ###
| [
"sumesh.pk@aot-technologies.com"
] | sumesh.pk@aot-technologies.com |
d0fd835e3d61a7db44b259b0c1d9a05bc4796396 | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /DPGAnalysis/SiStripTools/python/apvcyclephasemonitor_cfi.py | 9814e0f8f7209992f5a68a743eef2f4a9d42ad1f | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | Python | false | false | 198 | py | import FWCore.ParameterSet.Config as cms
apvcyclephasemonitor = cms.EDAnalyzer('APVCyclePhaseMonitor',
apvCyclePhaseCollection = cms.InputTag("APVPhases"),
)
| [
"giulio.eulisse@gmail.com"
] | giulio.eulisse@gmail.com |
deae5050d581b1d17e3c50c20f4ab36e74df1bd1 | d2c229f74a3ca61d6a22f64de51215d9e30c5c11 | /qiskit/circuit/library/templates/nct/template_nct_9c_7.py | b9f87f69effbf1b0646eb719daee998d4d86ad23 | [
"Apache-2.0"
] | permissive | 1ucian0/qiskit-terra | 90e8be8a7b392fbb4b3aa9784c641a818a180e4c | 0b51250e219ca303654fc28a318c21366584ccd3 | refs/heads/main | 2023-08-31T07:50:33.568824 | 2023-08-22T01:52:53 | 2023-08-22T01:52:53 | 140,555,676 | 6 | 1 | Apache-2.0 | 2023-09-14T13:21:54 | 2018-07-11T09:52:28 | Python | UTF-8 | Python | false | false | 1,620 | py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Template 9c_7:
.. parsed-literal::
q_0: ──■────■────■────■────■─────────■────■───────
┌─┴─┐ │ ┌─┴─┐┌─┴─┐ │ ┌───┐ │ │ ┌───┐
q_1: ┤ X ├──■──┤ X ├┤ X ├──┼──┤ X ├──■────┼──┤ X ├
└─┬─┘┌─┴─┐└───┘└─┬─┘┌─┴─┐└─┬─┘┌─┴─┐┌─┴─┐└─┬─┘
q_2: ──■──┤ X ├───────■──┤ X ├──■──┤ X ├┤ X ├──■──
└───┘ └───┘ └───┘└───┘
"""
from qiskit.circuit.quantumcircuit import QuantumCircuit
def template_nct_9c_7():
"""
Returns:
QuantumCircuit: template as a quantum circuit.
"""
qc = QuantumCircuit(3)
qc.ccx(0, 2, 1)
qc.ccx(0, 1, 2)
qc.cx(0, 1)
qc.ccx(0, 2, 1)
qc.cx(0, 2)
qc.cx(2, 1)
qc.ccx(0, 1, 2)
qc.cx(0, 2)
qc.cx(2, 1)
return qc
| [
"noreply@github.com"
] | 1ucian0.noreply@github.com |
7e7607f6a093f30de9aba7f216f56bb3e00dda94 | ddacbd31a215de3560d4c79489915f8b3bdf9a8d | /vertmodes.py | e4a45500783bee6e110328750660bec3d6ed6c71 | [] | no_license | jklymak/pythonlib | 40cfce6ee34f36a90c03350d3bf50e5e99655e26 | e71b1713394b5ac38ba0ea2f32d3fdff6f5118ff | refs/heads/master | 2021-06-18T12:53:57.051465 | 2017-05-29T19:14:27 | 2017-05-29T19:14:27 | 21,134,313 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,236 | py | from matplotlib import pylab
def vertModes(N2,dz,nmodes=0):
"""" psi,phi,ce,z=vertModes(N2,dz,nmodes=0)
Compute the vertical eigen modes of the internal wave solution on a flat bottom
Parameters:
-----------
N2 : (M) is buoyancy frequency squared (rad^2/s^2) as an 1-D
array. If there are M values of N2, the first one is assumed
to be at dz/2 deep, and the last one is H-dz/2 deep. The
water column is assumed to be H=M*dz deep. No gaps are
allowed, and N2>0 everywhere.
dz : is a single value, and the distance (in meters) between the N2 estimates
nmodes : number of modes to return. nmodes = 0 means return M-3 modes.
Returns:
--------
psi : (M,M-2) is the vertical structure function at
z=dz/2,3dz/2,2dz...,H-dz/2. Note there is one extra value
compared to N2 (ie there are M+1 values in depth). psi is
normalized so that sum(psi^2 dz) = 1. For internal waves,
psi is approriate for velocity and pressure vertical
structure.
phi : (M,M-2) is the vertical integral of psi (phi = int psi dz)
and represents the vertical velocity structure. It is
interpolated onto the same grid as psi.
ce : (M-2) is the non-rotating phase speed of the waves in m/s.
z : (M) is the vertical position of the psi and phi vector elements.
Notes:
------
This solves 1/N**2 psi_{zz} + (1/ce**2)psi = 0 subject to a
boundary condition of zero vertical velocity at the surface and
seafloor.
psi(0)=0 (rigid lid approx)
psi(H)=0
It is solved as an eigenvalue problem.
Also note that if
J. Klymak (Based on code by Sam Kelly and Gabe Vecchi)
"""
import numpy as np
# First we are solving for w on dz,2dz,3dz...H-dz
M = np.shape(N2)[0]-1
if M>200:
sparse = True
if nmodes==0:
nmodes = 100 # don't try too many eigenvectors in sparse mode...
else:
sparse = False
if nmodes==0:
nmodes = M-2
N2mid = N2[:-1]+np.diff(N2)/2.
# matrix for second difference operator
D = np.diag(-2.*np.ones(M),0)
D += np.diag(1.*np.ones(M-1),-1)
D += np.diag(1.*np.ones(M-1),1)
D=-D/dz/dz
D = np.diag(1./N2mid).dot(D)
ce,W = np.linalg.eig(D)
# psi is such that sum(psi^2)=1 but we want sum(psi^2 dz)=1.
W = W/np.sqrt(dz)
ce = 1./np.sqrt(ce)
ind=np.argsort(-ce)
ce=ce[ind[:-2]]
W=W[:,ind[:-2]]
# zphi
zphi = np.linspace(dz/2.,(M+1)*dz-dz/2.,M+1)
# now get phi (w structure) on dz/2,3dz/2...
phi = np.zeros((M+1,M+1-3))
phi[0,:]=0.5*(W[0,:])
phi[1:-1,:]=0.5*(W[:-1,:]+W[1:,:])
phi[-1,:]=0.5*(W[-1,:])
# Now get psi (u/p structure) on dz/2,3dz/2...
psi = np.zeros((M+1,M+1-3))
psi[0,:] = W[0,:]
psi[1:-1,] = np.diff(W,axis=0)
psi[-1,:] = -W[-1,:]
A = np.sqrt(np.sum(psi*psi,axis=0)*dz)
psi = psi/A
phi = phi/A
# flip sign so always same sign in psi at top:
phi[:,psi[0,:]<0] *= -1
psi[:,psi[0,:]<0] *= -1
return psi,phi,ce,zphi
| [
"jklymak@gmail.com"
] | jklymak@gmail.com |
7d454b4ee957e03dc6015d34bb5973486b64293d | 1e0a8a929f8ea69e476d8a8c5f3455aaf5317de6 | /scripts/utils/_rabbitmq.py | 71b8a0f02aff9298131339204af550da774c7e2f | [
"MIT"
] | permissive | jearistiz/guane-intern-fastapi | aa41400fa22076111e96be695fde0a1ff6f118d0 | 269adc3ee6a78a262b4e19e7df291fd920fae2e1 | refs/heads/master | 2023-06-25T08:58:03.729614 | 2023-06-11T15:28:59 | 2023-06-11T15:28:59 | 370,229,796 | 63 | 9 | MIT | 2021-06-11T01:28:52 | 2021-05-24T04:45:23 | Python | UTF-8 | Python | false | false | 4,175 | py | import time
import warnings
from pathlib import Path
from typing import Tuple
from subprocess import Popen, run, CompletedProcess
def local_rabbitmq_uri(
user: str, pwd: str, port: str, vhost: str
) -> str:
return f'amqp://{user}:{pwd}@0.0.0.0:{port}/{vhost}'
def init_rabbitmq_app(
rabbitmq_user: str,
rabbitmq_pass: str,
rabbitmq_vhost: str,
max_retries: int = 10,
sleep_time: int = 1 # In seconds
) -> Tuple[Popen, int]:
"""Starts the RabbitMQ server, creates a new user with its credentials,
creates a new virtual host and adds administration priviledges to the
user in the virtual host.
"""
module_name_tag = f'[{Path(__file__).stem}]'
hidden_pass = "x" * (len(rabbitmq_pass) - 2) + rabbitmq_pass[-2:]
user_with_pass = f'user {rabbitmq_user} with password {hidden_pass}'
_, _ = rabbitmq_full_start_app()
# Create user
rabbitmq_user_process = rabbitmq_create_user(rabbitmq_user, rabbitmq_pass)
if rabbitmq_user_process.returncode == 0:
print(f'{module_name_tag} rabbitmqctl created {user_with_pass} ')
else:
warnings.warn(
f'{module_name_tag} rabbitmqctl couldn\'t create '
f'{user_with_pass}, probably because the server couldn\'t be '
'started appropriately or the user already existed.'
)
# Add virtual host
rabbitmq_add_vhost(rabbitmq_vhost)
# Set user as administrator
rabbitmq_set_user_admin(rabbitmq_user)
# Set read, write and execute permissions on user
rabbitmq_user_permissions(rabbitmq_vhost, rabbitmq_user)
# We need to restart the server, this way the newly created user and
# permissions take effect
rabbitmq_server_process, server_ping_statuscode = rabbitmq_restart_server(
max_retries, sleep_time
)
return rabbitmq_server_process, server_ping_statuscode
def rabbitmq_start_wait_server(
retries: int = 15, sleep_time: int = 1
) -> Tuple[Popen, int]:
rabbitmq_server_process = Popen(['rabbitmq-server'])
ping_returncode = 1
i = 0
while ping_returncode != 0 and i < retries:
time.sleep(sleep_time)
ping_process = run(['rabbitmqctl', 'ping'])
ping_returncode = ping_process.returncode
del ping_process
i += 1
return rabbitmq_server_process, ping_returncode
def rabbitmq_full_start_app(
retries: int = 15, sleep_time: int = 1
) -> Tuple[Popen, int]:
"""Starts both rabbitmq server and application"""
# Start rabbitmq server
rabbitmq_server_process, server_ping_code = rabbitmq_start_wait_server(
retries, sleep_time
)
# Start rabbitmq application
run(['rabbitmqctl', 'start_app'])
run(['rabbitmqctl', 'await_startup'])
return rabbitmq_server_process, server_ping_code
def rabbitmq_create_user(
rabbitmq_user: str, rabbitmq_pass: str
) -> CompletedProcess:
return run(
['rabbitmqctl', 'add_user', rabbitmq_user, rabbitmq_pass]
)
def rabbitmq_add_vhost(rabbitmq_vhost: str) -> CompletedProcess:
return run(['rabbitmqctl', 'add_vhost', rabbitmq_vhost])
def rabbitmq_set_user_admin(
rabbitmq_user: str
) -> CompletedProcess:
# Set user as administrator
run(
['rabbitmqctl', 'set_user_tags', rabbitmq_user, 'administrator']
)
def rabbitmq_user_permissions(
rabbitmq_vhost: str,
rabbitmq_user: str,
permissions: Tuple[str, str, str] = ('.*', '.*', '.*')
):
"""Set read, write and execute permissions on user"""
cmd_base = [
'rabbitmqctl', 'set_permissions', '-p', rabbitmq_vhost, rabbitmq_user
]
run(cmd_base + list(permissions))
def rabbitmq_restart_server(
retries: int = 15, sleep_time: int = 1
) -> Tuple[Popen, int]:
run(['rabbitmqctl', 'shutdown'])
return rabbitmq_start_wait_server(retries, sleep_time)
def rabbitmq_reset_and_shut_down_server():
rabbitmq_start_wait_server()
run(['rabbitmqctl', 'stop_app'])
run(['rabbitmqctl', 'reset'])
run(['rabbitmqctl', 'shutdown'])
def rabbitmq_server_teardown(rabbitmq_server_process: Popen):
rabbitmq_server_process.terminate()
rabbitmq_reset_and_shut_down_server()
| [
"jeaz.git@gmail.com"
] | jeaz.git@gmail.com |
653fdc5ad9a6a125e22f78463105e985e68a1d81 | 79a61715a94e0a78e3268a514f97e5211c3e770b | /processors/notes_to_comments.py | 4653bc214790c24cf0339ee01b7a1289fbb470ce | [
"MIT",
"ISC"
] | permissive | eads/desapariciones | 2f120c18316e9ee3416b4c9eae1d68f72ec00e9c | 6069b21f26cc5175e78af54efb5cda0a64a2d9c5 | refs/heads/master | 2023-03-09T09:16:30.321455 | 2022-05-15T18:40:16 | 2022-05-15T18:40:16 | 188,893,244 | 5 | 0 | MIT | 2023-03-03T00:20:30 | 2019-05-27T18:42:01 | R | UTF-8 | Python | false | false | 577 | py | import click
import csv
from jinja2 import Template
from slugify import slugify
TEMPLATE = """
comment on column processed.cenapi.{{nombre_variable}} is '{{descripción}}';
"""
@click.command()
@click.argument('input', type=click.File('r', encoding='utf-8-sig'))
@click.argument('output', type=click.File('w'))
def generate(input, output):
"""Generate comments from a csv."""
t = Template(TEMPLATE)
reader = csv.DictReader(input)
for row in reader:
comment = t.render(**row)
output.write(comment)
if __name__ == '__main__':
generate()
| [
"davideads@gmail.com"
] | davideads@gmail.com |
2cff4d3069d8f77d32a1cdbe93772331360cc8ba | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/libwebp/libwebp.gyp | 67c03685dd3d9b42591b4f5d3b52fc8671446cb8 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webm",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | Python | false | false | 7,956 | gyp | # Copyright (c) 2012 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.
{
'target_defaults': {
'conditions': [
['os_posix==1 and (target_arch=="arm" or target_arch=="arm64")', {
'cflags!': [ '-Os' ],
'cflags': [ '-O2' ],
}],
],
},
'targets': [
{
'target_name': 'libwebp_dec',
'type': 'static_library',
'dependencies' : [
'libwebp_dsp',
'libwebp_dsp_neon',
'libwebp_utils',
],
'include_dirs': ['.'],
'sources': [
'dec/alpha.c',
'dec/buffer.c',
'dec/frame.c',
'dec/idec.c',
'dec/io.c',
'dec/quant.c',
'dec/tree.c',
'dec/vp8.c',
'dec/vp8l.c',
'dec/webp.c',
],
},
{
'target_name': 'libwebp_demux',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'demux/demux.c',
],
'dependencies' : [
'libwebp_utils',
],
},
{
'target_name': 'libwebp_dsp',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'dsp/alpha_processing.c',
'dsp/alpha_processing_mips_dsp_r2.c',
'dsp/argb.c',
'dsp/argb_mips_dsp_r2.c',
'dsp/cost.c',
'dsp/cost_mips32.c',
'dsp/cost_mips_dsp_r2.c',
'dsp/cpu.c',
'dsp/dec.c',
'dsp/dec_clip_tables.c',
'dsp/dec_mips32.c',
'dsp/dec_mips_dsp_r2.c',
'dsp/dec_msa.c',
'dsp/enc.c',
'dsp/enc_avx2.c',
'dsp/enc_mips32.c',
'dsp/enc_mips_dsp_r2.c',
'dsp/filters.c',
'dsp/filters_mips_dsp_r2.c',
'dsp/lossless.c',
'dsp/lossless_enc.c',
'dsp/lossless_enc_mips32.c',
'dsp/lossless_enc_mips_dsp_r2.c',
'dsp/lossless_mips_dsp_r2.c',
'dsp/rescaler.c',
'dsp/rescaler_mips32.c',
'dsp/rescaler_mips_dsp_r2.c',
'dsp/upsampling.c',
'dsp/upsampling_mips_dsp_r2.c',
'dsp/yuv.c',
'dsp/yuv_mips32.c',
'dsp/yuv_mips_dsp_r2.c',
],
'dependencies' : [
'libwebp_dsp_sse2',
'libwebp_dsp_sse41',
'libwebp_utils',
],
'conditions': [
['OS == "android"', {
'dependencies': [ '../../build/android/ndk.gyp:cpu_features' ],
}],
# iOS uses the same project to generate build project for both device
# and simulator and do not use "target_arch" variable. Other platform
# set it correctly.
['OS!="ios" and (target_arch=="ia32" or target_arch=="x64")', {
'defines': [ 'WEBP_HAVE_SSE2', 'WEBP_HAVE_SSE41' ],
}],
],
},
{
'target_name': 'libwebp_dsp_sse2',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'dsp/alpha_processing_sse2.c',
'dsp/argb_sse2.c',
'dsp/cost_sse2.c',
'dsp/dec_sse2.c',
'dsp/enc_sse2.c',
'dsp/filters_sse2.c',
'dsp/lossless_enc_sse2.c',
'dsp/lossless_sse2.c',
'dsp/rescaler_sse2.c',
'dsp/upsampling_sse2.c',
'dsp/yuv_sse2.c',
],
'conditions': [
# iOS uses the same project to generate build project for both device
# and simulator and do not use "target_arch" variable. Other platform
# set it correctly.
['OS!="ios" and (target_arch=="ia32" or target_arch=="x64") and msan==0', {
'cflags': [ '-msse2', ],
'xcode_settings': { 'OTHER_CFLAGS': [ '-msse2' ] },
}],
],
},
{
'target_name': 'libwebp_dsp_sse41',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'dsp/alpha_processing_sse41.c',
'dsp/dec_sse41.c',
'dsp/enc_sse41.c',
'dsp/lossless_enc_sse41.c',
],
'conditions': [
['OS=="win" and clang==1', {
# cl.exe's /arch flag doesn't have a setting for SSSE3/4, and cl.exe
# doesn't need it for intrinsics. clang-cl does need it, though.
'msvs_settings': {
'VCCLCompilerTool': { 'AdditionalOptions': [ '-msse4.1' ] },
},
}],
# iOS uses the same project to generate build project for both device
# and simulator and do not use "target_arch" variable. Other platform
# set it correctly.
['OS!="ios" and (target_arch=="ia32" or target_arch=="x64") and msan==0', {
'cflags': [ '-msse4.1', ],
'xcode_settings': { 'OTHER_CFLAGS': [ '-msse4.1' ] },
}],
],
},
{
'target_name': 'libwebp_dsp_neon',
'includes' : [
# Disable LTO due to Neon issues.
# crbug.com/408997
'../../build/android/disable_gcc_lto.gypi',
],
'conditions': [
# iOS uses the same project to generate build project for both device
# and simulator and do not use "target_arch" variable. Other platform
# set it correctly.
['OS == "ios" or (target_arch == "arm" and arm_version >= 7 and (arm_neon == 1 or arm_neon_optional == 1)) or (target_arch == "arm64")', {
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'dsp/dec_neon.c',
'dsp/enc_neon.c',
'dsp/lossless_enc_neon.c',
'dsp/lossless_neon.c',
'dsp/rescaler_neon.c',
'dsp/upsampling_neon.c',
],
'conditions': [
['target_arch == "arm" and arm_version >= 7 and (arm_neon == 1 or arm_neon_optional == 1)', {
# behavior similar to *.c.neon in an Android.mk
'cflags!': [ '-mfpu=vfpv3-d16' ],
'cflags': [ '-mfpu=neon' ],
}],
['target_arch == "arm64" and clang != 1', {
# avoid an ICE with gcc-4.9: b/15574841
'cflags': [ '-frename-registers' ],
}],
]
}, {
'type': 'none',
}],
],
},
{
'target_name': 'libwebp_enc',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'enc/alpha.c',
'enc/analysis.c',
'enc/backward_references.c',
'enc/config.c',
'enc/cost.c',
'enc/delta_palettization.c',
'enc/filter.c',
'enc/frame.c',
'enc/histogram.c',
'enc/iterator.c',
'enc/near_lossless.c',
'enc/picture.c',
'enc/picture_csp.c',
'enc/picture_psnr.c',
'enc/picture_rescale.c',
'enc/picture_tools.c',
'enc/quant.c',
'enc/syntax.c',
'enc/token.c',
'enc/tree.c',
'enc/vp8l.c',
'enc/webpenc.c',
],
'dependencies' : [
'libwebp_utils',
],
},
{
'target_name': 'libwebp_utils',
'type': 'static_library',
'include_dirs': ['.'],
'sources': [
'utils/bit_reader.c',
'utils/bit_writer.c',
'utils/color_cache.c',
'utils/filters.c',
'utils/huffman.c',
'utils/huffman_encode.c',
'utils/quant_levels.c',
'utils/quant_levels_dec.c',
'utils/random.c',
'utils/rescaler.c',
'utils/thread.c',
'utils/utils.c',
],
'variables': {
'clang_warning_flags': [
# See https://code.google.com/p/webp/issues/detail?id=253.
'-Wno-incompatible-pointer-types',
]
},
},
{
'target_name': 'libwebp',
'type': 'none',
'dependencies' : [
'libwebp_dec',
'libwebp_demux',
'libwebp_dsp',
'libwebp_dsp_neon',
'libwebp_enc',
'libwebp_utils',
],
'direct_dependent_settings': {
'include_dirs': ['.'],
},
'conditions': [
['OS!="win"', {'product_name': 'webp'}],
],
},
],
}
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
c64d298bed0f1f677a17ca3bac15570c447556a7 | 48e124e97cc776feb0ad6d17b9ef1dfa24e2e474 | /sdk/python/pulumi_azure_native/resources/v20190801/get_resource_group.py | 2f0d4bd30068643085cd612cac2f5e047a4d6f33 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | bpkgoud/pulumi-azure-native | 0817502630062efbc35134410c4a784b61a4736d | a3215fe1b87fba69294f248017b1591767c2b96c | refs/heads/master | 2023-08-29T22:39:49.984212 | 2021-11-15T12:43:41 | 2021-11-15T12:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,102 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetResourceGroupResult',
'AwaitableGetResourceGroupResult',
'get_resource_group',
'get_resource_group_output',
]
@pulumi.output_type
class GetResourceGroupResult:
"""
Resource group information.
"""
def __init__(__self__, id=None, location=None, managed_by=None, name=None, properties=None, tags=None, type=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if managed_by and not isinstance(managed_by, str):
raise TypeError("Expected argument 'managed_by' to be a str")
pulumi.set(__self__, "managed_by", managed_by)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if properties and not isinstance(properties, dict):
raise TypeError("Expected argument 'properties' to be a dict")
pulumi.set(__self__, "properties", properties)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def id(self) -> str:
"""
The ID of the resource group.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def location(self) -> str:
"""
The location of the resource group. It cannot be changed after the resource group has been created. It must be one of the supported Azure locations.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter(name="managedBy")
def managed_by(self) -> Optional[str]:
"""
The ID of the resource that manages this resource group.
"""
return pulumi.get(self, "managed_by")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> 'outputs.ResourceGroupPropertiesResponse':
"""
The resource group properties.
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
The tags attached to the resource group.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource group.
"""
return pulumi.get(self, "type")
class AwaitableGetResourceGroupResult(GetResourceGroupResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetResourceGroupResult(
id=self.id,
location=self.location,
managed_by=self.managed_by,
name=self.name,
properties=self.properties,
tags=self.tags,
type=self.type)
def get_resource_group(resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetResourceGroupResult:
"""
Resource group information.
:param str resource_group_name: The name of the resource group to get. The name is case insensitive.
"""
__args__ = dict()
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:resources/v20190801:getResourceGroup', __args__, opts=opts, typ=GetResourceGroupResult).value
return AwaitableGetResourceGroupResult(
id=__ret__.id,
location=__ret__.location,
managed_by=__ret__.managed_by,
name=__ret__.name,
properties=__ret__.properties,
tags=__ret__.tags,
type=__ret__.type)
@_utilities.lift_output_func(get_resource_group)
def get_resource_group_output(resource_group_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetResourceGroupResult]:
"""
Resource group information.
:param str resource_group_name: The name of the resource group to get. The name is case insensitive.
"""
...
| [
"noreply@github.com"
] | bpkgoud.noreply@github.com |
3621b7bff933e2d4959271d79594fd29094aa68c | 1698fe3ff15a6737c70501741b32b24fe68052f4 | /django-request-master/request/models.py | 102d2270e1323708bb13dd219052f6e37150f524 | [] | no_license | menhswu/djangoapps | 4f3718244c8678640af2d2a095d20a405e337884 | 039a42aa9d1537e7beb4071d86bea7a42253d8b3 | refs/heads/master | 2023-03-04T03:56:01.070921 | 2021-01-28T07:35:02 | 2021-01-28T07:35:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,049 | py | from socket import gethostbyaddr
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from . import settings as request_settings
from .managers import RequestManager
from .utils import HTTP_STATUS_CODES, browsers, engines, request_is_ajax
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class Request(models.Model):
# Response information.
response = models.SmallIntegerField(_('response'), choices=HTTP_STATUS_CODES, default=200)
# Request information.
method = models.CharField(_('method'), default='GET', max_length=7)
path = models.CharField(_('path'), max_length=255)
time = models.DateTimeField(_('time'), default=timezone.now, db_index=True)
is_secure = models.BooleanField(_('is secure'), default=False)
is_ajax = models.BooleanField(
_('is ajax'),
default=False,
help_text=_('Wheather this request was used via javascript.'),
)
# User information.
ip = models.GenericIPAddressField(_('ip address'))
user = models.ForeignKey(AUTH_USER_MODEL, blank=True, null=True, verbose_name=_('user'), on_delete=models.SET_NULL)
referer = models.URLField(_('referer'), max_length=255, blank=True, null=True)
user_agent = models.CharField(_('user agent'), max_length=255, blank=True, null=True)
language = models.CharField(_('language'), max_length=255, blank=True, null=True)
objects = RequestManager()
class Meta:
app_label = 'request'
verbose_name = _('request')
verbose_name_plural = _('requests')
ordering = ('-time',)
def __str__(self):
return '[{0}] {1} {2} {3}'.format(self.time, self.method, self.path, self.response)
def get_user(self):
return get_user_model().objects.get(pk=self.user_id)
def from_http_request(self, request, response=None, commit=True):
# Request information.
self.method = request.method
self.path = request.path[:255]
self.is_secure = request.is_secure()
self.is_ajax = request_is_ajax(request)
# User information.
self.ip = request.META.get('REMOTE_ADDR', '')
self.referer = request.META.get('HTTP_REFERER', '')[:255]
self.user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
self.language = request.META.get('HTTP_ACCEPT_LANGUAGE', '')[:255]
if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated'):
is_authenticated = request.user.is_authenticated
if is_authenticated:
self.user = request.user
if response:
self.response = response.status_code
if (response.status_code == 301) or (response.status_code == 302):
self.redirect = response['Location']
if commit:
self.save()
@property
def browser(self):
if not self.user_agent:
return
if not hasattr(self, '_browser'):
self._browser = browsers.resolve(self.user_agent)
return self._browser[0]
@property
def keywords(self):
if not self.referer:
return
if not hasattr(self, '_keywords'):
self._keywords = engines.resolve(self.referer)
if self._keywords:
return ' '.join(self._keywords[1]['keywords'].split('+'))
@property
def hostname(self):
try:
return gethostbyaddr(self.ip)[0]
except Exception: # socket.gaierror, socket.herror, etc
return self.ip
def save(self, *args, **kwargs):
if not request_settings.LOG_IP:
self.ip = request_settings.IP_DUMMY
elif request_settings.ANONYMOUS_IP:
parts = self.ip.split('.')[0:-1]
parts.append('1')
self.ip = '.'.join(parts)
if not request_settings.LOG_USER:
self.user = None
super().save(*args, **kwargs)
| [
"jinxufang@tencent.com"
] | jinxufang@tencent.com |
dbe246c5716bc5805439e941fe6ceb98c1161194 | e9539de5b8832e2a09365917fe201a945bf5d99b | /leetcode16.py | c6fc3a8fc977080489f30d083f334013a3f341b1 | [] | no_license | JoshuaW1990/leetcode-session1 | 56d57df30b21ccade3fe54e3fd56a2b3383bd793 | 6fc170c04fadec6966fb7938a07474d4ee107b61 | refs/heads/master | 2021-09-20T16:18:15.640839 | 2018-08-12T09:40:51 | 2018-08-12T09:40:51 | 76,912,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 874 | py | class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
ans = None
minDiff = float('inf')
nums.sort()
for i in xrange(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
left = i + 1
right = len(nums) - 1
while left < right:
diff = target - (nums[left] + nums[right] + nums[i])
if abs(diff) < minDiff:
ans = nums[left] + nums[right] + nums[i]
minDiff = abs(diff)
if diff == 0:
return ans
elif diff > 0:
left += 1
else:
right -= 1
return ans
| [
"Jun.Wang@tufts.edu"
] | Jun.Wang@tufts.edu |
0c28ae315ae4aca9b257d2bda00cbfc798cdca4e | 092a13e08cc412d85f2115b9efaad17e1afdfc1a | /common/models/food/Food.py | 068207c4915f3f47faa1deb6364f04b1ec590403 | [] | no_license | Willanzhang/flask_mvc | 283196e1850f8676f1db52fe6361aa8706276e9d | 408470329494cd40691e4014b85ccdc9ba11711d | refs/heads/master | 2022-12-12T11:13:06.202893 | 2019-08-04T14:21:48 | 2019-08-04T14:21:48 | 173,304,987 | 0 | 0 | null | 2022-12-08T04:54:05 | 2019-03-01T13:18:14 | JavaScript | UTF-8 | Python | false | false | 1,501 | py | # coding: utf-8
from sqlalchemy import Column, DateTime, Integer, Numeric, String
from sqlalchemy.schema import FetchedValue
from application import db
class Food(db.Model):
__tablename__ = 'food'
id = db.Column(db.Integer, primary_key=True)
cat_id = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
name = db.Column(db.String(100), nullable=False, server_default=db.FetchedValue())
price = db.Column(db.Numeric(10, 2), nullable=False, server_default=db.FetchedValue())
main_image = db.Column(db.String(100), nullable=False, server_default=db.FetchedValue())
summary = db.Column(db.String(10000), nullable=False, server_default=db.FetchedValue())
stock = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
tags = db.Column(db.String(200), nullable=False, server_default=db.FetchedValue())
status = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
month_count = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
total_count = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
view_count = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
comment_count = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue())
updated_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue())
created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue())
| [
"631871612@qq.com"
] | 631871612@qq.com |
9514c4458b97cb367130adb69501908c8ee29532 | 51a37b7108f2f69a1377d98f714711af3c32d0df | /src/leetcode/P5664.py | 146ff2962cd3355bf82250c46bf4e1657269de8d | [] | no_license | stupidchen/leetcode | 1dd2683ba4b1c0382e9263547d6c623e4979a806 | 72d172ea25777980a49439042dbc39448fcad73d | refs/heads/master | 2022-03-14T21:15:47.263954 | 2022-02-27T15:33:15 | 2022-02-27T15:33:15 | 55,680,865 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 610 | py | class Solution:
def minimumBoxes(self, n: int):
t = 0
m = 0
i = 1
while True:
t += (i * (i + 1)) >> 1
if t >= n:
m = i
break
i += 1
if t == n:
return (m * (m + 1)) >> 1
t -= (m * (m + 1)) >> 1
m -= 1
j = 1
r = (m * (m + 1)) >> 1
while True:
r += 1
t += j
if t >= n:
return r
j += 1
if __name__ == '__main__':
for i in range(20):
print(Solution().minimumBoxes(i + 1))
| [
"stupidchen@foxmail.com"
] | stupidchen@foxmail.com |
bca93284647db372a5236cc8a447f4654434f78c | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_grout.py | 989f969bf4769d1c0640642da950d88a9f05f5b4 | [
"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 | 302 | py |
#calss header
class _GROUT():
def __init__(self,):
self.name = "GROUT"
self.definitions = [u'mortar used for grouting']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
f421e5d3c9490ad52705ea07bdcf8dd9763a729b | ec551303265c269bf1855fe1a30fdffe9bc894b6 | /old/t20190416_divide/divide.py | 19521d6d57481134378c263ec0fe597333aca22a | [] | no_license | GongFuXiong/leetcode | 27dbda7a5ced630ae2ae65e19d418ebbc65ae167 | f831fd9603592ae5bee3679924f962a3ebce381c | refs/heads/master | 2023-06-25T01:05:45.683510 | 2021-07-26T10:05:25 | 2021-07-26T10:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,694 | py | #!/usr/bin/env python
# encoding: utf-8
'''
@author: KM
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: yangkm601@gmail.com
@software: garner
@file: divide.py
@time: 2019/4/16 11:56
@desc:
22. 括号生成
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2
说明:
被除数和除数均为 32 位有符号整数。
除数不为 0。
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。
本题中,如果除法结果溢出,则返回 2^31 − 1。
'''
import math
class Solution:
def __init__(self):
self.MIN_VALUE = - math.pow(2,31)
self.MAX_VALUE = math.pow(2,31)-1
def divide(self, dividend, divisor):
sym_flag = 1
if divisor == 0:
return 0
if dividend < 0 and divisor > 0:
sym_flag = -1
dividend = -1 * dividend
elif dividend > 0 and divisor < 0:
sym_flag = -1
divisor = -1 * divisor
elif dividend < 0 and divisor < 0:
dividend = -1 * dividend
divisor = -1 * divisor
result = 0
for i in range(31,-1 ,-1):
if (dividend>>i) >= divisor:
result = result + (1<<i)
dividend = dividend - (divisor<<i)
result = sym_flag * result
if result < - math.pow(2, 31) or result > math.pow(2, 31) - 1:
result = math.pow(2, 31) - 1
return int(result)
def divide1(self, dividend, divisor):
sym_flag = 1
if divisor == 0:
return 0
if dividend<0 and divisor>0:
sym_flag = -1
dividend = -1 * dividend
elif dividend>0 and divisor<0:
sym_flag = -1
divisor = -1 * divisor
elif dividend<0 and divisor<0:
dividend = -1 * dividend
divisor = -1 * divisor
quotient = 0
while dividend >= divisor:
dividend = dividend - divisor
quotient = quotient + 1
quotient = sym_flag * quotient
if quotient < - math.pow(2,31) or quotient > math.pow(2,31)-1:
quotient = math.pow(2,31)-1
return quotient
if __name__ == "__main__":
solution=Solution()
res = solution.divide(-2147483648,-1)
print("res:{0}".format(res))
| [
"958747457@qq.com"
] | 958747457@qq.com |
899c7ea862d1368e04b45d33aabd03d943fa2d16 | 1b845de8123c750e8735ccf4297bf1e5861cbb4b | /katas/5kyu/kata11.py | 4c378777c4c279724b5df14f510e2318865c2f63 | [] | no_license | jorgemira/codewars | 3ef2b05fa90722cdd48bb8afb0f7536627bcfec9 | 701a756f3d466dbfe93f228b2e294cf49a7af2ae | refs/heads/master | 2020-12-19T19:07:51.485286 | 2020-01-23T15:54:52 | 2020-01-23T15:54:52 | 235,824,468 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 941 | py | """
Codewars 5 kyu kata: Finding an appointment
URL: https://www.codewars.com/kata/525f277c7103571f47000147/python
"""
def t2n(time):
h, m = (int(i) for i in time.split(':'))
return (h - 9) * 60 + m
def n2t(num):
h = ('' if num / 60 else '0') + str(num / 60 + 9)
m = ('' if num - num / 60 * 60 else '0') + str(num - num / 60 * 60)
return ':'.join([h, m])
def overlaps(period1, period2):
return period1[0] <= period2[0] < period1[1] or period2[0] <= period1[0] < period2[1]
def get_start_time(schedules, duration):
day = []
end_times = set([0])
for appointments in schedules:
for start, end in appointments:
day.append([t2n(start), t2n(end)])
end_times.add(t2n(end))
for end_time in sorted(end_times):
if end_time + duration <= 600 and all(not overlaps(d, (end_time, end_time + duration)) for d in day):
return n2t(end_time)
return None
| [
"jorge.mira.yague@gmail.com"
] | jorge.mira.yague@gmail.com |
15a699a1ba9a4aff30701aeada95d57169f75f68 | fc5708b8f291c314dad85f53e23c5728d7b9627f | /week3/excercise_3.py | 81fb9030a46a6251b5d5e74230201b77b1756328 | [] | no_license | OnestoneW/UZH | d271beeb9cfa31c67a5ce9e6f8a7b9ec5d3b8658 | 9c243a6e92c504f83d5fc091a5d67bd05e79d905 | refs/heads/master | 2021-05-07T05:03:58.526573 | 2017-11-22T19:55:46 | 2017-11-22T19:55:46 | 111,398,660 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 904 | py | import pylab as plb
import numpy as np
import matplotlib
def calc_average_radiation(data_set):
values = data_set[:,0]
errors = data_set[:,1]
#calc the measurements for "per year":
values = values*365*24
errors = errors*365*24
weights = 1/(errors**2)
average = sum((weights*values))/sum(weights)
error_on_average = (1/np.sqrt(sum(weights)))/np.sqrt(len(weights))
return average, error_on_average
if __name__ == "__main__":
data = plb.loadtxt("radiation.dat")
average, error = calc_average_radiation(data)
result = "({} +/- {}) mSv/year".format(round(average, 3), round(error, 3))
print("Average radiation per year:",result)
'''Taking a look onto the natural radiation of 2.4 mSv/year, our result is about (0.191 +/- 0.012) mSv/year higher.
Since this is only about 8% higher as the natural background radiation, it is compatible.''' | [
"root@localhost.localdomain"
] | root@localhost.localdomain |
45f25cb7ac03ba31a0808b28ae688e323ba4c5d7 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /python/youtube-dl/2016/12/amcnetworks.py | 87c803e948fd2e04cde6b0b43251d3f804b952a0 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Python | false | false | 4,211 | py | # coding: utf-8
from __future__ import unicode_literals
from .theplatform import ThePlatformIE
from ..utils import (
update_url_query,
parse_age_limit,
int_or_none,
)
class AMCNetworksIE(ThePlatformIE):
_VALID_URL = r'https?://(?:www\.)?(?:amc|bbcamerica|ifc|wetv)\.com/(?:movies/|shows/[^/]+/(?:full-episodes/)?[^/]+/episode-\d+(?:-(?:[^/]+/)?|/))(?P<id>[^/?#]+)'
_TESTS = [{
'url': 'http://www.ifc.com/shows/maron/season-04/episode-01/step-1',
'md5': '',
'info_dict': {
'id': 's3MX01Nl4vPH',
'ext': 'mp4',
'title': 'Maron - Season 4 - Step 1',
'description': 'In denial about his current situation, Marc is reluctantly convinced by his friends to enter rehab. Starring Marc Maron and Constance Zimmer.',
'age_limit': 17,
'upload_date': '20160505',
'timestamp': 1462468831,
'uploader': 'AMCN',
},
'params': {
# m3u8 download
'skip_download': True,
},
'skip': 'Requires TV provider accounts',
}, {
'url': 'http://www.bbcamerica.com/shows/the-hunt/full-episodes/season-1/episode-01-the-hardest-challenge',
'only_matching': True,
}, {
'url': 'http://www.amc.com/shows/preacher/full-episodes/season-01/episode-00/pilot',
'only_matching': True,
}, {
'url': 'http://www.wetv.com/shows/million-dollar-matchmaker/season-01/episode-06-the-dumped-dj-and-shallow-hal',
'only_matching': True,
}, {
'url': 'http://www.ifc.com/movies/chaos',
'only_matching': True,
}, {
'url': 'http://www.bbcamerica.com/shows/doctor-who/full-episodes/the-power-of-the-daleks/episode-01-episode-1-color-version',
'only_matching': True,
}]
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
query = {
'mbr': 'true',
'manifest': 'm3u',
}
media_url = self._search_regex(r'window\.platformLinkURL\s*=\s*[\'"]([^\'"]+)', webpage, 'media url')
theplatform_metadata = self._download_theplatform_metadata(self._search_regex(
r'https?://link.theplatform.com/s/([^?]+)', media_url, 'theplatform_path'), display_id)
info = self._parse_theplatform_metadata(theplatform_metadata)
video_id = theplatform_metadata['pid']
title = theplatform_metadata['title']
rating = theplatform_metadata['ratings'][0]['rating']
auth_required = self._search_regex(r'window\.authRequired\s*=\s*(true|false);', webpage, 'auth required')
if auth_required == 'true':
requestor_id = self._search_regex(r'window\.requestor_id\s*=\s*[\'"]([^\'"]+)', webpage, 'requestor id')
resource = self._get_mvpd_resource(requestor_id, title, video_id, rating)
query['auth'] = self._extract_mvpd_auth(url, video_id, requestor_id, resource)
media_url = update_url_query(media_url, query)
formats, subtitles = self._extract_theplatform_smil(media_url, video_id)
self._sort_formats(formats)
info.update({
'id': video_id,
'subtitles': subtitles,
'formats': formats,
'age_limit': parse_age_limit(parse_age_limit(rating)),
})
ns_keys = theplatform_metadata.get('$xmlns', {}).keys()
if ns_keys:
ns = list(ns_keys)[0]
series = theplatform_metadata.get(ns + '$show')
season_number = int_or_none(theplatform_metadata.get(ns + '$season'))
episode = theplatform_metadata.get(ns + '$episodeTitle')
episode_number = int_or_none(theplatform_metadata.get(ns + '$episode'))
if season_number:
title = 'Season %d - %s' % (season_number, title)
if series:
title = '%s - %s' % (series, title)
info.update({
'title': title,
'series': series,
'season_number': season_number,
'episode': episode,
'episode_number': episode_number,
})
return info
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
8c3cc63178cb6a0d72b3a1b00ef7ca7fcc050cf5 | 523f8f5febbbfeb6d42183f2bbeebc36f98eadb5 | /140.py | 8533e0a38d71ce3286ff6fbbbf15ed5d61c38e6e | [] | no_license | saleed/LeetCode | 655f82fdfcc3000400f49388e97fc0560f356af0 | 48b43999fb7e2ed82d922e1f64ac76f8fabe4baa | refs/heads/master | 2022-06-15T21:54:56.223204 | 2022-05-09T14:05:50 | 2022-05-09T14:05:50 | 209,430,056 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,708 | py | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
if len(s)==0 or len(wordDict)==0:
return []
dict=set(wordDict)
dp=[False for _ in range(len(s)+1)]
pre=[[] for _ in range(len(s)+1)]
dp[0]=True
for i in range(1,len(s)+1):
for j in range(i):
if dp[j] and s[j:i] in dict:
dp[i]=True
pre[i].append(j)
print(pre)
if dp[len(s)]==True:
path=self.generatePath(pre,s)
# print(path)
strres=[]
for i in range(len(path)):
path[i]=list(reversed(path[i]))
strres.append(" ".join(path[i]))
return strres
# return dp[len(s)]
return []
def generatePath(self,pre,s):
cur=len(s)
res=[]
self.recursiveSearch(res,pre,len(s),s,[])
# strarr=[]
# for i in res:
# strarr.append(" ".join(i))
return res
#回溯的方法??
def recursiveSearch(self,res,pre,id,s,curpath):
if len(pre[id])==0:
res.append(curpath[:])
return
for i in pre[id]:
curpath.append(s[i:id])
self.recursiveSearch(res,pre,i,s,curpath)
curpath.pop()
a=Solution()
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
print(a.wordBreak(s,wordDict))
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
print(a.wordBreak(s,wordDict))
test=['pine', 'applepen', 'apple']
print(" ".join(test)) | [
"1533441387@qq.com"
] | 1533441387@qq.com |
80e8c98591b0afb1451043bb84bd90a39ef8b326 | 71012df2815a4666203a2d574f1c1745d5a9c6dd | /4 Django/solutions/mysite/polls/views.py | ee7ecc4a4c55eaec3ae5baa8abb4803fe3c76ed1 | [] | no_license | PdxCodeGuild/class_mouse | 6c3b85ccf5ed4d0c867aee70c46af1b22d20a9e8 | 40c229947260134a1f9da6fe3d7073bee3ebb3f7 | refs/heads/main | 2023-03-23T14:54:39.288754 | 2021-03-20T01:48:21 | 2021-03-20T01:48:21 | 321,429,925 | 1 | 7 | null | null | null | null | UTF-8 | Python | false | false | 1,007 | py | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
# Create your views here.
def index(request):
questions = Question.objects.order_by('-pub_date')
context = {
'questions': questions
}
return render(request, 'polls/index.html', context)
def detail(request, id):
question = get_object_or_404(Question, id=id)
context = {
'question': question
}
return render(request, 'polls/detail.html', context)
def results(request, id):
question = get_object_or_404(Question, id=id)
context = {
'question': question
}
return render(request, 'polls/results.html', context)
def vote(request, id):
selected_choice = request.POST['choice']
choice = get_object_or_404(Choice, id=selected_choice)
choice.votes += 1
choice.save()
return HttpResponseRedirect(reverse('polls:detail', args=(id,)))
| [
"anthony@Anthonys-MBP.lan"
] | anthony@Anthonys-MBP.lan |
52e8847e9de82e204fdf0c8cd2b6aae8698321bd | 534b315921a7ad091aaef3ad9dd33691a570adad | /ex_03_02.py | 92e6efbfca059085bac104c573028c8f2f8773d7 | [] | no_license | epicarts/Python-for-Everybody | 42d91b66f6c5fbae47caabee98f64269ac4b2437 | edbe916b0beb9087e2a4a57516ccb3a315ac95d7 | refs/heads/master | 2020-03-21T21:00:07.393582 | 2018-07-17T10:58:11 | 2018-07-17T10:58:11 | 139,041,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | sh = input("Enter Hours: ")
sr = input("Enter Rate: ")
try:
fh = float(sh)
fr = float(sr)
except:
print("Error, please enter numeric input")
quit()
if fh > 40 :
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:", xp)
| [
"0505zxc@gmail.com"
] | 0505zxc@gmail.com |
390ca1273fd423bf42edd83f7b629397e189fd4b | bca124bc2cecb5d3dec17c9666ec00d29fadf517 | /i03Python-API-Development-Fundamentals/ch8pgination_search_order/resources/user.py | 438080c8c6bf226f01b9b4c26477bcc73ceb2276 | [] | no_license | greatabel/FlaskRepository | 1d1fdb734dd25d7273136206727c76b2742a915f | 85d402bc7b4218d3ae33d90f4a51dbac474f70ee | refs/heads/master | 2023-08-19T18:30:33.585509 | 2023-08-07T14:12:25 | 2023-08-07T14:12:25 | 60,396,096 | 5 | 0 | null | 2023-02-15T18:18:42 | 2016-06-04T06:11:32 | JavaScript | UTF-8 | Python | false | false | 5,782 | py | import os
from flask import request, url_for, render_template
from flask_restful import Resource
from flask_jwt_extended import jwt_optional, get_jwt_identity, jwt_required
from http import HTTPStatus
from webargs import fields
from webargs.flaskparser import use_kwargs
from extensions import image_set
from mailgun import MailgunApi
from models.recipe import Recipe
from models.user import User
from schemas.user import UserSchema
from schemas.recipe import RecipeSchema, RecipePaginationSchema
from marshmallow import ValidationError
from utils import generate_token, verify_token, save_image
user_schema = UserSchema()
user_public_schema = UserSchema(exclude=('email', ))
user_avatar_schema = UserSchema(only=('avatar_url', ))
recipe_list_schema = RecipeSchema(many=True)
recipe_pagination_schema = RecipePaginationSchema()
domain = os.environ.get('YOUR_DOMAIN_NAME', '')
api_key = os.environ.get('YOUR_API_KEY', '')
mailgun = MailgunApi(domain=domain, api_key=api_key)
class UserListResource(Resource):
def post(self):
json_data = request.get_json()
# data, errors = user_schema.load(data=json_data)
try:
data = user_schema.load(data=json_data)
username = data.get('username')
email = data.get('email')
if User.get_by_username(username):
return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST
if User.get_by_email(email):
return {'message': 'email already used'}, HTTPStatus.BAD_REQUEST
user = User(**data)
user.save()
token = generate_token(user.email, salt='activate')
subject = '请确认你的注册'
link = url_for('useractivateresource',
token=token,
_external=True)
# text = '感谢使用 SmileCook! 请点击确认链接: {}'.format(link)
# text Body of the message. (text version)/ html:Body of the message. (HTML version)
text = None
mailgun.send_email(to=user.email,
subject=subject,
text=text,
html=render_template('email/confirmation.html', link=link))
data = user_schema.dump(user)
return data, HTTPStatus.CREATED
except ValidationError as err:
return {'message': err.messages}, HTTPStatus.BAD_REQUEST
# if errors:
# return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST
class UserResource(Resource):
@jwt_optional
def get(self, username):
user = User.get_by_username(username=username)
if user is None:
return {'message': 'user not found'}, HTTPStatus.NOT_FOUND
current_user = get_jwt_identity()
# print('current_user=', current_user, user.id)
if current_user == user.id:
data = user_schema.dump(user)
else:
data = user_public_schema.dump(user)
return data, HTTPStatus.OK
class MeResource(Resource):
@jwt_required
def get(self):
user = User.get_by_id(id=get_jwt_identity())
data = user_schema.dump(user)
return data, HTTPStatus.OK
example_args = {
'page': fields.Int(missing=1),
'per_page': fields.Int(missing=10),
'visibility': fields.String(missing='public')
}
class UserRecipeListResource(Resource):
#visibility 和 username 顺序很重要,错了不行
@jwt_optional
@use_kwargs(example_args, location="query")
def get(self, page, per_page, visibility, username):
print('visibility=', visibility, page, per_page)
user = User.get_by_username(username=username)
if user is None:
return {'message': 'User not found'}, HTTPStatus.NOT_FOUND
current_user = get_jwt_identity()
print(current_user, user.id, visibility)
if current_user == user.id and visibility in ['all', 'private']:
pass
else:
visibility = 'public'
paginated_recipes = Recipe.get_all_by_user(user_id=user.id, page=page, per_page=per_page, visibility=visibility)
# print('recipes=', recipes)
data = recipe_pagination_schema.dump(paginated_recipes)
return data, HTTPStatus.OK
class UserActivateResource(Resource):
def get(self, token):
email = verify_token(token, salt='activate')
if email is False:
return {'message': 'Invalid token or token expired'}, HTTPStatus.BAD_REQUEST
user = User.get_by_email(email=email)
if not user:
return {'message': 'User not found'}, HTTPStatus.NOT_FOUND
if user.is_active is True:
return {'message': 'The user account is already activated'}, HTTPStatus.BAD_REQUEST
user.is_active = True
user.save()
return {}, HTTPStatus.NO_CONTENT
class UserAvatarUploadResource(Resource):
@jwt_required
def put(self):
file = request.files.get('avatar')
if not file:
return {'message': 'Not a valid image'}, HTTPStatus.BAD_REQUEST
if not image_set.file_allowed(file, file.filename):
return {'message': 'File type not allowed'}, HTTPStatus.BAD_REQUEST
user = User.get_by_id(id=get_jwt_identity())
if user.avatar_image:
avatar_path = image_set.path(folder='avatars', filename=user.avatar_image)
if os.path.exists(avatar_path):
os.remove(avatar_path)
filename = save_image(image=file, folder='avatars')
user.avatar_image = filename
user.save()
return user_avatar_schema.dump(user), HTTPStatus.OK
| [
"myreceiver2for2github@gmail.com"
] | myreceiver2for2github@gmail.com |
ae84bb1551d919d5a78e142d3902aadd859be877 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03475/s980181713.py | a507864b19aaa3ae22e296c2df9129769450df61 | [] | 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 | 506 | py | #!/usr/bin/env python3
N = int(input())
data = []
for _ in range(N - 1):
data.append(tuple(map(int, input().split())))
for i in range(N - 1):
c_i, s_i, f_i = data[i]
ans = c_i + s_i
if i == N - 2:
print(ans)
continue
for j in range(i + 1, N - 1):
c_j, s_j, f_j = data[j]
if ans >= s_j:
tmp = (ans - s_j) % f_j
ans += c_j if tmp == 0 else f_j - tmp + c_j
else:
ans += s_j - ans + c_j
print(ans)
print(0) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
eb46806d343bb2682eec400c2d940d7baf75857f | 819ea4165220ecaed5b168e37773282195501a38 | /src/snakemake/rules/bcftools_stats.smk | d5aa48244c3c2de15c3a78a09a1ed77da8eda257 | [
"MIT"
] | permissive | guillaumecharbonnier/mw-lib | 662fe4f1ca28ed48554971d5fbf47bb11bb210d9 | 870f082431fb92d0aeb0a28f9f1e88c448aebd8a | refs/heads/master | 2023-07-06T05:36:42.436637 | 2023-06-26T10:34:38 | 2023-06-26T10:34:38 | 198,626,514 | 0 | 1 | MIT | 2023-04-14T07:06:10 | 2019-07-24T11:57:07 | Python | UTF-8 | Python | false | false | 1,285 | smk | rule bcftools_stats_dev:
input:
"out/scalpel/discovery_--single_--bed_chr1:10000000-60000000_fa-genome-hg19-main-chr/samtools/index/samtools/sort/samtools/view_sam_to_bam/bwa/mem_se_fa-genome-hg19-main-chr/gunzip/to-stdout/ln/alias/sst/all_samples/fastq/Jurkat_SRR1057274_H3K27ac/variants.indel.vcf",
"out/scalpel/discovery_--single_--bed_chr1:10000000-60000000_fa-genome-hg19-main-chr/samtools/index/samtools/sort/samtools/view_sam_to_bam/bwa/mem_se_fa-genome-hg19-main-chr/gunzip/to-stdout/ln/alias/sst/all_samples/fastq/T11C_H3K27ac/variants.indel.vcf",
"out/scalpel/discovery_--single_--bed_chr1:10000000-60000000_fa-genome-hg19-main-chr/samtools/index/samtools/sort/samtools/view_sam_to_bam/bwa/mem_se_fa-genome-hg19-main-chr/gunzip/to-stdout/ln/alias/sst/all_samples/fastq/T11C_all_DNA_samples/variants.indel.vcf"
output:
"out/bcftools/stats_dev/stats.out"
conda:
"../envs/bcftools.yaml"
shell:
"bcftools stats {input} > {output}"
rule bcftools_plot_vcfstats:
input:
"out/bcftools/stats_dev/stats.out"
output:
touch("out/bcftools/plot-vcfstats/done")
conda:
"../envs/bcftools.yaml"
shell:
"""
plot-vcfstats -p out/bcftools/plot-vcfstats {input}
"""
| [
"guillaume.charbonnier@outlook.com"
] | guillaume.charbonnier@outlook.com |
8936e6c360a6169bb413fbc6ec891dedb2385f3a | c317312696645e061d955148058267dea10c9743 | /backend/home/migrations/0002_load_initial_data.py | 147470d221ed4d67a3edd73ef542a9b807f60286 | [] | no_license | lorence-crowdbotics/shiny-block-1 | 96dc1fb4af1bae7eb535d1db25430a8114c124eb | 64452c85dd1ebb6437437a637f4dff0402f57a9c | refs/heads/master | 2023-02-08T10:32:14.106980 | 2021-01-04T11:51:18 | 2021-01-04T11:51:18 | 326,667,249 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,298 | py | from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "Shiny Block"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">Shiny Block</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "shiny-block-1.herokuapp.com"
site_params = {
"name": "Shiny Block",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
| [
"lorence@crowdbotics.com"
] | lorence@crowdbotics.com |
99f471c3fbb40c19903e3f7b38741578d0324710 | 2e74c7339c63385172629eaa84680a85a4731ee9 | /infertility/male_attr.py | 59775495fac01fe5138790d83275bb10332c138e | [] | no_license | zhusui/ihme-modeling | 04545182d0359adacd22984cb11c584c86e889c2 | dfd2fe2a23bd4a0799b49881cb9785f5c0512db3 | refs/heads/master | 2021-01-20T12:30:52.254363 | 2016-10-11T00:33:36 | 2016-10-11T00:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,587 | py | import os
import argparse
os.chdir(os.path.dirname(os.path.realpath(__file__)))
from job_utils import draws, parsers
##############################################################################
# class to calculate attribution
##############################################################################
class AttributeMale(draws.SquareImport):
def __init__(self, me_map, **kwargs):
# super init
super(AttributeMale, self).__init__(**kwargs)
# store data by me in this dict key=me_id, val=dataframe
self.me_map = me_map
self.me_dict = {}
# import every input
for v in me_map.values():
inputs = v.get("srcs", {})
for me_id in inputs.values():
self.me_dict[me_id] = self.import_square(
gopher_what={"modelable_entity_ids": [me_id]},
source="dismod")
def calc_residual(self):
# compile keys
env_prim_key = self.me_map["env"]["srcs"]["prim"]
env_sec_key = self.me_map["env"]["srcs"]["sec"]
kline_bord_key = self.me_map["kline"]["srcs"]["bord"]
kline_mild_key = self.me_map["kline"]["srcs"]["mild"]
kline_asym_key = self.me_map["kline"]["srcs"]["asym"]
idio_prim_key = self.me_map["idio"]["trgs"]["prim"]
idio_sec_key = self.me_map["idio"]["trgs"]["sec"]
# sum up klinefelter
sigma_kline = (
self.me_dict[kline_bord_key] + self.me_dict[kline_mild_key] +
self.me_dict[kline_asym_key])
# subtract klinefleter from total primary
self.me_dict[idio_prim_key] = self.me_dict[env_prim_key] - sigma_kline
self.me_dict[idio_sec_key] = self.me_dict[env_sec_key]
##############################################################################
# function to run attribution
##############################################################################
def male_attribution(me_map, year_id, out_dir):
# declare calculation dimensions
dim = AttributeMale.default_idx_dmnsns
dim["year_id"] = year_id
dim["measure_id"] = [5]
dim["sex_id"] = [1]
# run attribution
attributer = AttributeMale(me_map=me_map, idx_dmnsns=dim)
attributer.calc_residual()
# save results to disk
for mapper in me_map.values():
outputs = mapper.get("trgs", {})
for me_id in outputs.values():
fname = str(year_id[0]) + ".h5"
out_df = attributer.me_dict[me_id].reset_index()
out_df.to_hdf(os.path.join(out_dir, str(me_id), fname), key="data",
format="table", data_columns=dim.keys())
##############################################################################
# when called as a script
##############################################################################
if __name__ == "__main__":
# parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("--me_map", help="json style string map of ops",
required=True, type=parsers.json_parser)
parser.add_argument("--out_dir", help="root directory to save stuff",
required=True)
parser.add_argument("--year_id", help="which location to use",
type=parsers.int_parser, nargs="*", required=True)
args = vars(parser.parse_args())
# call function
male_attribution(me_map=args["me_map"], out_dir=args["out_dir"],
year_id=args["year_id"])
| [
"nsidles@uw.edu"
] | nsidles@uw.edu |
d592e11371f738e326662c96b83751e6fe5f369f | f6bc15034ee1809473279c87e13cc3131bc3675c | /reader/migrations/0008_chapter_views.py | cb0aeea0af86abf7285e39283b5f7ac21f6a41cf | [
"MIT"
] | permissive | mangadventure/MangAdventure | d92e4c184d1ad91983cf650aa7fa584ba9b977ce | e9da91d0309eacca9fbac8ef72356fe35407b795 | refs/heads/master | 2023-07-20T04:54:49.215457 | 2023-07-14T15:34:20 | 2023-07-14T15:34:20 | 144,012,269 | 70 | 16 | MIT | 2022-08-13T12:22:39 | 2018-08-08T12:43:19 | Python | UTF-8 | Python | false | false | 444 | py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('reader', '0007_series_licensed')]
operations = [
migrations.AddField(
model_name='chapter',
name='views',
field=models.PositiveIntegerField(
db_index=True, default=0, editable=False,
help_text='The total views of the chapter.'
),
),
]
| [
"chronobserver@disroot.org"
] | chronobserver@disroot.org |
7f7ae6f458cc8b68f26e89c645ab071ca90deb65 | 0199004d124f05c820a39af7914d57c3b53a44ff | /instagram/urls.py | 96937019d58b89e8d2fa9c66381ddbb822b51d97 | [
"MIT"
] | permissive | AnumAsif/instagram | ae6e4ffb7ce7aa2df5025f19fd25eef73fb62702 | 619731f799109b216e6ae0f75a4edd8057aa340c | refs/heads/master | 2022-12-10T13:03:39.219406 | 2019-03-14T09:30:33 | 2019-03-14T09:30:33 | 174,493,800 | 0 | 0 | null | 2022-12-08T04:51:45 | 2019-03-08T07:58:40 | Python | UTF-8 | Python | false | false | 1,046 | py |
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^home/$', views.home, name = 'home'),
url(r'^$',views.signup, name='signup'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.activate, name='activate'),
url(r'profile/(?P<username>\w+)', views.profile, name='profile'),
url(r'post/$', views.addpost, name='add_post'),
url(r'^likes/(\d+)/$', views.like, name='like'),
url(r'^comments/(\d+)/$', views.comment, name='add_comment'),
url(r'^search/', views.search, name="search"),
url(r'^accounts/edit/',views.edit_profile, name='edit_profile'),
url(r'^image/(?P<image_id>\d+)', views.image, name='image'),
url(r'^profile/(?P<user>\w+)/$', views.follow, name='follow')
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| [
"anum@cockar.com"
] | anum@cockar.com |
77f2499232cafc4fe32a56e198bb85a9b79b4c31 | 3fbbd07f588aaeca78f18a4567b2173ce0154a85 | /contours.py | 6a57fb5fac998614e8a1a363cd6813b7e554a908 | [
"MIT"
] | permissive | MuAuan/read_keiba_paper | d0af6e7454da04e89ad3080649df0436f09e26a6 | b7c523f5880d1b4d1d397450baaefddbbdd6cfff | refs/heads/master | 2020-06-10T23:51:11.406246 | 2019-07-30T07:20:57 | 2019-07-30T07:20:57 | 193,795,441 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,974 | py | import numpy as np
import cv2
import matplotlib.pyplot as plt
import os, shutil, time, cv2, math
import csv
from operator import attrgetter
from operator import itemgetter
output_root_path = './text_detection/data'
if not os.path.exists(output_root_path):os.mkdir(output_root_path)
output_root_path += '/takaraduka'
if not os.path.exists(output_root_path):os.mkdir(output_root_path)
output_root_path += '/20190622_9'
if not os.path.exists(output_root_path):os.mkdir(output_root_path)
output_root_path += '/'
input_original_data = './text_detection/data/raw/kiseki.jpg' #kiseki_oosaka.jpg'
img = cv2.imread(input_original_data)
cv2.imshow("img",img)
h, s, gray = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
size = (3, 3)
blur = cv2.GaussianBlur(gray, size, 0)
cv2.imwrite(output_root_path + '1_blur.jpg', blur)
lap = cv2.Laplacian(blur, cv2.CV_8UC1)
cv2.imwrite(output_root_path + '2_laplacian.jpg', lap)
# Otsu's thresholding
ret2, th2 = cv2.threshold(lap, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) #lap
cv2.imwrite(output_root_path + '3_th2.jpg', th2)
kernel = np.ones((3, 8), np.uint8) #(3, 20)
closing = cv2.morphologyEx(th2, cv2.MORPH_CLOSE, kernel)
cv2.imwrite(output_root_path + '4_closing.jpg', closing)
kernel = np.ones((3, 3), np.uint8)
dilation = cv2.dilate(closing, kernel, iterations = 1) #closing
cv2.imwrite(output_root_path + '5_dilation.jpg', dilation)
erosion = cv2.erode(dilation, kernel, iterations = 1)
cv2.imwrite(output_root_path + '6_erosion.jpg', erosion)
lap2 = cv2.Laplacian(erosion, cv2.CV_8UC1)
cv2.imwrite(output_root_path + '7_laplacian_2.jpg', lap2)
contours, hierarchy = cv2.findContours(lap2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #CV_RETR_TREE
min_area = 30 #img.shape[0] * img.shape[1] * 1e-3 #-4
max_area = 2500 #img.shape[0] * img.shape[1] * 1e-3 #-4
tmp = img.copy()
tmp2 = img.copy()
rect=[]
for i, contour in enumerate(contours):
re = cv2.boundingRect(contour)
print(re)
rect.append(re)
rect=sorted(rect, key=itemgetter(0))
with open(output_root_path +'./rect.csv', 'w', newline='') as f:
writer = csv.writer(f)
#if len(contours) > 0:
for i in range(len(rect)):
print(rect[i][0],rect[i][1],rect[i][2],rect[i][3])
if rect[i][2] < 5 or rect[i][3] < 5:
continue
area = (rect[i][3])*(rect[i][2])
if area < min_area or area > max_area:
continue
roi = tmp[rect[i][1]:rect[i][1]+rect[i][3], rect[i][0]:rect[i][0]+rect[i][2]]
roi=cv2.resize(roi,(5*rect[i][2],5*rect[i][3]),interpolation=cv2.INTER_CUBIC)
cv2.imshow("roi",roi)
img_dst=cv2.rectangle(tmp, (rect[i][0], rect[i][1]), (rect[i][0]+rect[i][2], rect[i][1]+rect[i][3]), (0, 255, 0), 2)
cv2.imshow("IMAGE",img_dst)
writer.writerow(map(lambda x: x, rect[i]))
plt.imshow(tmp)
plt.pause(1)
cv2.imwrite(output_root_path + '8_1_findContours.jpg', tmp)
cv2.imwrite(output_root_path + '8_2_findContours.jpg', tmp2)
| [
"noreply@github.com"
] | MuAuan.noreply@github.com |
4b9e181c5fe7aac13ac618f98100dd7d6fa48825 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02678/s166039907.py | c6ab12488d55986930af9ba0117c10dc1bcf8bd2 | [] | 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 | 423 | py | N, M = map(int, input().split())
route = [[] for _ in range(N)]
sign = [0]*N
#print(route)
for i in range(M):
a,b = map(int, input().split())
route[a-1].append(b-1)
route[b-1].append(a-1)
#print(route)
marked = {0}
q = [0]
for i in q:
for j in route[i]:
if j in marked:
continue
q.append(j)
marked.add(j)
sign[j] = i+1
print('Yes')
[print(i) for i in sign[1:]] | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
e2cad7806874150acb3e00e8b4608cc4353915a9 | ee81f6a67eba2d01ca4d7211630deb621c78189d | /my_profile/manage.py | b4a7631a6dfab5e670a48068f1d1f80597c22456 | [] | no_license | zkan/saksiam-django-workshop | d452fa0ffec687a287965988a9afe256222a7920 | ccef5359e04693681040c482865350720fa49189 | refs/heads/main | 2023-06-07T00:17:02.524926 | 2021-06-28T15:43:22 | 2021-06-28T15:43:22 | 374,397,011 | 1 | 1 | null | 2021-06-28T15:43:23 | 2021-06-06T15:33:50 | Python | UTF-8 | Python | false | false | 1,062 | py | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django # noqa
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
# This allows easy placement of apps within the interior
# {{ cookiecutter.project_slug }} directory.
current_path = Path(__file__).parent.resolve()
sys.path.append(str(current_path / "my_profile"))
execute_from_command_line(sys.argv) | [
"zkan.cs@gmail.com"
] | zkan.cs@gmail.com |
00706a0ce78e5eee13d25f0e6fae2b55a8f50fe9 | 6ce826375d4ecc7b15cd843a0bf85438db7d1389 | /cbmcfs3_runner/scenarios/demand_plus_minus.py | 05177670f00eb079ad601a2bbc5d8ca5533566b6 | [
"MIT"
] | permissive | xapple/cbmcfs3_runner | b34aaeeed34739d2d94d4ee485f4973403aa6843 | ec532819e0a086077475bfd479836a378f187f6f | refs/heads/master | 2021-12-26T07:06:02.073775 | 2021-10-25T14:15:53 | 2021-10-25T14:15:53 | 172,949,685 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,759 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC biomass Project.
Unit D1 Bioeconomy.
"""
# Built-in modules #
# First party modules #
from plumbing.cache import property_cached
# Internal modules #
from cbmcfs3_runner.scenarios.base_scen import Scenario
from cbmcfs3_runner.core.runner import Runner
###############################################################################
class DemandPlusMinus(Scenario):
"""
This scenario is similar to the `static_demand` scenario. Except that it
multiples said demand by a variable ratio before running the model.
Either increasing the demand or reducing it.
"""
demand_ratio = 1.0
@property_cached
def runners(self):
"""A dictionary of country codes as keys with a list of runners as values."""
# Create all runners #
result = {c.iso2_code: [Runner(self, c, 0)] for c in self.continent}
# Modify these runners #
for country in self.continent:
# Get the maker #
runner = result[country.iso2_code][-1]
dist_maker = runner.pre_processor.disturbance_maker
# Adjust the artificial ratios #
dist_maker.irw_artificial_ratio = self.demand_ratio
dist_maker.fw_artificial_ratio = self.demand_ratio
# Don't modify these runners #
return result
###############################################################################
class DemandPlus20(DemandPlusMinus):
short_name = 'demand_plus_20'
demand_ratio = 1.2
###############################################################################
class DemandMinus20(DemandPlusMinus):
short_name = 'demand_minus_20'
demand_ratio = 0.8
| [
"649288+xapple@users.noreply.github.com"
] | 649288+xapple@users.noreply.github.com |
e7d80b8d7f8bb438a4b24d5e18068fb5eefecd31 | 43acaf9718b0a62594ed8e42b6c01099acd2d075 | /apps/asistencias/migrations/0003_auto_20200402_1450.py | 0de223587557a923ebbda4dff048d594001e03b5 | [] | no_license | JmSubelza/Demo | 2f357889975c183b4a0f627330a80e535823faea | affceeadb87f1f14fb4e481851a1ac107e512f48 | refs/heads/master | 2023-05-14T18:16:38.153963 | 2020-04-28T16:15:27 | 2020-04-28T16:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 574 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2020-04-02 19:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('asistencias', '0002_auto_20200305_1646'),
]
operations = [
migrations.AlterModelOptions(
name='asistencias',
options={'verbose_name': 'asistencia', 'verbose_name_plural': 'asistencias'},
),
migrations.AlterModelTable(
name='asistencias',
table='asistencia',
),
]
| [
"Chrisstianandres@gmail.com"
] | Chrisstianandres@gmail.com |
5abfe9793871b012e49279286068e81223a85910 | 44d8042c77a8f18c03bec92b619425a0787e3ddb | /Classes/py3intro/EXAMPLES/creating_dicts.py | fc407b28becb13ff2907caaa355638516327a687 | [] | no_license | Jgoschke86/Jay | 3015613770d85d9fa65620cc1d2514357569b9bb | 9a3cd87a5cff35c1f2a4fd6a14949c6f3694e3e2 | refs/heads/master | 2023-05-26T15:49:08.681125 | 2023-04-28T22:16:09 | 2023-04-28T22:16:09 | 215,616,981 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 710 | py | #!/usr/bin/python3
d1 = dict()
d2 = {}
d3 = dict(red=5, blue=10, yellow=1, brown=5, black=12)
airports = { 'IAD': 'Dulles', 'SEA': 'Seattle-Tacoma',
'RDU': 'Raleigh-Durham', 'LAX': 'Los Angeles' }
pairs = [('Washington', 'Olympia'),('Virginia','Richmond'),
('Oregon','Salem'), ('California', 'Sacramento')]
state_caps = dict(pairs)
print(state_caps['Virginia'])
print(d3['red'])
print(airports['LAX'])
airports['SLC'] = 'Salt Lake City'
airports['LAX'] = 'Lost Angels'
print(airports['SLC'])
key = 'PSP'
if key in airports:
print(airports[key])
print(airports.get(key))
print(airports.get(key, 'NO SUCH AIRPORT'))
print(airports.setdefault(key, 'Palm Springs'))
print(key in airports)
| [
"56652104+Jgoschke86@users.noreply.github.com"
] | 56652104+Jgoschke86@users.noreply.github.com |
275e7ee7138368d6558257df45f8773d5533b5f9 | 8e858eea97c8654040552d190574acfc738b66e0 | /tests/test_util.py | 70f815d479ff6bf91ee0eb438df8782123904ec6 | [
"MIT"
] | permissive | Typecraft/casetagger | 73f0105caa7ab8a84e7ae3f84720797966addd31 | b311f33449c8796e656600e8c9f255b40c4c2dce | refs/heads/develop | 2023-01-14T00:28:06.339217 | 2017-05-10T10:44:09 | 2017-05-10T10:44:09 | 65,621,998 | 1 | 0 | MIT | 2022-12-26T20:26:26 | 2016-08-13T14:47:36 | Python | UTF-8 | Python | false | false | 6,592 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from casetagger.util import *
from typecraft_python.models import Text, Morpheme, Phrase, Word
class TestUtil(object):
@classmethod
def setup_class(cls):
pass
def test_get_morphemes_concatenated(self):
morpheme = Morpheme()
morpheme.glosses.append("1SG")
morpheme.glosses.append("3SG")
morpheme.glosses.append("2SG")
concatted = get_glosses_concatenated(morpheme)
assert concatted == "1SG.2SG.3SG"
def test_separate_texts_by_language(self):
text_1 = Text()
text_2 = Text()
text_3 = Text()
text_4 = Text()
text_5 = Text()
text_1.language = "nno"
text_2.language = "eng"
text_3.language = "eng"
text_4.language = "kri"
text_5.language = "nno"
texts = [text_1, text_2, text_3, text_4, text_5]
separated = separate_texts_by_languages(texts)
assert isinstance(separated, dict)
assert "nno" in separated
assert "eng" in separated
assert "kri" in separated
assert isinstance(separated["nno"], list)
assert isinstance(separated["eng"], list)
assert isinstance(separated["kri"], list)
assert text_1 in separated["nno"]
assert text_2 in separated["eng"]
assert text_3 in separated["eng"]
assert text_4 in separated["kri"]
assert text_5 in separated["nno"]
def test_get_text_words(self):
text = Text()
phrase = Phrase()
phrase_1 = Phrase()
word_1 = Word()
word_2 = Word()
word_3 = Word()
word_4 = Word()
phrase.add_word(word_1)
phrase.add_word(word_2)
phrase.add_word(word_3)
phrase_1.add_word(word_4)
text.add_phrase(phrase)
text.add_phrase(phrase_1)
words = get_text_words(text)
assert word_1 in words
assert word_2 in words
assert word_3 in words
assert word_4 in words
def test_get_text_morphemes(self):
text = Text()
phrase_1 = Phrase()
phrase_2 = Phrase()
word_1 = Word()
word_2 = Word()
word_3 = Word()
morpheme_1 = Morpheme()
morpheme_2 = Morpheme()
morpheme_3 = Morpheme()
morpheme_4 = Morpheme()
morpheme_5 = Morpheme()
phrase_1.add_word(word_1)
phrase_2.add_word(word_2)
phrase_2.add_word(word_3)
word_1.add_morpheme(morpheme_1)
word_1.add_morpheme(morpheme_2)
word_2.add_morpheme(morpheme_3)
word_2.add_morpheme(morpheme_4)
word_3.add_morpheme(morpheme_5)
text.add_phrase(phrase_1)
text.add_phrase(phrase_2)
morphemes = get_text_morphemes(text)
assert morpheme_1 in morphemes
assert morpheme_2 in morphemes
assert morpheme_3 in morphemes
assert morpheme_4 in morphemes
assert morpheme_5 in morphemes
def test_get_consecutive_sublists(self):
a_list = list(range(6))
sublists = get_consecutive_sublists_of_length(a_list, 2)
assert sublists == [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
sublists = get_consecutive_sublists_of_length(a_list, 4)
assert sublists == [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
def test_get_consecutive_sublists_around(self):
a_list = list(range(6)) # [0,1,2,3,4,5]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 3, 3)
assert sublists == [[0, 1, 2], [1, 2, 4], [2, 4, 5]]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 0, 3)
assert sublists == [[1, 2, 3]]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 5, 2)
assert sublists == [[3, 4]]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 3, 2)
assert sublists == [[1, 2], [2, 4], [4, 5]]
a_list = a_list + [6] # [0,1,2,3,4,5,6]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 3, 3)
assert sublists == [[0, 1, 2], [1, 2, 4], [2, 4, 5], [4, 5, 6]]
sublists = get_consecutive_sublists_of_length_around_index(a_list, 3, 1)
assert sublists == [[2], [4]]
def test_get_all_prefix_sublists_upto_length(self):
a_list = list(range(6)) # [0,1,2,3,4,5]
sublists = get_all_prefix_sublists_upto_length(a_list, 3, 2)
assert sublists == [[2], [1, 2]]
sublists = get_all_prefix_sublists_upto_length(a_list, 0, 3)
assert sublists == []
sublists = get_all_prefix_sublists_upto_length(a_list, 5, 4)
assert sublists == [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
def test_get_all_suffix_sublists_upto_length(self):
a_list = list(range(6)) # [0,1,2,3,4,5]
sublists = get_all_suffix_sublists_upto_length(a_list, 3, 2)
assert sublists == [[4], [4, 5]]
sublists = get_all_suffix_sublists_upto_length(a_list, 5, 3)
assert sublists == []
sublists = get_all_suffix_sublists_upto_length(a_list, 0, 4)
assert sublists == [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
def test_get_surrounding_sublists_upto_length(self):
a_list = list(range(6)) #[0, 1, 2, 3, 4, 5]
sublists = get_surrounding_sublists_upto_length(a_list, 3, 1)
assert sublists == [[2, 4]]
sublists = get_surrounding_sublists_upto_length(a_list, 3, 2)
assert sublists == [[2, 4], [1, 2, 4, 5]]
sublists = get_surrounding_sublists_upto_length(a_list, 1, 2)
assert sublists == [[0, 2], [0, 2, 3]]
sublists = get_surrounding_sublists_upto_length(a_list, 0, 3)
assert sublists == [[1], [1, 2], [1, 2, 3]]
sublists = get_surrounding_sublists_upto_length([1], 0, 2, filler=[2])
print(sublists)
def test_get_surrounding_sublists_upto_length_with_filler(self):
a_list = list(range(6))
sublists = get_surrounding_sublists_upto_length(a_list, 3, 1, filler=[13])
assert sublists == [[2, 13, 4]]
sublists = get_surrounding_sublists_upto_length(a_list, 1, 2, filler=[97])
assert sublists == [[0, 97, 2], [0, 97, 2, 3]]
def test_standard_0_to_1000_factor_scale(self):
assert standard_0_to_1000_factor_scale(0) == 0
assert standard_0_to_1000_factor_scale(1) == 1
assert standard_0_to_1000_factor_scale(20) > 2
assert standard_0_to_1000_factor_scale(200) > 3
assert standard_0_to_1000_factor_scale(1000) < 4
| [
"tormod.haugland@gmail.com"
] | tormod.haugland@gmail.com |
b193d042f11de77758ebb4740dee22fad21ba1f8 | 684658837ca81a9a906ff8156a28f67b0ed53e81 | /venv/bin/jupyter-serverextension | 5493e28add6cf5377f63b4abb7dde6311928fb15 | [] | no_license | sangramga/djangocon | 30d6d47394daadfa162c5f96bf2e8476e580906d | d67203a7a7be2cefedbd75e080a6737e71a5bad3 | refs/heads/master | 2020-03-17T21:20:35.097025 | 2017-08-15T19:45:47 | 2017-08-15T19:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | #!/Users/lorenamesa/Desktop/bootstrap_ml_project/venv/bin/python3.5
# -*- coding: utf-8 -*-
import re
import sys
from notebook.serverextensions import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"me@lorenamesa.com"
] | me@lorenamesa.com | |
31f6af36af85cf21686384f18d934765ad86235b | e1add42d3095608e73717cddf39646a1eaa62729 | /setup.py | 67db060118ca11d8cd2841bba696b5410defe1a0 | [
"MIT"
] | permissive | PhoenixEra/mbcd | 70870e7a774f649b22bb42810118640333d8c822 | 4be85b964bf02818f2fc83b21f2b339b3fc7a14f | refs/heads/main | 2023-07-01T21:28:00.506563 | 2021-08-04T15:03:06 | 2021-08-04T15:03:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 522 | py | from setuptools import setup, find_packages
REQUIRED = ['numpy', 'pandas', 'matplotlib', 'stable-baselines']
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='mbcd',
version='0.1',
packages=['mbcd',],
install_requires=REQUIRED,
author='LucasAlegre',
author_email='lucasnale@gmail.com',
long_description=long_description,
url='https://github.com/LucasAlegre/mbcd',
license="MIT",
description='Model-Based Reinforcement Learning Context Detection.'
) | [
"lucasnale@gmail.com"
] | lucasnale@gmail.com |
d7f322eb83e4c6777bb715eb2d33ac92cdd6091e | 6146e33102797407ede06ce2daa56c28fdfa2812 | /python/GafferSceneUI/CopyOptionsUI.py | ec82897c8adf729127236f6d11032db45fc406ed | [
"BSD-3-Clause"
] | permissive | GafferHQ/gaffer | e1eb78ba8682bfbb7b17586d6e7b47988c3b7d64 | 59cab96598c59b90bee6d3fc1806492a5c03b4f1 | refs/heads/main | 2023-09-01T17:36:45.227956 | 2023-08-30T09:10:56 | 2023-08-30T09:10:56 | 9,043,124 | 707 | 144 | BSD-3-Clause | 2023-09-14T09:05:37 | 2013-03-27T00:04:53 | Python | UTF-8 | Python | false | false | 2,430 | py | ##########################################################################
#
# Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import Gaffer
import GafferScene
##########################################################################
# Metadata
##########################################################################
Gaffer.Metadata.registerNode(
GafferScene.CopyOptions,
"description",
"""
A node which copies options from a source scene.
""",
plugs = {
"options" : [
"description",
"""
The names of the options to be copied. Names should be
separated by spaces and can use Gaffer's standard wildcards.
""",
],
"source" : [
"description",
"""
The source of the options to be copied.
""",
],
}
)
| [
"thehaddonyoof@gmail.com"
] | thehaddonyoof@gmail.com |
9a4de1381f1804be5dae1d274c222ccdc3d44048 | 21c09799d006ed6bede4123d57d6d54d977c0b63 | /python2/framework/Drawer.py | 3db7fba10a54fe603542ecd1b16e825c7fa55e41 | [] | no_license | corvettettt/DijetRootTreeAnalyzer | 68cb12e6b280957e1eb22c9842b0b9b30ae2c779 | e65624ffc105798209436fc80fb82e2c252c6344 | refs/heads/master | 2021-05-06T09:57:12.816787 | 2019-04-18T15:32:38 | 2019-04-18T15:32:38 | 114,043,763 | 1 | 0 | null | 2017-12-12T22:02:46 | 2017-12-12T22:02:46 | null | UTF-8 | Python | false | false | 1,924 | py | import os
import ROOT as rt
from rootTools import tdrstyle as setTDRStyle
class Drawer():
"""Class to draw overlayed histos for data and signals"""
def __init__(self, hData, hSignal):
print "Drawer::init"
self._hData = hData
self._hSignal = hSignal
self._dataHistos = {}
self._sigHistos = {}
#get the histos
for sample,opts in hData.items():
self._dataHistos[sample] = self.loopfile(opts[0])
for sample,opts in hSignal.items():
self._sigHistos[sample] = self.loopfile(opts[0])
def scalePlots(self, lumi):
for sample,opts in self._hSignal.items():
for histo in self._sigHistos[sample]:
integral = histo.Integral()
if integral > 0:
print opts[1]*lumi/integral
histo.Scale(opts[1]*lumi/integral)
def loopfile(self, infile):
print "Drawer::loopfile",infile
hlist = []
rootFile = rt.TFile(infile)
hnames = [k.GetName() for k in rootFile.GetListOfKeys()]
for name in hnames:
myTh1 = rootFile.Get(name)
myTh1.SetDirectory(0)
hlist.append(myTh1)
return hlist
def setStyle(self):
print "Drawer::setStyle"
setTDRStyle.setTDRStyle()
def addRatioBox(self, histo):
print "Drawer::addRatioBox"
def printPlots(self, outPath):
print "Drawer::printCanvas"
self.setStyle()
for it,dataplot in enumerate(self._dataHistos["data"]):
corrCanvas = rt.TCanvas()
dataplot.Draw()
for mcsample,hlist in self._sigHistos.items():
hlist[it].Draw("sames")
corrCanvas.Print(outPath+'/'+dataplot.GetName()+'.pdf')
#self.addRatioBox()
#def drawSignificance
| [
"zhixing.wang@ttu.edu"
] | zhixing.wang@ttu.edu |
6aa09349aae1917b65ddc6cca2c954c8cddbb364 | bd5303f1fd7a6b8244c9d7f2f9037fd52f55686a | /crawler.py | 08d56a24c3aac2d588ee945756150c353267800b | [] | no_license | mmmmkin/crawler | dfe446871ca09844e1dc8182d370f89cf24d2c78 | 8247270733ebd07284d93539c59e460e3d4458d7 | refs/heads/master | 2020-05-25T11:01:54.044397 | 2019-05-20T12:47:28 | 2019-05-20T12:47:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 628 | py | import ssl
from datetime import datetime
from urllib.request import Request, urlopen
def crawling(url='', encoding='utf-8'):
try:
request = Request(url)
ssl._create_default_https_context = ssl._create_unverified_context
resp = urlopen(request)
try:
receive = resp.read()
result = receive.decode(encoding)
except UnicodeDecodeError:
result = receive.decode(encoding, 'replace')
print('%s : success for reuqest(%s)' % (datetime.now(), url))
return result
except Exception as e:
print('%s : %s' % (e, datetime.now())) | [
"kickscar@gmail.com"
] | kickscar@gmail.com |
a583c5437d4f807b407d482f5e2221cce5862b2f | 677f4896f21c46aee199c9f84c012c9733ece6f6 | /ddsp/losses_test.py | dd4a23020c2d427443b4fb0f729ffa8fa5546d67 | [
"Apache-2.0"
] | permissive | werkaaa/ddsp | 90b2881a350dad9f954e28ead4f145140c7d2ad4 | 92ce8724e22c17822d7f7564547733ed7fe918e2 | refs/heads/master | 2022-12-13T06:41:48.871697 | 2020-09-03T15:50:49 | 2020-09-03T15:50:49 | 286,489,693 | 0 | 0 | Apache-2.0 | 2020-08-10T13:57:00 | 2020-08-10T13:57:00 | null | UTF-8 | Python | false | false | 1,770 | py | # Copyright 2020 The DDSP 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.
# Lint as: python3
"""Tests for ddsp.losses."""
from ddsp import losses
import numpy as np
import tensorflow.compat.v2 as tf
class SpectralLossTest(tf.test.TestCase):
def test_output_shape_is_correct(self):
"""Test correct shape with all losses active."""
loss_obj = losses.SpectralLoss(
mag_weight=1.0,
delta_time_weight=1.0,
delta_freq_weight=1.0,
cumsum_freq_weight=1.0,
logmag_weight=1.0,
loudness_weight=1.0,
)
input_audio = tf.ones((3, 8000), dtype=tf.float32)
target_audio = tf.ones((3, 8000), dtype=tf.float32)
loss = loss_obj(input_audio, target_audio)
self.assertListEqual([], loss.shape.as_list())
self.assertTrue(np.isfinite(loss))
class PretrainedCREPEEmbeddingLossTest(tf.test.TestCase):
def test_output_shape_is_correct(self):
loss_obj = losses.PretrainedCREPEEmbeddingLoss()
input_audio = tf.ones((3, 16000), dtype=tf.float32)
target_audio = tf.ones((3, 16000), dtype=tf.float32)
loss = loss_obj(input_audio, target_audio)
self.assertListEqual([], loss.shape.as_list())
self.assertTrue(np.isfinite(loss))
if __name__ == '__main__':
tf.test.main()
| [
"no-reply@google.com"
] | no-reply@google.com |
09cce8fbbaa41efbc8ae40424576b47d84a05964 | 0e4d09b2a1b93aaa6d623d16905854d993a934ae | /Python/Django/belt_reviewer/apps/bookReviews/admin.py | ac72368c4b888b1d7d074e846a9860e09e00d9d3 | [] | no_license | freefaller69/DojoAssignments | ee7f6308b02041be3244f795422e0e044d4a41b2 | f40426ac448026c1172048665f36024ad22f0d81 | refs/heads/master | 2021-01-17T10:23:39.419514 | 2017-07-25T00:50:41 | 2017-07-25T00:50:41 | 84,012,790 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 261 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Book, Author, Review
# Register your models here.
admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Review)
| [
"freefaller@gmail.com"
] | freefaller@gmail.com |
5686d5a00a202f2b6cb60723f475bbd967b5cc76 | 5b4c803f68e52849a1c1093aac503efc423ad132 | /UnPyc/tests/tests/CFG/2/return/return_if+elif_if+elif+else_.py | 4d3f6e3a97f865aea7e5a8d94a62fe7ad96b04a8 | [] | no_license | Prashant-Jonny/UnPyc | 9ce5d63b1e0d2ec19c1faa48d932cc3f71f8599c | 4b9d4ab96dfc53a0b4e06972443e1402e9dc034f | refs/heads/master | 2021-01-17T12:03:17.314248 | 2013-02-22T07:22:35 | 2013-02-22T07:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 163 | py | def f():
if 1:
if 1:
return
elif 1:
return
elif 1:
if 1:
return
elif 1:
return
else:
if 1:
return
elif 1:
return
| [
"d.v.kornev@gmail.com"
] | d.v.kornev@gmail.com |
e6dddca50724f057823cd02a76e2d1c2cb00d118 | 44e6fecee8710156333e171ad38a2b4d4cd4e3e3 | /2-numpy/ex.5.19.py | d32d0241d72a77738eec995557aa944742c2e792 | [] | no_license | 3141592/data-science | 5b0291ca40b275a1624e699828db5e63b5502b3c | f4f9bec56ee09bbd521b6dbacb0b221693a78637 | refs/heads/master | 2021-05-04T14:43:09.094396 | 2018-02-04T20:31:06 | 2018-02-04T20:31:06 | 120,209,026 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | import numpy as np
print("arr")
arr = np.arange(0,11)
print(arr)
print("=============")
print("arr[8]")
print(arr[8])
print("=============")
print("arr[1:6]: ")
print arr[1:6]
print("=============")
print "arr[:6]"
print arr[:6]
print("=============")
print "arr[0:5] = 100"
arr[0:5] = 100
print arr
print("=============")
arr_2d = np.array([[5,10,15],[20,25,30],[30,35,40]])
print "arr_2d"
print arr_2d
print("=============")
print "arr_2d[0][0]"
print arr_2d[0][0]
print "arr_2d[1][1] = 25"
print arr_2d[1][1]
print "arr_2d[0][2] = 15"
print arr_2d[0][2]
print "arr_2d[0,0]"
print arr_2d[0,0]
print "arr_2d[1,1] = 25"
print arr_2d[1,1]
print "arr_2d[0,2] = 15"
print arr_2d[0,2]
print "=============="
arr3 = (np.random.rand(1,25)*10).reshape(5,5)
print "arr3"
print arr3
print "arr3[:3,2:]"
print arr3[:3,2:]
print "arr3[:3,:2]"
print arr3[:3,:2]
print "=============="
arr = np.arange(1,11)
print "np.arange91,11)"
print arr
print "arr > 5"
print arr > 5
bool_arr = arr > 6
print "bool_arr"
print bool_arr
print "arr[bool_arr]"
print arr[bool_arr]
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
8e3ef950698fbf7d3e8c20133ccd2085180d1c8d | e204cdd8a38a247aeac3d07f6cce6822472bdcc5 | /.history/app_test_django/models_20201116131143.py | ff79574c97012778681ec2385d75639933239b9a | [] | no_license | steven-halla/python-test | 388ad8386662ad5ce5c1a0976d9f054499dc741b | 0b760a47d154078002c0272ed1204a94721c802a | refs/heads/master | 2023-04-08T03:40:00.453977 | 2021-04-09T19:12:29 | 2021-04-09T19:12:29 | 354,122,365 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,333 | py | from django.db import models
import re
class UserManager(models.Manager):
def user_registration_validator(self, post_data):
errors = {}
EMAIL_REGEX = re.compile(
r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(post_data['first_name']) < 3:
errors['first_name'] = "First name must be 3 characters"
if post_data['first_name'].isalpha() == False:
errors['first_name'] = "letters only"
if len(post_data['last_name']) < 3:
errors['last_name'] = "Last name must be 3 characters"
if post_data['last_name'].isalpha() == False:
errors['last_name'] = "letters only"
if len(post_data['email']) < 8:
errors['email'] = "Email must contain 8 characters"
#if post_data['email'].Books.objects.filter(title=post_data) == True:
# errors['email'] ="this email already exist in database"
if post_data['email'].find("@") == -1:
errors['email'] = "email must contain @ and .com"
if post_data['email'].find(".com") == -1:
errors['email'] = "email must contain @ and .com"
# test whether a field matches the pattern
if not EMAIL_REGEX.match(post_data['email']):
errors['email'] = "Invalid email address!"
if post_data['password'] != post_data['confirm_password']:
errors['pass_match'] = "password must match confirm password"
if len(post_data['password']) < 8:
errors['pass_length'] = "password must be longer than 8 characters"
return errors
class User(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
email = models.CharField(max_length=20)
password = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
class TripManager(models.Manager):
def add_trip_validator(self, post_data)
class Trip(models.Model):
destination = models.CharField(max_length=20)
startdate = models.DateTimeField()
enddate = models.DateTimeField()
plan = models.CharField(max_length=30)
uploaded_by = models.ForeignKey(User, related_name="trip_uploaded", on_delete=models.CASCADE)
| [
"69405488+steven-halla@users.noreply.github.com"
] | 69405488+steven-halla@users.noreply.github.com |
7debb913ce33acbbf107e40036794d0f9b9fd499 | affdb1186825486d40c1140314cc04fe63b153b7 | /bike-sharing-demand/preprocessing/preprocessing.py | 1f949627fbcd95c8b691834f548fd29c225a61bb | [] | no_license | Yagami360/kaggle_exercises | 2f9a8a12c48a6e55ded6c626ceef5fb0cfca935b | 17b731bb6f1ce0b81254047ffc56371f4c485df0 | refs/heads/master | 2022-11-22T23:00:27.176123 | 2020-07-23T05:05:00 | 2020-07-23T05:05:00 | 252,343,652 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,293 | py | import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
def preprocessing( args, df_train, df_test ):
# 全データセット
df_data = pd.concat([df_train, df_test], sort=False)
# 時系列データを処理
df_train['year'] = [t.year for t in pd.DatetimeIndex(df_train.datetime)]
df_train['year'] = df_train['year'].map( {2011:0, 2012:1} )
df_train["month"] = [t.month for t in pd.DatetimeIndex(df_train.datetime)]
df_train["day"] = [t.dayofweek for t in pd.DatetimeIndex(df_train.datetime)]
df_train["hour"] = [t.hour for t in pd.DatetimeIndex(df_train.datetime)]
df_train["weekday"] = [t for t in pd.DatetimeIndex(df_train.datetime).weekday]
df_test['year'] = [t.year for t in pd.DatetimeIndex(df_test.datetime)]
df_test['year'] = df_test['year'].map( {2011:0, 2012:1} )
df_test["month"] = [t.month for t in pd.DatetimeIndex(df_test.datetime)]
df_test["day"] = [t.dayofweek for t in pd.DatetimeIndex(df_test.datetime)]
df_test["hour"] = [t.hour for t in pd.DatetimeIndex(df_test.datetime)]
df_test["weekday"] = [t for t in pd.DatetimeIndex(df_test.datetime).weekday]
# 無用なデータを除外
df_train.drop(["casual", "registered"], axis=1, inplace=True)
df_train.drop(["datetime"], axis=1, inplace=True)
df_test.drop(["datetime"], axis=1, inplace=True)
# 全特徴量を一括で処理
for col in df_train.columns:
if( args.debug ):
print( "df_train[{}].dtypes ] : {}".format(col, df_train[col].dtypes))
# 目的変数
if( col in ["count"] ):
if( args.target_norm ):
# 正規分布に従うように対数化
df_train[col] = pd.Series( np.log(df_train[col].values), name=col )
continue
#-----------------------------
# ラベル情報のエンコード
#-----------------------------
if( df_train[col].dtypes == "object" ):
label_encoder = LabelEncoder()
label_encoder.fit(list(df_train[col]))
df_train[col] = label_encoder.transform(list(df_train[col]))
label_encoder = LabelEncoder()
label_encoder.fit(list(df_test[col]))
df_test[col] = label_encoder.transform(list(df_test[col]))
#-----------------------------
# 欠損値の埋め合わせ
#-----------------------------
"""
# NAN 値の埋め合わせ(平均値)
pass
# NAN 値の埋め合わせ(ゼロ値)/ int 型
if( df_train[col].dtypes in ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"] ):
df_train[col].fillna(0, inplace=True)
df_test[col].fillna(0, inplace=True)
# NAN 値の埋め合わせ(ゼロ値)/ float 型
elif( df_train[col].dtypes in ["float16", "float32", "float64", "float128"] ):
df_train[col].fillna(0.0, inplace=True)
df_test[col].fillna(0.0, inplace=True)
# NAN 値の補完(None値)/ object 型
else:
df_train[col] = df_train[col].fillna('NA')
df_test[col] = df_test[col].fillna('NA')
"""
#-----------------------------
# 正規化処理
#-----------------------------
if( args.input_norm ):
#if( df_train[col].dtypes != "object" ):
if( df_train[col].dtypes in ["float16", "float32", "float64", "float128"] ):
scaler = StandardScaler()
scaler.fit( df_train[col].values.reshape(-1,1) )
df_train[col] = scaler.fit_transform( df_train[col].values.reshape(-1,1) )
df_test[col] = scaler.fit_transform( df_test[col].values.reshape(-1,1) )
#-----------------------------
# 値が単一の特徴量をクレンジング
#-----------------------------
if( df_train[col].nunique() == 1 ):
print( "remove {} : {}".format(col,df_train[col].nunique()) )
df_train.drop([col], axis=1, inplace=True)
df_test.drop([col], axis=1, inplace=True)
return df_train, df_test
| [
"y034112@gmail.com"
] | y034112@gmail.com |
7dc2bc6f99ef24ea573366cb23999dea0e981450 | ed54290846b5c7f9556aacca09675550f0af4c48 | /salt/salt/modules/win_path.py | 7e1601e22563416628aa2d70fd625b8e953dbe4f | [
"Apache-2.0"
] | permissive | smallyear/linuxLearn | 87226ccd8745cd36955c7e40cafd741d47a04a6f | 342e5020bf24b5fac732c4275a512087b47e578d | refs/heads/master | 2022-03-20T06:02:25.329126 | 2019-08-01T08:39:59 | 2019-08-01T08:39:59 | 103,765,131 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,719 | py | # -*- coding: utf-8 -*-
'''
Manage the Windows System PATH
Note that not all Windows applications will rehash the PATH environment variable,
Only the ones that listen to the WM_SETTINGCHANGE message
http://support.microsoft.com/kb/104011
'''
from __future__ import absolute_import
# Python Libs
import logging
import re
import os
from salt.ext.six.moves import map
# Third party libs
try:
import win32gui
import win32con
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Import salt libs
import salt.utils
# Settings
log = logging.getLogger(__name__)
def __virtual__():
'''
Load only on Windows
'''
if salt.utils.is_windows() and HAS_WIN32:
return 'win_path'
return False
def _normalize_dir(string):
'''
Normalize the directory to make comparison possible
'''
return re.sub(r'\\$', '', string.lower())
def rehash():
'''
Send a WM_SETTINGCHANGE Broadcast to Windows to refresh the Environment variables
CLI Example:
... code-block:: bash
salt '*' win_path.rehash
'''
return win32gui.SendMessageTimeout(win32con.HWND_BROADCAST,
win32con.WM_SETTINGCHANGE,
0,
'Environment',
0,
10000)[0] == 1
def get_path():
'''
Returns a list of items in the SYSTEM path
CLI Example:
.. code-block:: bash
salt '*' win_path.get_path
'''
ret = __salt__['reg.read_value']('HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',
'PATH')['vdata'].split(';')
# Trim ending backslash
return list(map(_normalize_dir, ret))
def exists(path):
'''
Check if the directory is configured in the SYSTEM path
Case-insensitive and ignores trailing backslash
Returns:
boolean True if path exists, False if not
CLI Example:
.. code-block:: bash
salt '*' win_path.exists 'c:\\python27'
salt '*' win_path.exists 'c:\\python27\\'
salt '*' win_path.exists 'C:\\pyThon27'
'''
path = _normalize_dir(path)
sysPath = get_path()
return path in sysPath
def add(path, index=0):
'''
Add the directory to the SYSTEM path in the index location
Returns:
boolean True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
# Will add to the beginning of the path
salt '*' win_path.add 'c:\\python27' 0
# Will add to the end of the path
salt '*' win_path.add 'c:\\python27' index='-1'
'''
currIndex = -1
sysPath = get_path()
path = _normalize_dir(path)
index = int(index)
# validate index boundaries
if index < 0:
index = len(sysPath) + index + 1
if index > len(sysPath):
index = len(sysPath)
localPath = os.environ["PATH"].split(os.pathsep)
if path not in localPath:
localPath.append(path)
os.environ["PATH"] = os.pathsep.join(localPath)
# Check if we are in the system path at the right location
try:
currIndex = sysPath.index(path)
if currIndex != index:
sysPath.pop(currIndex)
else:
return True
except ValueError:
pass
# Add it to the Path
sysPath.insert(index, path)
regedit = __salt__['reg.set_value'](
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',
'PATH',
';'.join(sysPath),
'REG_EXPAND_SZ'
)
# Broadcast WM_SETTINGCHANGE to Windows
if regedit:
return rehash()
else:
return False
def remove(path):
r'''
Remove the directory from the SYSTEM path
Returns:
boolean True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
# Will remove C:\Python27 from the path
salt '*' win_path.remove 'c:\\python27'
'''
path = _normalize_dir(path)
sysPath = get_path()
localPath = os.environ["PATH"].split(os.pathsep)
if path in localPath:
localPath.remove(path)
os.environ["PATH"] = os.pathsep.join(localPath)
try:
sysPath.remove(path)
except ValueError:
return True
regedit = __salt__['reg.set_value'](
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',
'PATH',
';'.join(sysPath),
'REG_EXPAND_SZ'
)
if regedit:
return rehash()
else:
return False
| [
"5931263123@163.com"
] | 5931263123@163.com |
82097c0eafbc46e1235c7382b6d048e7d4ef8aa8 | eec267b544295bccb2ab88b13b221ff4fd3d2985 | /test_plot_rms_map.py | c6bf17198c876c8af1635ee13bbe3c644bcfd488 | [] | no_license | ralfcam/sandbox_scripts | dda368dcf8b8d01147660dedc6d0fcae2d15f80c | 6fa53a63152c4a00396b38fb92ae7dc6f72d6b90 | refs/heads/master | 2022-05-29T02:02:24.849913 | 2020-05-01T02:23:57 | 2020-05-01T02:23:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,219 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 28 13:42:25 2018
@author: jpeacock
"""
import mtpy.modeling.modem as modem
import matplotlib.pyplot as plt
import scipy.interpolate as interpolate
import numpy as np
res_fn = r"c:\\Users\\jpeacock\\Documents\\Geothermal\\Umatilla\\modem_inv\\inv_03\\um_err03_cov03_NLCG_130.res"
prms = modem.PlotRMSMaps(res_fn, plot_yn='n')
#prms.period_index = 15
#prms.plot_map()
prms.plot_loop(style='map', fig_format='pdf')
#d = modem.Data()
#d.read_data_file(res_fn)
#
#lat = d.data_array['lat']
#lon = d.data_array['lon']
#rms_arr = d.data_array['z'][:, 0, 0, 1].__abs__()/d.data_array['z_err'][:, 0, 0, 1].real
#
#x = np.linspace(lon.min(), lon.max(), 100)
#y = np.linspace(lat.min(), lat.max(), 100)
#
#grid_x, grid_y = np.meshgrid(x, y)
#
#points = np.array([lon, lat])
#
#rms_map = interpolate.griddata(points.T,
# np.nan_to_num(rms_arr),
# (grid_x, grid_y),
# method='cubic')
#
#fig = plt.figure(3)
#fig.clf()
#ax = fig.add_subplot(1, 1, 1, aspect='equal')
#im = ax.pcolormesh(grid_x, grid_y, rms_map, cmap='jet', vmin=0, vmax=5)
#plt.colorbar(im, ax=ax, shrink=.6)
#plt.show()
| [
"peacock.jared@gmail.com"
] | peacock.jared@gmail.com |
f28154c1d8284b4c1afcf2b115181573d4880ff2 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5658282861527040_0/Python/ChevalierMalFet/lottery.py | 187e6b8d05f410b95b0987ef03b00f8a8567c866 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 509 | py | inputFile = open('B-small-attempt0.in', 'r')
outputFile = open('B-small-attempt0.out', 'w')
numTests = int(inputFile.readline())
for i in range(numTests):
nums = map(lambda x: int(x), inputFile.readline().split())
a = nums[0]
b = nums[1]
k = nums[2]
count = 0
for m in range(a):
for n in range(b):
if m&n < k:
count += 1
outputFile.write('Case #'+str(i+1)+': ' + str(count) + '\n')
inputFile.close()
outputFile.close()
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
211199e7bff2d13c497e7a08f172ffc279744939 | 3dcf3b4d1822fefc0dcab8195af1239abe7971a1 | /AMAO/apps/Avaliacao/Questao/views/__init__.py | 554a3a1467bf3ffcd4b9de57c04ac01067e84fd5 | [
"MIT"
] | permissive | arruda/amao | a1b0abde81be98a04dee22af9ff0723ed7697fb8 | 83648aa2c408b1450d721b3072dc9db4b53edbb8 | refs/heads/master | 2021-01-13T02:11:52.776011 | 2014-09-20T15:43:16 | 2014-09-20T15:43:16 | 23,271,083 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 134 | py | #from temporario import *
from resolucao import *
from gabarito import *
from criar import *
from exibir import *
from listar import * | [
"felipe.arruda.pontes@gmail.com"
] | felipe.arruda.pontes@gmail.com |
de77b537516f29eb8f057077717c9b426ad9d33f | a4e4c3faa29043fc80f62a8442e2f8333cd23933 | /MPI_test.py | 5801da732e8dd08ddffe0d60fb141f04be8e6599 | [] | no_license | FangYang970206/Intrinsic_Image | 652ab87c2d95b400cf80c6a49d1863a40d1cba07 | 3b8ec261b7b3aeaa1c611473f53fb4e23b82893b | refs/heads/master | 2023-01-21T05:18:40.748488 | 2020-11-24T02:22:00 | 2020-11-24T02:22:00 | 228,824,635 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,477 | py | import os
import random
import argparse
import torch
import torch.optim as optim
from tensorboardX import SummaryWriter
from torch.backends import cudnn
# import RIN
import RIN
import RIN_pipeline
import numpy as np
import scipy.misc
from utils import *
def main():
random.seed(9999)
torch.manual_seed(9999)
cudnn.benchmark = True
parser = argparse.ArgumentParser()
parser.add_argument('--split', type=str, default='ImageSplit')
parser.add_argument('--mode', type=str, default='test')
parser.add_argument('--save_path', type=str, default='MPI_logs\\RIID_origin_RIN_updateLR_CosBF_VGG0.1_shading_epoch240_ImageSplit_size256\\',
help='save path of model, visualizations, and tensorboard')
parser.add_argument('--loader_threads', type=float, default=8,
help='number of parallel data-loading threads')
parser.add_argument('--state_dict', type=str, default='composer_state_231.t7')
args = parser.parse_args()
# pylint: disable=E1101
device = torch.device("cuda: 1" if torch.cuda.is_available() else 'cpu')
# pylint: disable=E1101
shader = RIN.Shader(output_ch=3)
reflection = RIN.Decomposer()
composer = RIN.Composer(reflection, shader).to(device)
# RIN.init_weights(composer, init_type='kaiming')
# MPI_Image_Split_test_txt = 'D:\\fangyang\\intrinsic_by_fangyang\\MPI_TXT\\MPI_main_imageSplit-fullsize-ChenSplit-test.txt'
# MPI_Scene_Split_test_txt = 'D:\\fangyang\\intrinsic_by_fangyang\\MPI_TXT\\MPI_main_sceneSplit-fullsize-NoDefect-test.txt'
MPI_Image_Split_test_txt = 'D:\\fangyang\\intrinsic_by_fangyang\\MPI_TXT\\MPI_main_imageSplit-256-test.txt'
MPI_Scene_Split_test_txt = 'D:\\fangyang\\intrinsic_by_fangyang\\MPI_TXT\\MPI_main_sceneSplit-256-test.txt'
if args.split == 'ImageSplit':
test_txt = MPI_Image_Split_test_txt
print('Image split mode')
else:
test_txt = MPI_Scene_Split_test_txt
print('Scene split mode')
composer.load_state_dict(torch.load(os.path.join(args.save_path, args.state_dict)))
print('load checkpoint success!')
test_set = RIN_pipeline.MPI_Dataset_Revisit(test_txt)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=1, num_workers=args.loader_threads, shuffle=False)
check_folder(os.path.join(args.save_path, "refl_target"))
check_folder(os.path.join(args.save_path, "shad_target"))
check_folder(os.path.join(args.save_path, "refl_output"))
check_folder(os.path.join(args.save_path, "shad_output"))
check_folder(os.path.join(args.save_path, "shape_output"))
check_folder(os.path.join(args.save_path, "mask"))
composer.eval()
with torch.no_grad():
for ind, tensors in enumerate(test_loader):
print(ind)
inp = [t.to(device) for t in tensors]
input_g, albedo_g, shading_g, mask_g = inp
_, albedo_fake, shading_fake, shape_fake = composer.forward(input_g)
albedo_fake = albedo_fake*mask_g
lab_refl_targ = albedo_g.squeeze().cpu().numpy().transpose(1,2,0)
lab_sha_targ = shading_g.squeeze().cpu().numpy().transpose(1,2,0)
mask = mask_g.squeeze().cpu().numpy().transpose(1,2,0)
refl_pred = albedo_fake.squeeze().cpu().numpy().transpose(1,2,0)
sha_pred = shading_fake.squeeze().cpu().numpy().transpose(1,2,0)
shape_pred = shape_fake.squeeze().cpu().numpy().transpose(1,2,0)
lab_refl_targ = np.clip(lab_refl_targ, 0, 1)
lab_sha_targ = np.clip(lab_sha_targ, 0, 1)
refl_pred = np.clip(refl_pred, 0, 1)
sha_pred = np.clip(sha_pred, 0, 1)
shape_pred = np.clip(shape_pred, 0, 1)
mask = np.clip(mask, 0, 1)
scipy.misc.imsave(os.path.join(args.save_path, "refl_target", "{}.png".format(ind)), lab_refl_targ)
scipy.misc.imsave(os.path.join(args.save_path, "shad_target", "{}.png".format(ind)), lab_sha_targ)
scipy.misc.imsave(os.path.join(args.save_path, "mask", "{}.png".format(ind)), mask)
scipy.misc.imsave(os.path.join(args.save_path, "refl_output", "{}.png".format(ind)), refl_pred)
scipy.misc.imsave(os.path.join(args.save_path, "shad_output", "{}.png".format(ind)), sha_pred)
scipy.misc.imsave(os.path.join(args.save_path, "shape_output", "{}.png".format(ind)), shape_pred)
if __name__ == "__main__":
main()
| [
"15270989505@163.com"
] | 15270989505@163.com |
0b4f08bcee570cf762e0b682205d8fdcec785a9e | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_289/ch88_2020_05_11_13_11_45_850336.py | 5e8eda89358bc1e91ffb03476a4549962854f650 | [] | 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 | 241 | py | class Retangulo:
def calcula_perimetro(self):
dy = self.y - self.x
dx = self.x - self.y
return 2*dx + 2*dy
def calcula_area(self):
dy = self.y - self.x
dx = self.x - self.y
return dx*dy | [
"you@example.com"
] | you@example.com |
e8bfec56b5c39e4bd3a759a4a033e6502c721abf | e5bc2c2c7ce172bf66cb526e6a27578e2919b807 | /python/libs/r.py | c314af5e861f0aee2ddfd68a42af50f714b87c8b | [] | no_license | github188/libs-1 | c561c3e8875f2fed3351692af62f833585e95511 | 83bfeeb29e9fafdd274ef645d2602f81290fd9e2 | refs/heads/master | 2020-05-29T11:43:55.629814 | 2016-03-04T11:11:41 | 2016-03-04T11:11:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | #! python
import re
import sys
def MatchString(p,s):
spat = re.compile(p)
if spat.search(s):
print '(%s) match (%s)'%(p,s)
sarr = re.findall(p,s)
print 'match (%s) (%s) (%s)'%(p,s,repr(sarr))
else:
print '(%s) not match (%s)'%(p,s)
if __name__ == '__main__':
MatchString(sys.argv[1],sys.argv[2])
| [
"jeppeter@gmail.com"
] | jeppeter@gmail.com |
fdef8858fee95042d8bf62e3cc9b60a763ae012f | cd557e3c2b34f30f2e7caf7c79c07ff6e109fbd3 | /k2/addons/k2-monitor/monitor/__init__.py | 0ffee09d23f4e86d8b089538069e89f0c4c99707 | [
"Apache-2.0"
] | permissive | Zenterio/opensourcelib | f005174c049df0f5deddc1269d7c343a8e219ca5 | 07f0dabffaceb7b6202b5f691cbad46dac5868a8 | refs/heads/master | 2022-12-09T02:53:36.444094 | 2021-04-28T18:03:24 | 2021-05-27T13:14:58 | 186,092,997 | 5 | 6 | NOASSERTION | 2022-12-07T23:37:26 | 2019-05-11T05:44:37 | Groovy | UTF-8 | Python | false | false | 290 | py | from zaf.messages.message import EndpointId, MessageId
MONITOR_ENDPOINT = EndpointId('monitor', """\
The K2 monitor addon endpoint.
""")
PERFORM_MEASUREMENT = MessageId(
'PERFORM_MEASUREMENT', """
Request that a monitor performs its measurements.
data: None
""")
| [
"per.bohlin@zenterio.com"
] | per.bohlin@zenterio.com |
66e68b0679a6c7ab9e1e751a07a8086ef46b0705 | f0d3ef10061147fb3bd04774a8b4eac9e4d9b671 | /feedly/serializers/cassandra/activity_serializer.py | 9e1d0ac4a1564c446dc88d23ab34e3b65db56800 | [
"BSD-3-Clause"
] | permissive | jblomo/Feedly | 9929077be3364d827aa03c4506ade29b819141cb | 3e4999cc794231841e3b4909f0a73beabfcca046 | refs/heads/master | 2021-01-20T21:19:21.017683 | 2013-09-06T12:33:48 | 2013-09-06T12:33:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 972 | py | from feedly.activity import Activity
from feedly.storage.cassandra.maps import ActivityMap
from feedly.verbs import get_verb_by_id
import pickle
from feedly.serializers.base import BaseSerializer
class CassandraActivitySerializer(BaseSerializer):
def dumps(self, activity):
return ActivityMap(
key=str(activity.serialization_id),
actor=activity.actor_id,
time=activity.time,
verb=activity.verb.id,
object=activity.object_id,
target=activity.target_id,
extra_context=pickle.dumps(activity.extra_context)
)
def loads(self, serialized_activity):
activity_kwargs = serialized_activity.__dict__.copy()
activity_kwargs.pop('key')
activity_kwargs['verb'] = get_verb_by_id(activity_kwargs['verb'])
activity_kwargs['extra_context'] = pickle.loads(
activity_kwargs['extra_context'])
return Activity(**activity_kwargs)
| [
"thierryschellenbach@gmail.com"
] | thierryschellenbach@gmail.com |
df16df9b7b4a3e8e07986df56e4f464254235aaa | 0090756d7a6eb6ab8389ad23b20e89cd68dbd0e4 | /배열정렬.py | 2be7e2bad6cda422e8b99414109ecc6efe66010d | [] | no_license | ssh6189/2019.12.16 | 5c3093e03ac793d5f0a93cf99e78c6483fcee6d8 | c1021bb72b3fdc05d7f5e8ae350bbd6eee65b0d3 | refs/heads/master | 2020-12-13T19:19:04.558270 | 2020-01-17T08:47:04 | 2020-01-17T08:47:04 | 234,507,219 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 517 | py | import numpy as np
#ndarray 객체는 axis를 기준으로 요소 정렬하는 sort 함수를 제공합니다.
unsorted_arr = np.random.random((3, 3))
print(unsorted_arr)
#데모를 위한 배열 복사
unsorted_arr1 = unsorted_arr.copy()
unsorted_arr2 = unsorted_arr.copy()
unsorted_arr3 = unsorted_arr.copy()
unsorted_arr1.sort() #배열 정렬
print(unsorted_arr1)
unsorted_arr2.sort(axis=0) #배열 정렬, axis=0
print(unsorted_arr2)
unsorted_arr3.sort(axis=1) #배열 정렬, axis=1
print(unsorted_arr3)
| [
"ssh6189@naver.com"
] | ssh6189@naver.com |
992d39d8e5c5649b6954e1bd952fb77fbc4f0cb5 | 768c3fd42e0d3b407d89ccd9a3b3ace9eb0414c5 | /user/migrations/0004_city.py | 5c51ffa30bf5c417f1dc9f699aad8d54ad519165 | [] | no_license | samkayz/LocationAPi | a644a45c6eb4ba6fb198b9992b5b79a89d6d9960 | e7d601467e73ab127c61be257c2354dcd3aee21c | refs/heads/master | 2023-08-14T03:33:32.574732 | 2020-05-03T18:38:08 | 2020-05-03T18:38:08 | 260,606,040 | 0 | 0 | null | 2021-09-22T18:57:32 | 2020-05-02T03:27:12 | JavaScript | UTF-8 | Python | false | false | 761 | py | # Generated by Django 3.0.5 on 2020-05-02 02:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0003_auto_20200430_1954'),
]
operations = [
migrations.CreateModel(
name='City',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('city', models.CharField(max_length=100)),
('lat', models.CharField(max_length=100)),
('lng', models.CharField(max_length=100)),
('state', models.CharField(max_length=100)),
],
options={
'db_table': 'city',
},
),
]
| [
"ilemobayosamson@gmail.com"
] | ilemobayosamson@gmail.com |
3d294da817dabde94948c630eda7e6f79b1cf950 | 233f97c6f360d478bf975016dd9e9c2be4a64adb | /guvi_4_1_3.py | 00eb925ae9c76c8511522e660cf1e63382c44343 | [] | no_license | unknownboyy/GUVI | 3dbd1bb2bc6b3db52f5f79491accd6c56a2dec45 | d757dd473c4f5eef526a516cf64a1757eb235869 | refs/heads/master | 2020-03-27T00:07:12.449280 | 2019-03-19T12:57:03 | 2019-03-19T12:57:03 | 145,595,379 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 418 | py | s1,s2=input().split()
column=len(s1)+1
row=len(s2)+1
c=[[0 for i in range(column)] for i in range(row)]
for i in range(1,row):
c[i][0]=i
for i in range(1,column):
c[0][i]=i
for i in range(1,row):
for j in range(1,column):
if s2[i-1]==s1[j-1]:
c[i][j]=min(c[i-1][j-1],c[i-1][j],c[i][j-1])
else:
c[i][j]=min(c[i-1][j-1],c[i-1][j],c[i][j-1])+1
print(c[row-1][column-1]) | [
"ankitagrawal11b@gmail.com"
] | ankitagrawal11b@gmail.com |
0cc0ef34f5666bda22936a734d144ace9100a9b7 | 9d123c6b87b0baf80a6fce070023e19d68048b90 | /slothql/utils/case.py | bb1ab8d97d84957c3449f009eb68fe74385f063f | [
"MIT"
] | permissive | IndioInc/slothql | ea4da3727cb974360eeb3b38517ead4328687e81 | 64a574013e249968746044555bd8779ac353b13f | refs/heads/master | 2021-05-08T11:07:34.420797 | 2018-04-14T02:08:55 | 2018-04-14T02:08:55 | 119,881,523 | 2 | 0 | MIT | 2018-04-15T01:31:10 | 2018-02-01T19:16:50 | Python | UTF-8 | Python | false | false | 527 | py | import re
CAMELCASE_SNAKE_REGEX = re.compile(r'([a-z\d])([A-Z])')
def snake_to_camelcase(string: str) -> str:
first_char = next((i for i, c in enumerate(string) if c != '_'), len(string))
prefix, suffix = string[:first_char], string[first_char:]
words = [i or '_' for i in suffix.split('_')] if suffix else []
return prefix + ''.join(word.title() if i else word for i, word in enumerate(words))
def camelcase_to_snake(string: str) -> str:
return re.sub(CAMELCASE_SNAKE_REGEX, r'\1_\2', string).lower()
| [
"karol.gruszczyk@gmail.com"
] | karol.gruszczyk@gmail.com |
6e94648de2944ea3fae80b2f53a1364afd58c094 | 82da0dd86f0d8bbd526578f1a5252955bb2cc63b | /testClient.py | 57082ea4c12edf7776d4b22583c80de163542678 | [] | no_license | guldfisk/HexCG | a200a4790782fc91147da8342300cb618bdcb0c6 | 435511a8e61656baa8f7addb8f64128977033349 | refs/heads/master | 2021-01-12T06:35:58.738660 | 2017-04-27T21:24:15 | 2017-04-27T21:24:15 | 77,392,407 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 956 | py | import drawSurface
import os
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MainView(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MainView, self).__init__(parent)
botsplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
botsplitter.addWidget(drawSurface.DrawSurface())
botsplitter.addWidget(drawSurface.DrawSurface())
topsplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
topsplitter.addWidget(botsplitter)
vbox = QtWidgets.QVBoxLayout(self)
vbox.addWidget(topsplitter)
self.setLayout(vbox)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.mainview = MainView()
self.setCentralWidget(self.mainview)
self.setWindowTitle('Test Hex Client')
self.setGeometry(300, 300, 300, 200)
def test():
app=QtWidgets.QApplication(sys.argv)
w=MainWindow()
w.show()
sys.exit(app.exec_())
if __name__=='__main__': test() | [
"ce.guldfisk@gmail.com"
] | ce.guldfisk@gmail.com |
82c30f1ac576e4d5f43336166d9b2aa053797c7c | 6be845bf70a8efaf390da28c811c52b35bf9e475 | /windows/Resources/Dsz/PyScripts/Lib/dsz/mca_dsz/file/cmd/get/type_Result.py | e6ebf7d8de0e5bc766dae92b2644b9a4e230863d | [] | no_license | kyeremalprime/ms | 228194910bf2ed314d0492bc423cc687144bb459 | 47eea098ec735b2173ff0d4e5c493cb8f04e705d | refs/heads/master | 2020-12-30T15:54:17.843982 | 2017-05-14T07:32:01 | 2017-05-14T07:32:01 | 91,180,709 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 6,656 | py | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: type_Result.py
from types import *
import mcl.object.MclTime
import array
RESULT_FLAG_IGNORED_DUE_TO_FILESIZE = 1
class ResultFileInfo:
def __init__(self):
self.__dict__['index'] = 0
self.__dict__['fileSize'] = 0
self.__dict__['createTime'] = mcl.object.MclTime.MclTime()
self.__dict__['accessTime'] = mcl.object.MclTime.MclTime()
self.__dict__['modifyTime'] = mcl.object.MclTime.MclTime()
self.__dict__['openStatus'] = 0
self.__dict__['offset'] = 0
self.__dict__['name'] = ''
self.__dict__['flags'] = 0
def __getattr__(self, name):
if name == 'index':
return self.__dict__['index']
if name == 'fileSize':
return self.__dict__['fileSize']
if name == 'createTime':
return self.__dict__['createTime']
if name == 'accessTime':
return self.__dict__['accessTime']
if name == 'modifyTime':
return self.__dict__['modifyTime']
if name == 'openStatus':
return self.__dict__['openStatus']
if name == 'offset':
return self.__dict__['offset']
if name == 'name':
return self.__dict__['name']
if name == 'flags':
return self.__dict__['flags']
raise AttributeError("Attribute '%s' not found" % name)
def __setattr__(self, name, value):
if name == 'index':
self.__dict__['index'] = value
elif name == 'fileSize':
self.__dict__['fileSize'] = value
elif name == 'createTime':
self.__dict__['createTime'] = value
elif name == 'accessTime':
self.__dict__['accessTime'] = value
elif name == 'modifyTime':
self.__dict__['modifyTime'] = value
elif name == 'openStatus':
self.__dict__['openStatus'] = value
elif name == 'offset':
self.__dict__['offset'] = value
elif name == 'name':
self.__dict__['name'] = value
elif name == 'flags':
self.__dict__['flags'] = value
else:
raise AttributeError("Attribute '%s' not found" % name)
def Marshal(self, mmsg):
from mcl.object.Message import MarshalMessage
submsg = MarshalMessage()
submsg.AddU32(MSG_KEY_RESULT_FILE_INFO_INDEX, self.__dict__['index'])
submsg.AddU64(MSG_KEY_RESULT_FILE_INFO_FILE_SIZE, self.__dict__['fileSize'])
submsg.AddTime(MSG_KEY_RESULT_FILE_INFO_CREATE_TIME, self.__dict__['createTime'])
submsg.AddTime(MSG_KEY_RESULT_FILE_INFO_ACCESS_TIME, self.__dict__['accessTime'])
submsg.AddTime(MSG_KEY_RESULT_FILE_INFO_MODIFY_TIME, self.__dict__['modifyTime'])
submsg.AddU32(MSG_KEY_RESULT_FILE_INFO_OPEN_STATUS, self.__dict__['openStatus'])
submsg.AddS64(MSG_KEY_RESULT_FILE_INFO_OFFSET, self.__dict__['offset'])
submsg.AddStringUtf8(MSG_KEY_RESULT_FILE_INFO_NAME, self.__dict__['name'])
submsg.AddU16(MSG_KEY_RESULT_FILE_INFO_FLAGS, self.__dict__['flags'])
mmsg.AddMessage(MSG_KEY_RESULT_FILE_INFO, submsg)
def Demarshal(self, dmsg, instance=-1):
import mcl.object.Message
msgData = dmsg.FindData(MSG_KEY_RESULT_FILE_INFO, mcl.object.Message.MSG_TYPE_MSG, instance)
submsg = mcl.object.Message.DemarshalMessage(msgData)
self.__dict__['index'] = submsg.FindU32(MSG_KEY_RESULT_FILE_INFO_INDEX)
self.__dict__['fileSize'] = submsg.FindU64(MSG_KEY_RESULT_FILE_INFO_FILE_SIZE)
self.__dict__['createTime'] = submsg.FindTime(MSG_KEY_RESULT_FILE_INFO_CREATE_TIME)
self.__dict__['accessTime'] = submsg.FindTime(MSG_KEY_RESULT_FILE_INFO_ACCESS_TIME)
self.__dict__['modifyTime'] = submsg.FindTime(MSG_KEY_RESULT_FILE_INFO_MODIFY_TIME)
self.__dict__['openStatus'] = submsg.FindU32(MSG_KEY_RESULT_FILE_INFO_OPEN_STATUS)
self.__dict__['offset'] = submsg.FindS64(MSG_KEY_RESULT_FILE_INFO_OFFSET)
self.__dict__['name'] = submsg.FindString(MSG_KEY_RESULT_FILE_INFO_NAME)
self.__dict__['flags'] = submsg.FindU16(MSG_KEY_RESULT_FILE_INFO_FLAGS)
class ResultData:
def __init__(self):
self.__dict__['index'] = 0
self.__dict__['buffer'] = array.array('B')
def __getattr__(self, name):
if name == 'index':
return self.__dict__['index']
if name == 'buffer':
return self.__dict__['buffer']
raise AttributeError("Attribute '%s' not found" % name)
def __setattr__(self, name, value):
if name == 'index':
self.__dict__['index'] = value
elif name == 'buffer':
self.__dict__['buffer'] = value
else:
raise AttributeError("Attribute '%s' not found" % name)
def Marshal(self, mmsg):
from mcl.object.Message import MarshalMessage
submsg = MarshalMessage()
submsg.AddU32(MSG_KEY_RESULT_DATA_INDEX, self.__dict__['index'])
submsg.AddData(MSG_KEY_RESULT_DATA_BUFFER, self.__dict__['buffer'])
mmsg.AddMessage(MSG_KEY_RESULT_DATA, submsg)
def Demarshal(self, dmsg, instance=-1):
import mcl.object.Message
msgData = dmsg.FindData(MSG_KEY_RESULT_DATA, mcl.object.Message.MSG_TYPE_MSG, instance)
submsg = mcl.object.Message.DemarshalMessage(msgData)
self.__dict__['index'] = submsg.FindU32(MSG_KEY_RESULT_DATA_INDEX)
self.__dict__['buffer'] = submsg.FindData(MSG_KEY_RESULT_DATA_BUFFER)
class ResultDone:
def __init__(self):
self.__dict__['index'] = 0
def __getattr__(self, name):
if name == 'index':
return self.__dict__['index']
raise AttributeError("Attribute '%s' not found" % name)
def __setattr__(self, name, value):
if name == 'index':
self.__dict__['index'] = value
else:
raise AttributeError("Attribute '%s' not found" % name)
def Marshal(self, mmsg):
from mcl.object.Message import MarshalMessage
submsg = MarshalMessage()
submsg.AddU32(MSG_KEY_RESULT_DONE_INDEX, self.__dict__['index'])
mmsg.AddMessage(MSG_KEY_RESULT_DONE, submsg)
def Demarshal(self, dmsg, instance=-1):
import mcl.object.Message
msgData = dmsg.FindData(MSG_KEY_RESULT_DONE, mcl.object.Message.MSG_TYPE_MSG, instance)
submsg = mcl.object.Message.DemarshalMessage(msgData)
self.__dict__['index'] = submsg.FindU32(MSG_KEY_RESULT_DONE_INDEX) | [
"kyeremalprime@gmail.com"
] | kyeremalprime@gmail.com |
8ba65c3c7211433bf61d3a399af108469c4e73d0 | ee974d693ca4c4156121f8cb385328b52eaac07c | /env/lib/python3.6/site-packages/setuptools/sandbox.py | 2ed7a0bf7fe00623e3280c9c013f6ef5a25e57e6 | [] | no_license | ngonhi/Attendance_Check_System_with_Face_Recognition | f4531cc4dee565d0e45c02217f73f3eda412b414 | 92ff88cbc0c740ad48e149033efd38137c9be88d | refs/heads/main | 2023-03-12T07:03:25.302649 | 2021-02-26T15:37:33 | 2021-02-26T15:37:33 | 341,493,686 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 130 | py | version https://git-lfs.github.com/spec/v1
oid sha256:48ec4eb0b34103d21dc9a1544c6daed3406c040dc389ef8a07380ec677ad2ecf
size 14767
| [
"Nqk180998!"
] | Nqk180998! |
1f0274c73fe51e1f7184f82248d76deb389cbc77 | 08d99e1d2d8dc2adbfea957855279c6ed62f9a5b | /Udemy-kurs-zaawansowany/sekcja_4/4.58_returing_function_L.py | e9e085670c87d5208d149c3c816435631b39d2c0 | [] | no_license | rucpata/udemy-python-zaawansowany | 23f6202edea8879f5a0ca24800908e11af59486e | 597de3ceca723b799e1b31d13552bbb2c9d57a74 | refs/heads/master | 2022-03-15T20:48:36.076232 | 2019-12-09T14:19:09 | 2019-12-09T14:19:09 | 218,304,905 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,167 | py | from datetime import datetime
def time_span_m(start, end):
duration = end - start
duration_in_s = duration.total_seconds()
return divmod(duration_in_s, 60)[0]
def time_span_h(start, end):
duration = end - start
duration_in_s = duration.total_seconds()
return divmod(duration_in_s, 3600)[0]
def time_span_d(start, end):
duration = end - start
duration_in_s = duration.total_seconds()
return divmod(duration_in_s, 86400)[0]
start = datetime(2019, 1, 1, 0, 0, 0)
end = datetime.now()
print(time_span_m(start, end))
print(time_span_h(start, end))
print(time_span_d(start, end))
print('-'*60)
def create_function(span):
if span == 'm':
sec = 60
elif span == 'h':
sec = 3600
elif span == 'd':
sec = 86400
source = '''
def f(start, end):
duration = end - start
duration_in_s = duration.total_seconds()
return divmod(duration_in_s, {})[0]
'''.format(sec)
exec(source, globals())
return f
f_minutes = create_function('m')
f_hours = create_function('h')
f_days = create_function('d')
print(f_minutes(start, end))
print(f_hours(start, end))
print(f_days(start, end)) | [
"rucinska.patrycja@gmail.com"
] | rucinska.patrycja@gmail.com |
54befdb3e0a8b30d69a2aeeaa1a1cc346bb4cf05 | 18ca2e0f98b98941ff9d9e098e0be89166c8b87c | /Abp/Cp9/c9_4_2_backupToZip.py | 9fec4c043c7091fcbfe196e42c9554230ca52d3c | [] | no_license | masa-k0101/Self-Study_python | f20526a9cd9914c9906059678554285bfda0c932 | 72b364ad4da8485a201ebdaaa430fd2e95681b0a | refs/heads/master | 2023-03-07T07:38:27.559606 | 2021-02-22T16:24:47 | 2021-02-22T16:24:47 | 263,381,292 | 1 | 0 | null | 2020-06-09T17:32:06 | 2020-05-12T15:47:48 | Python | UTF-8 | Python | false | false | 908 | py | # -*- coding: utf-8 -*-
#! python3
# backupToZip.py - フォルダ全体を連番付きZIPファイルにコピーする
import zipfile, os
def backup_to_zip(folder):
# フォルダ全体をZIPファイルにバックアップする
folder = os.path.abspath(folder)
# 既存のファイル名からファイル名の連番を決める
number = 1
while True:
zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zip_filename):
break
number = number + 1
# ZIPファイルを作成する
print('Creating {}...'.format(zip_filename))
backup_zip = zipfile.ZipFile(zip_filename, 'w')
# TODO: フォルダのツリーを渡り歩いてその中のファイルを圧縮する
print('Done')
backup_to_zip('c:\\Study\\python\\Automate the Boring Stuff with Python') | [
"noreply@github.com"
] | masa-k0101.noreply@github.com |
29dee4c6ed46e6c4f30e6d3f5b852347f06edfa7 | 668e32dea18d0a7dd3884801d773009b207b35d9 | /api/migrations/0002_profile_phone.py | c7d193c54362c88c647621c0abd58f150cf0223d | [] | no_license | aviox-git/driss-backend | 7a1b0759e899354b4dcbcb9e5dd20120667b0c5f | 8825722c7c3c26896ebb2827075445f364bd2764 | refs/heads/master | 2020-06-13T12:35:10.939614 | 2019-10-05T14:33:52 | 2019-10-05T14:33:52 | 194,655,723 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | # Generated by Django 2.2.1 on 2019-06-13 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='phone',
field=models.BigIntegerField(null=True, verbose_name='Phone Number'),
),
]
| [
"user@example.com"
] | user@example.com |
14fec06ce8e0cefe82323f6b61ffa8b906026b8c | 537b58ea8a1d1fcd961862876662da31efe4880f | /django/blog/migrations/0001_initial.py | ee37d7ab85daeacc6a7fc1012305eb781ec4eb54 | [] | no_license | petershan1119/Djangogirls-Tutorial | d82e4ecdb6322f9c03dbe4d365087e692c265443 | 2f9bc6a6d0599859cf22d0f315553a5932814b39 | refs/heads/master | 2021-05-09T06:16:47.077800 | 2018-02-25T05:30:25 | 2018-02-25T05:30:25 | 119,325,945 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 995 | py | # Generated by Django 2.0.1 on 2018-01-29 07:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('content', models.TextField(blank=True)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('published_date', models.DateField(blank=True, null=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"peter.s.han.1119@gmail.com"
] | peter.s.han.1119@gmail.com |
c4ac81f2ad3729430ee488e572e843dd780a98fc | f04fb8bb48e38f14a25f1efec4d30be20d62388c | /牛客Top200/89验证IP地址.py | 8194a075a514d37ea432617022318981185de087 | [] | no_license | SimmonsChen/LeetCode | d8ef5a8e29f770da1e97d295d7123780dd37e914 | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | refs/heads/master | 2023-09-03T01:16:52.828520 | 2021-11-19T06:37:19 | 2021-11-19T06:37:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,327 | py | #
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
def isIpv4(self, chs):
ans = 0
for ch in chs:
if not ch.isdigit(): return False
ans = ans * 10 + int(ch)
if ans > 255:
return False
else:
return True
def isIpv6(self, chs):
for ch in chs:
if ch.islower():
if ch > "f": return False
elif ch.isupper():
if ch > "F": return False
return True
def solve(self, IP):
# write code here
if not IP:
return "Neither"
if "." in IP:
arr = IP.split(".")
if len(arr) != 4: return "Neither"
for item in arr:
if item == "" or (len(item) > 1 and item[0] == "0") or len(item) > 3 or not self.isIpv4(item): return "Neither"
return "IPv4"
else:
arr = IP.split(":")
if len(arr) != 8: return "Neither"
for item in arr:
if item == "" or len(item) > 4 or not self.isIpv6(item): return "Neither"
return "IPv6"
if __name__ == '__main__':
s = Solution()
print(s.solve("192.0.0.1"))
# print(s.solve("2001:0db8:85a3:0000:0:8A2E:0370:733a"))
| [
"15097686925@163.com"
] | 15097686925@163.com |
d8f81028d7f2a386824631eaa7c1a4f7c435a895 | 510b4d4db394191f1e5a6058555c29903c24d8c8 | /geomat/stein/fields.py | 36429148fa889e8ab0f43283d62e9e37732fff29 | [
"BSD-3-Clause"
] | permissive | GeoMatDigital/django-geomat | 8635735776b924d3ce4d8b2c64b2835d2a6b20d0 | 8c5bc4c9ba9759b58b52ddf339ccaec40ec5f6ea | refs/heads/develop | 2021-09-10T07:19:04.212942 | 2019-10-31T15:56:12 | 2019-10-31T15:56:12 | 45,467,102 | 3 | 0 | BSD-3-Clause | 2021-09-07T23:33:48 | 2015-11-03T13:09:05 | Python | UTF-8 | Python | false | false | 955 | py | from django import forms
from django.contrib.postgres.fields import ArrayField
class ChoiceArrayField(ArrayField):
"""
A field that allows us to store an array of choices.
Uses Django 1.9's postgres ArrayField
and a MultipleChoiceField for its formfield.
Usage:
choices = ChoiceArrayField(models.CharField(max_length=...,
choices=(...,)),
default=[...])
"""
# Voodoo-voodoo from https://gist.github.com/danni/f55c4ce19598b2b345ef
def formfield(self, **kwargs):
defaults = {
'form_class': forms.MultipleChoiceField,
'choices': self.base_field.choices,
}
defaults.update(kwargs)
# Skip our parent's formfield implementation completely as we don't
# care for it.
# pylint:disable=bad-super-call
return super(ArrayField, self).formfield(**defaults)
| [
"gecht.m@gmail.com"
] | gecht.m@gmail.com |
54c3c7e8fe81cb1aab1bd644c8e54b0d2a2a2f5a | d2c4934325f5ddd567963e7bd2bdc0673f92bc40 | /tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_PolyTrend_Seasonal_Second_LSTM.py | 97fe0297c57bed7d7cbbb7625f8f3d5fea08b058 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jmabry/pyaf | 797acdd585842474ff4ae1d9db5606877252d9b8 | afbc15a851a2445a7824bf255af612dc429265af | refs/heads/master | 2020-03-20T02:14:12.597970 | 2018-12-17T22:08:11 | 2018-12-17T22:08:11 | 137,104,552 | 0 | 0 | BSD-3-Clause | 2018-12-17T22:08:12 | 2018-06-12T17:15:43 | Python | UTF-8 | Python | false | false | 163 | py | import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Anscombe'] , ['PolyTrend'] , ['Seasonal_Second'] , ['LSTM'] ); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
8f8b7378f3e164e8ce802728ec439babb5859ec9 | 45b9beebad2f297486c9c12da537a0e28cbcd597 | /users/config.py | c7d8704328ab790aebaaafcefe3ccfb2dccb3bf3 | [] | no_license | thinkingserious/flask-microservices-users | 27a00c3a0e5194a2ab8b7c244365cf343e8b6d57 | 943d0717db72600be590df3df9b8d21e8cf5c4a3 | refs/heads/master | 2021-09-08T08:49:48.978016 | 2018-03-08T22:30:19 | 2018-03-08T22:30:19 | 115,350,010 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 645 | py | import os
class BaseConfig:
"""Base configuration"""
DEBUG = False
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'my_precious'
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
class TestingConfig(BaseConfig):
"""Testing configuration"""
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_TEST_URL')
class ProductionConfig(BaseConfig):
"""Production configuration"""
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
| [
"elmer@thinkingserious.com"
] | elmer@thinkingserious.com |
88c23711f8433fde27a7f539630b6a9d0120f461 | a4753147801dbabfec45f6f9f47572cda77efb81 | /debugging-constructs/ibmfl/evidencia/evidence_recorder.py | fa7058b58049d01df8a7237e81121f847aabfab1 | [
"MIT"
] | permissive | SEED-VT/FedDebug | e1ec1f798dab603bd208b286c4c094614bb8c71d | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | refs/heads/main | 2023-05-23T09:40:51.881998 | 2023-02-13T21:52:25 | 2023-02-13T21:52:25 | 584,879,212 | 8 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,115 | py | """
Licensed Materials - Property of IBM
Restricted Materials of IBM
20221069
© Copyright IBM Corp. 2022 All Rights Reserved.
"""
"""
Abstract base class for providing evidence for accountability.
"""
from abc import ABC, abstractmethod
class AbstractEvidenceRecorder(ABC):
"""
Class that supports providing evidence of FL actions.
Concrete implementations should act in a black-box fashion
with only the methods below exposed to the caller
"""
def __init__(self, info):
"""
Initializes an `AbstractEvidenceRecorder` object with info.
:param info: info required for this recorder.
:type info: `dict`
"""
self.info = info
@abstractmethod
def add_claim(self, predicate: str, custom_string: str):
"""
Adds a new claim as evidence.
Throws: An exception on failure
:custom_string: a caller provided string, non-empty
"""
"""
We may need to:
1) enhance the above method parameters etc
2) provide for a module "registration" mechanism
3) consider logging-like usage
"""
| [
"waris@vt.edu"
] | waris@vt.edu |
94ba0c13938603187c3de37f00105a9894637186 | a359c7be79fd15809b659ae745352757b052e5fa | /web/pgadmin/feature_tests/table_ddl_feature_test.py | 9fb90d662ca4225e39d306f7b864db3be67ce747 | [
"PostgreSQL"
] | permissive | harshal-dhumal/pgadmin4 | 579cfd91a1659d1e27445accb542511e73c88e4f | 1977a5fcda44b78b00d6eaac2e6a99df355d5105 | refs/heads/master | 2020-12-02T22:16:34.682407 | 2017-07-03T10:19:02 | 2017-07-03T10:19:02 | 96,105,663 | 1 | 0 | null | 2017-07-03T11:54:02 | 2017-07-03T11:54:02 | null | UTF-8 | Python | false | false | 2,316 | py | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2017, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
from regression.feature_utils.base_feature_test import BaseFeatureTest
from regression.python_test_utils import test_utils
class TableDdlFeatureTest(BaseFeatureTest):
""" This class test acceptance test scenarios """
scenarios = [
("Test table DDL generation", dict())
]
def before(self):
connection = test_utils.get_db_connection(self.server['db'],
self.server['username'],
self.server['db_password'],
self.server['host'],
self.server['port'])
test_utils.drop_database(connection, "acceptance_test_db")
test_utils.create_database(self.server, "acceptance_test_db")
self.page.add_server(self.server)
def runTest(self):
test_utils.create_table(self.server, "acceptance_test_db", "test_table")
self.page.toggle_open_server(self.server['name'])
self.page.toggle_open_tree_item('Databases')
self.page.toggle_open_tree_item('acceptance_test_db')
self.page.toggle_open_tree_item('Schemas')
self.page.toggle_open_tree_item('public')
self.page.toggle_open_tree_item('Tables')
self.page.select_tree_item('test_table')
self.page.click_tab("SQL")
self.page.find_by_xpath(
"//*[contains(@class,'CodeMirror-lines') and contains(.,'CREATE TABLE public.test_table')]")
def after(self):
self.page.remove_server(self.server)
connection = test_utils.get_db_connection(self.server['db'],
self.server['username'],
self.server['db_password'],
self.server['host'],
self.server['port'])
test_utils.drop_database(connection, "acceptance_test_db")
| [
"dpage@pgadmin.org"
] | dpage@pgadmin.org |
f197366b23568d36afd7a0adc83041610a363335 | 85eaa822b3a565163820a2c8f997c508c43b1d13 | /Table/iris_table.py | ef34c72bb85f390990dfc039b6df43c383cf2c3b | [] | no_license | woorud/GuiTest | 5e59db21eeb640db734b114ff351f25bc12fcdce | 50b35818b09220b73092a01e86dd9cee174fc3ae | refs/heads/master | 2023-01-01T05:44:10.969120 | 2020-10-06T16:09:49 | 2020-10-06T16:09:49 | 293,092,869 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,197 | py | import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QTableWidgetItem
from PyQt5.uic import loadUiType
import pymysql
import pandas as pd
form_class = loadUiType("iris_table.ui")[0]
class ViewerClass(QMainWindow, form_class):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
dbConn = pymysql.connect(user='######', passwd='######~', host='######', db='iris', charset='utf8')
cursor = dbConn.cursor(pymysql.cursors.DictCursor)
sql = "select a.SL, a.SW, a.PL, a.PW, b.Species_name from dataset a " \
"left join flower b on a.species = b.species;"
cursor.execute(sql)
result = cursor.fetchall()
result = pd.DataFrame(result)
self.tableWidget.setColumnCount(len(result.columns))
self.tableWidget.setRowCount(len(result))
self.tableWidget.setHorizontalHeaderLabels(result.columns)
for i in range(len(result)):
for j in range(len(result.columns)):
self.tableWidget.setItem(i, j, QTableWidgetItem(str(result.iloc[i, j])))
app = QApplication(sys.argv)
myWindow = ViewerClass(None)
myWindow.show()
app.exec() | [
"woorud96@gmail.com"
] | woorud96@gmail.com |
92d3bb59489918ddcbcf0506d9c0336019d219e1 | bc91d344ed2ee3f4f93547ec16350f2713e5f704 | /.history/CRUD/views_20190108014602.py | 5ca799bd23b34134d8e78785ed5186cce9299464 | [] | no_license | SabitDeepto/Chitra | 10ecf0c4a7588234f0a50adf038783c9ce8706d0 | 160e5d64c8e4ee56a95bb639386785590160ff07 | refs/heads/master | 2020-04-27T21:55:09.685341 | 2019-03-09T16:14:35 | 2019-03-09T16:14:35 | 174,716,372 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 253 | py | from django.shortcuts import render
from urllib3 import request
# Create your views here.
def home(request):
executive = Exe
templates = 'index.html'
context = {
'name': 'deepto'
}
return render(request, templates, context) | [
"deepto69@gmail.com"
] | deepto69@gmail.com |
a798a0e843c705439966420e50750750658888f2 | c7e028d71b5dd72eb18b72c6733e7e98a969ade6 | /src/algoritmia/problems/traversals/treetraversals.py | 418311d170e2b266f36eec01d2d8af08272ec59a | [
"MIT"
] | permissive | antoniosarosi/algoritmia | da075a7ac29cc09cbb31e46b82ae0b0ea8ee992f | 22b7d61e34f54a3dee03bf9e3de7bb4dd7daa31b | refs/heads/master | 2023-01-24T06:09:37.616107 | 2020-11-19T16:34:09 | 2020-11-19T16:34:09 | 314,302,653 | 8 | 1 | null | null | null | null | WINDOWS-1258 | Python | false | false | 3,233 | py | #coding: latin1
from algoritmia.datastructures.queues import Fifo #[]level
from algoritmia.datastructures.queues import Lifo #[]prepro
from collections import namedtuple
from abc import ABCMeta, abstractmethod
class ITreeTraverser(metaclass=ABCMeta): #[interface
@abstractmethod
def traverse(self, tree: "IRootedTree<T>", #?tree?¶tree?
visitor: "IRootedTree<T> -> S") -> "Iterable<S>": pass #?vis?»vis? #]interface
class LevelOrderTreeTraverser(ITreeTraverser): #[level
def __init__(self, createFifo=lambda: Fifo()):
self.createFifo = createFifo
def traverse(self, tree: "IRootedTree<T>", #?tree?¶tree?
visitor: "IRootedTree<T> -> S"=None) -> "Iterable<S>":#?vis?»vis?
visitor = visitor or (lambda subtree: subtree.root)
Q = self.createFifo()
Q.push(tree)
yield visitor(tree)
while len(Q) > 0:
t = Q.pop()
for child in t.subtrees():
Q.push(child)
yield visitor(child) #]level
class PreorderTreeTraverser(ITreeTraverser):#[pre
def __init__(self, createLifo=lambda: Lifo()):
self.createLifo = createLifo
def traverse(self, tree: "IRootedTree<T>", #?tree?¶tree?
visitor: "IRootedTree<T> -> S"=None) -> "Iterable<S>":#?vis?»vis?
visitor = visitor or (lambda subtree: subtree.root)
Q = self.createLifo()
Q.push(tree)
while len(Q) > 0:
t = Q.pop()
yield visitor(t)
for st in reversed(tuple(t.subtrees())):
Q.push(st) #]pre
class PostorderTreeTraverser(ITreeTraverser): #[post
def __init__(self, createLifo=lambda: Lifo()):
self.createLifo = createLifo
def traverse(self, tree: "IRootedTree<T>", #?tree?¶tree?
visitor: "IRootedTree<T> -> S"=None) -> "Iterable<S>":#?vis?»vis?
visitor = visitor or (lambda subtree: subtree.root)
Q = self.createLifo()
Q.push(tree)
while len(Q) > 0:
t = Q.pop()
if isinstance(t, _ReadyToVisitTree):
yield visitor(t.tree)
else:
Q.push(_ReadyToVisitTree(t))
for st in reversed(tuple(t.subtrees())):
Q.push(st)
_ReadyToVisitTree = namedtuple("_ReadyToVisitTree", "tree") #]post
class InorderTreeTraverser(object): #[in
def __init__(self, createLifo=lambda: Lifo()):
self.createLifo = createLifo
def traverse(self, tree: "IRootedTree<t>", #?tree?¶tree?
visitor: "IRootedTree<T> -> S"=None) -> "Iterable<S>":#?vis?»vis?
visitor = visitor or (lambda subtree: subtree.root)
Q = self.createLifo()
Q.push(tree)
while len(Q) > 0:
t = Q.pop()
if isinstance(t, _ReadyToVisitTree):
yield visitor(t.tree)
else:
st= tuple(t.subtrees())
if len(st) == 2: Q.push(st[1])
Q.push(_ReadyToVisitTree(t))
if len(st) == 2: Q.push(st[0]) #]in
#]in | [
"amarzal@localhost"
] | amarzal@localhost |
7d6c3094add2dc3f6c27c81424781b777d17f603 | 4cb79aeadba003db92f295931012f4b85f0a10fa | /purkinje_model/neuron2morph.py | 29afa103e60a24f35f9080a4d79b8f0cb7727d71 | [] | no_license | ModelDBRepository/225089 | 77f64de167ac148336189c0e1c93cb94f55ec000 | 4d8cfd8d93cf74eda52df7a14b988eed691dc27c | refs/heads/master | 2020-05-29T18:26:35.794854 | 2019-05-31T03:23:31 | 2019-05-31T03:23:31 | 189,299,613 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 652 | py | #########################################################################
# This script is provided for
#
# Chen W and De Schutter E (2017) Parallel STEPS: Large Scale Stochastic Spatial Reaction-Diffusion Simulation with High Performance Computers. Front. Neuroinform. 11:13. doi: 10.3389/fninf.2017.00013
#
##########################################################################
import sys
import steps.utilities.morph_support as morph_support
import cPickle
HOC_FILE = sys.argv[1]
MORPH_FILE = sys.argv[2]
moprhdata = morph_support.hoc2morph(HOC_FILE)
morph_file = open(MORPH_FILE, 'w')
cPickle.dump(moprhdata, morph_file)
morph_file.close()
| [
"tom.morse@yale.edu"
] | tom.morse@yale.edu |
49771ad3463b7f6cc1c7859994b5db00ce8fe7aa | 48d232cc6dcf57abf6fca9cbbef8943e189acb04 | /longest-peak-ae.py | 81f9a6e95a133066bda1afc53954f3e21569d6c1 | [] | no_license | csusb-005411285/CodeBreakersCode | dae796ba4262770e0a568e9c27597a041db0775c | 8f218164e1b9e42c1a928d22ef5a76328abb66a2 | refs/heads/master | 2022-01-12T09:11:33.668338 | 2021-12-27T04:45:13 | 2021-12-27T04:45:13 | 232,490,141 | 1 | 1 | null | 2021-01-29T23:09:14 | 2020-01-08T06:02:11 | Python | UTF-8 | Python | false | false | 2,198 | py | # tc: o(n2), sc: o(n)
def longestPeak(array):
if len(array) < 3:
return 0
peaks = get_peaks(array)
path_to_from_peak = get_path_from_peak(array, peaks)
if not path_to_from_peak:
return 0
max_len = float('-inf')
for i in path_to_from_peak:
max_len = max(max_len, len(path_to_from_peak[i]))
return max_len
def get_path_from_peak(array, peaks):
path = {}
for i in peaks:
forward = i + 1
backward = i - 1
path[i] = [array[backward], array[i], array[forward]]
while backward >= 0 and array[backward - 1] < array[backward]:
path[i].append(array[backward - 1]) #
backward -= 1
while forward < len(array) - 1 and array[forward + 1] < array[forward]:
path[i].append(array[forward + 1])
forward += 1
return path
# 2nd attempt
# tc: o(n), sc: o(n)
def longestPeak(array):
if len(array) < 3:
return 0
heights = {}
peaks = get_peaks(array)
if len(peaks) == 0:
return 0
heights = populate_default_height(heights, peaks)
heights = get_heights(heights, array)
return max(heights.values())
def get_heights(heights, array):
for index in heights.keys():
backward = index
forward = index
height_for_index = 0
while backward > 0:
if array[backward - 1] < array[backward]:
height_for_index += 1
backward -= 1
else:
break
heights[index] = height_for_index + 1
height_for_index = 0
while forward < len(array) - 1:
if array[forward + 1] < array[forward]:
height_for_index += 1
forward += 1
else:
break
heights[index] += height_for_index
return heights
def populate_default_height(heights, peaks):
for peak in peaks:
heights[peak] = 0
return heights
def get_peaks(array):
peaks = []
for i in range(1, len(array) - 1):
if array[i] > array[i - 1] and array[i] > array[i + 1]:
peaks.append(i)
return peaks
| [
"noreply@github.com"
] | csusb-005411285.noreply@github.com |
fdbe466ecb4fc79c93bb6a16feee06d295ce8d0b | f121695e2dff353607fa47fb42482470e03bbf8a | /capitulo_08-Funcoes/magicos.py | 908835a823b126a47b6d631c241eec625501b463 | [] | no_license | ranog/python_work | 76cbcf784c86fae4482be5383223e4b0a34f4130 | 47c442a90dcf32d5aef70858693a772a3c76a7ac | refs/heads/master | 2022-12-22T11:02:26.482059 | 2021-04-17T01:12:22 | 2021-04-17T01:12:22 | 233,634,221 | 2 | 1 | null | 2022-12-08T07:38:43 | 2020-01-13T15:58:46 | Python | UTF-8 | Python | false | false | 916 | py | #! /usr/bin/env python3
"""
NOME
magicos.py - FAÇA VOCÊ MESMO.
SINOPSES
chmod +x magicos.py
./magicos.py
Mágicos famosos:
- Harry Houdini
- Fu-Manchu
- Richiardi Jr
- Jasper Maskelyne
- Dai Vernon
- David Blaine
- Siegfried Fischbacher
- David Copperfield
DESCRIÇÃO
8.9 – Mágicos: Crie uma lista de nomes de mágicos. Passe a lista
para uma função chamada show_magicians() que exiba o nome de cada
mágico da lista.
HISTÓRICO
20200611: João Paulo, outubro de 2020.
- 8.9 - Mágicos (pg 187).
"""
def show_magicians(magicians):
for magic in magicians:
print("- " + magic)
magicians = ['Harry Houdini', 'Fu-Manchu', 'Richiardi Jr',
'Jasper Maskelyne', 'Dai Vernon', 'David Blaine',
'Siegfried Fischbacher', 'David Copperfield', ]
print("\nMágicos famosos: ")
show_magicians(magicians)
| [
"jprnogueira@yahoo.com.br"
] | jprnogueira@yahoo.com.br |
77fd6bb439e708106d8cb5ef3ab6313444780583 | 2455062787d67535da8be051ac5e361a097cf66f | /Producers/BSUB/TrigProd_amumu_a5_dR5/trigger_amumu_producer_cfg_TrigProd_amumu_a5_dR5_450.py | 540db515812846a4d296cd0d53441e47d7f6a26e | [] | no_license | kmtos/BBA-RecoLevel | 6e153c08d5ef579a42800f6c11995ee55eb54846 | 367adaa745fbdb43e875e5ce837c613d288738ab | refs/heads/master | 2021-01-10T08:33:45.509687 | 2015-12-04T09:20:14 | 2015-12-04T09:20:14 | 43,355,189 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,360 | py | import FWCore.ParameterSet.Config as cms
process = cms.Process("PAT")
#process.load("BBA/Analyzer/bbaanalyzer_cfi")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load('Configuration.EventContent.EventContent_cff')
process.load("Configuration.Geometry.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")
process.load("PhysicsTools.PatAlgos.selectionLayer1.selectedPatCandidates_cff")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'MCRUN2_71_V1::All', '')
process.load("Configuration.StandardSequences.MagneticField_cff")
####################
# Message Logger
####################
process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100)
process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
## switch to uncheduled mode
process.options.allowUnscheduled = cms.untracked.bool(True)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(500)
)
####################
# Input File List
####################
# Input source
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('root://eoscms//eos/cms/store/user/ktos/RECO_Step3_amumu_a5/RECO_Step3_amumu_a5_450.root'),
secondaryFileNames = cms.untracked.vstring()
)
############################################################
# Defining matching in DeltaR, sorting by best DeltaR
############################################################
process.mOniaTrigMatch = cms.EDProducer("PATTriggerMatcherDRLessByR",
src = cms.InputTag( 'slimmedMuons' ),
matched = cms.InputTag( 'patTrigger' ), # selections of trigger objects
matchedCuts = cms.string( 'type( "TriggerMuon" ) && path( "HLT_Mu16_TkMu0_dEta18_Onia*")' ), # input does not yet have the 'saveTags' parameter in HLT
maxDPtRel = cms.double( 0.5 ), # no effect here
maxDeltaR = cms.double( 0.3 ), #### selection of matches
maxDeltaEta = cms.double( 0.2 ), # no effect here
resolveAmbiguities = cms.bool( True ),# definition of matcher output
resolveByMatchQuality = cms.bool( True )# definition of matcher output
)
# talk to output module
process.out = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string("file:RECO_Step3_amumu_a5_TrigProd_450.root"),
outputCommands = process.MINIAODSIMEventContent.outputCommands
)
process.out.outputCommands += [ 'drop *_*_*_*',
'keep *_*slimmed*_*_*',
'keep *_pfTausEI_*_*',
'keep *_hpsPFTauProducer_*_*',
'keep *_hltTriggerSummaryAOD_*_*',
'keep *_TriggerResults_*_HLT',
'keep *_patTrigger*_*_*',
'keep *_prunedGenParticles_*_*',
'keep *_mOniaTrigMatch_*_*'
]
################################################################################
# Running the matching and setting the the trigger on
################################################################################
from PhysicsTools.PatAlgos.tools.trigTools import *
switchOnTrigger( process ) # This is optional and can be omitted.
switchOnTriggerMatching( process, triggerMatchers = [ 'mOniaTrigMatch'
])
process.outpath = cms.EndPath(process.out)
| [
"kmtos@ucdavis.edu"
] | kmtos@ucdavis.edu |
5e45d92c570a19aed882561fb8ce582ded4238ea | aeac131d9da991853a7eb0a68bc7be4f848b9ed6 | /API_DB/adjacent.py | 0c0f176ff137a3bd764efc066cb40a5b8bbd3aaa | [] | no_license | xuqil/-Crawler | d5b10c137beedb9daa8a33facf8ed80f62e8e53f | c9703d8ee2a7ea66ae50d20e53247932987122e6 | refs/heads/master | 2020-04-04T11:25:34.729191 | 2018-12-15T11:49:16 | 2018-12-15T11:49:16 | 155,890,694 | 0 | 0 | null | 2018-12-06T11:43:28 | 2018-11-02T16:09:30 | HTML | UTF-8 | Python | false | false | 1,708 | py | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Integer, Unicode
from sqlalchemy.orm import relationship, sessionmaker, joinedload, joinedload_all
Base = declarative_base()
Engine = create_engine('mysql+mysqlconnector://root:19218@127.0.0.1:3306/test2', encoding='utf8')
DBSession = sessionmaker(bind=Engine)
session = DBSession()
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(32), nullable=False, server_default='')
parent = Column(Integer, ForeignKey('node.id'), index=True, server_default=None)
children = relationship('Node', lazy='joined', cascade='all, delete-orphan')
parent_obj = relationship('Node', remote_side=[id])
def init_db():
Base.metadata.create_all(Engine)
# init_db()
# # n = session.query(Node).filter(Node.name == u'小猪').first()
# n = session.query(Node).filter(Node.name == u'小猪').options(joinedload('parent_obj')).first()
# print(n.id)
# n = session.query(Node).filter(Node.name == u'大直沽').options(joinedload('children').joinedload('children')).first()
# print(n.name)
# print(n.children[0].name)
# print(n.children[0].children[0].name)
# n = session.query(Node).filter(Node.name == u'大直沽').options(joinedload_all('children', 'children')).first()
# print(n.name)
# print(n.children[0].name)
# print(n.children[0].children[0].name)
# n = session.query(Node).filter(Node.name == u'小猪').first()
# session.delete(n)
# session.commit()
n = session.query(Node).filter(Node.name == u'等等').first()
n.children = []
session.commit()
| [
"13829842679@163.com"
] | 13829842679@163.com |
d10a5e2e66da614421ca8064583cae2b09a27942 | 09aea7ebe2ce7214ac9f18741e85e49a3d8bcd5e | /testes.py | f37cee7c457681542087f83cf56ef77f62f49f01 | [] | no_license | bmsrangel/Projeto_Biblioteca | 3555bf10058d450ad3d3b61bb20bd7427fe65a4d | 4789c8070d194dd1ab8e1c2c0e7cc3102086d058 | refs/heads/master | 2020-04-27T15:12:24.472246 | 2019-03-07T23:51:35 | 2019-03-07T23:51:35 | 174,436,851 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,407 | py | import unittest
from livro import Livro
from pessoa import Pessoa
from emprestimo import Emprestimo
from database import Database
class TestDatabase(unittest.TestCase):
def setUp(self):
self.db = Database()
self.db.conectar()
self.db.criar_tabelas()
self.db.desconectar()
def test_00_inclusao_pessoa(self):
self.db.conectar()
# self.db.inserir_pessoa('Bruno Rangel', '1234', '17/02/1990')
# self.db.inserir_pessoa('Edilania Silva', '5678', '25/10/1991')
self.assertEqual((2, 'Edilania Silva', '5678', '25/10/1991', 0.0), self.db.buscar_pessoa('5678'))
self.db.desconectar()
def test_01_alterar_multa(self):
self.db.conectar()
self.db.definir_multa('1234', 3.0)
self.assertEqual((1, 'Bruno Rangel', '1234', '17/02/1990', 3.0), self.db.buscar_pessoa('1234'))
self.db.desconectar()
def test_02_inclusao_livro(self):
self.db.conectar()
# self.db.inserir_livro('origem', 'dan brown', 'doubleday', 2017, 3)
self.assertEqual((1, 'Origem', 'Dan Brown', 'Doubleday', 2017, 4), self.db.buscar_livro('origem'))
self.db.desconectar()
def test_03_alterar_quantidade_livros(self):
self.db.conectar()
self.db.alterar_quantidade('origem', 4)
self.assertEqual((1, 'Origem', 'Dan Brown', 'Doubleday', 2017, 4), self.db.buscar_livro('origem'))
self.db.desconectar()
def test_04_novo_emprestimo(self):
self.db.conectar()
# self.db.novo_emprestimo('1234', 'origem')
self.assertEqual((1, '06/03/2019', 'E', 'Bruno Rangel', 'Origem', 'Dan Brown'), self.db.buscar_emprestimo('1234'))
self.db.desconectar()
def test_05_alterar_situacao_emprestimo(self):
self.db.conectar()
self.db.alterar_situacao_emprestimo(1, 'E')
self.assertEqual((1, '06/03/2019', 'E', 'Bruno Rangel', 'Origem', 'Dan Brown'), self.db.buscar_emprestimo('1234'))
self.db.desconectar()
class TestPessoa(unittest.TestCase):
def setUp(self):
self.pessoa = Pessoa('Lidia Gandra', '1011', '15/04/1991')
def test_00_cadastrarPessoa(self):
# self.pessoa.cadastrar()
# self.assertEqual(self.pessoa, Pessoa.consultar_pessoa('1011'))
self.assertTrue(self.pessoa == Pessoa.consultar_pessoa('1011'))
def test_01_multar(self):
self.pessoa.multar(2.5)
self.assertTrue(self.pessoa == Pessoa.consultar_pessoa('1011'))
def test_02_pagar_multa(self):
self.pessoa.pagar_multa()
self.assertTrue(self.pessoa == Pessoa.consultar_pessoa('1011'))
def test_03_pessoa_inexistente(self):
self.assertFalse(Pessoa.consultar_pessoa('1213'))
class TestLivro(unittest.TestCase):
def setUp(self):
self.livro = Livro('A Cabana', 'William Young', 'Sextante', 2007, 10)
def test_00_cadastrar_livro(self):
# self.livro.cadastrar_livro()
self.livro.quantidade = 8
self.assertTrue(self.livro == Livro.consultar_livro('a cabana'))
def test_01_alterar_quantidade_livro(self):
self.livro.alterar_quantidade(8)
self.assertTrue(self.livro == Livro.consultar_livro('a cabana'))
def test_02_livro_inexistente(self):
self.assertFalse(Livro.consultar_livro('madagascar'))
if __name__ == '__main__':
unittest.main(verbosity=3)
| [
"bmsrangel@hotmail.com"
] | bmsrangel@hotmail.com |
2f26d83ce23d45e2fed8f7f4851fecfb82a00b63 | c7c969259d9600eaa152d6896b8c3278e019f8c1 | /cluster/util.py | 5d2baf066105077e0c19e50a6cd6507549c3fc92 | [] | no_license | jwintersinger/csc2515-project | 4874d1fec5c3825cff7091ac6b9af147be88b9c5 | ccd71032ae0617a2cc125c73b9b0af6e92a902c0 | refs/heads/master | 2016-09-11T12:20:29.766193 | 2015-04-17T03:23:08 | 2015-04-17T03:23:08 | 34,094,429 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 682 | py | import multiprocessing
import numpy as np
def load_mutpairs(fnames, in_parallel=True, limit=None):
if limit:
fnames = fnames[:limit]
if in_parallel:
results = multiprocessing.Pool(8).map(load_single_mutpairs, fnames)
else:
results = map(load_single_mutpairs, fnames)
mutpairs = np.zeros(shape=(len(fnames), results[0].shape[0], 4), dtype=np.bool)
for i, fname in enumerate(fnames):
mutpairs[i,:,:] = results[i]
return mutpairs
def load_single_mutpairs(fname):
t = np.loadtxt(fname)
t = t.astype(np.bool, copy=False)
t = t.T
return t
def extract_score(fname):
fname = fname.rsplit('_', 1)[1]
fname = fname.rsplit('.', 2)[0]
return fname
| [
"jeff.git@wintersinger.com"
] | jeff.git@wintersinger.com |
d46a62a0887148e9646d19c3afb237ce53409f3d | bd8ec52d55798ae62bbea1906847f56b37593911 | /vtol/python/hw11/vtolController_lat.py | b9da0e6822e1f52d3f630250183268a61562076e | [] | no_license | jaringson/Controls_EcEn483 | 2d4e4a65d84afb8f9ddc74925b85349d348a59d5 | 1ca4f24dad65ce92f1ab5310242adf08062e22d1 | refs/heads/master | 2021-08-29T22:14:18.007719 | 2017-12-15T05:06:42 | 2017-12-15T05:06:42 | 103,585,334 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,987 | py | import vtolParamHW11_lat as P
import sys
sys.path.append('..') # add parent directory
import vtolParam as P0
import numpy as np
class vtolController_lat:
'''
This class inherits other controllers in order to organize multiple controllers.
'''
def __init__(self):
# Instantiates the SS_ctrl object
self.z_dot = 0.0 # derivative of z
self.theta_dot = 0.0 # derivative of theta
self.z_d1 = 0.0 # Position z delayed by 1 sample
self.theta_d1 = 0.0 # Angle theta delayed by 1 sample
self.K = P.K # state feedback gain
self.kr = P.kr # Input gain
self.limit = P.tau_max # Maxiumum force
self.beta = P.beta # dirty derivative gain
self.Ts = P.Ts # sample rate of controller
def u(self, y_r, y):
# y_r is the referenced input
# y is the current state
z_r = y_r[0]
z = y[0]
theta = y[2]
# differentiate z and theta
self.differentiateZ(z)
self.differentiateTheta(theta)
# Construct the state
x = np.matrix([[z], [theta], [self.z_dot], [self.theta_dot]])
# Compute the state feedback controller
tau_tilde = -self.K*x + self.kr*z_r
tau_e = 0
tau = tau_e + tau_tilde
tau = self.saturate(tau)
return [tau]
def differentiateZ(self, z):
'''
differentiate z
'''
self.z_dot = self.beta*self.z_dot + (1-self.beta)*((z - self.z_d1) / self.Ts)
self.z_d1 = z
def differentiateTheta(self, theta):
'''
differentiate theta
'''
self.theta_dot = self.beta*self.theta_dot + (1-self.beta)*((theta - self.theta_d1) / self.Ts)
self.theta_d1 = theta
def saturate(self, u):
if abs(u) > self.limit:
u = self.limit*np.sign(u)
return u
| [
"jaringson@gmail.com"
] | jaringson@gmail.com |
79510f66671377a5b36333913b1852dbca847db4 | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/networking_flow/Minimum_cut.py | 33daad3378607ec598d9c9fbdfc725885e05db27 | [
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | Python | false | false | 1,583 | py | # Minimum cut on Ford_Fulkerson algorithm.
def BFS(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
while queue:
u = queue.pop(0)
for ind in range(len(graph[u])):
if visited[ind] == False and graph[u][ind] > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
return True if visited[t] else False
def mincut(graph, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (len(graph))
max_flow = 0
res = []
temp = [i[:] for i in graph] # Record orignial cut, copy.
while BFS(graph, source, sink, parent):
path_flow = float("Inf")
s = sink
while s != source:
# Find the minimum value in select path
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
for i in range(len(graph)):
for j in range(len(graph[0])):
if graph[i][j] == 0 and temp[i][j] > 0:
res.append((i, j))
return res
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
source, sink = 0, 5
print(mincut(graph, source, sink))
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
65f119cbba27c8105c81c41132cf967b03783924 | bdda458001808a029b171c09286f022a1384d180 | /prove/provascript.py | b5d257652e5cc5bda09a9bc81170655522f2767a | [] | no_license | bianchimro/crm-django | 4189f5c0c31f03d23a2b644a14403d63b8efdf0a | d8e4d18174cb050fd7a22d53fe8bb152e6e43120 | refs/heads/master | 2021-04-27T15:15:28.219887 | 2018-02-22T16:51:00 | 2018-02-22T16:51:00 | 122,466,604 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 321 | py | import sys
from libreria import helpers
def provafunzione(a, b=10, c=6):
print(a)
print(b)
provafunzione(10)
provafunzione(10, b=2)
provafunzione(10, b=2, c=10)
provafunzione(10, c=10)
def main(msg):
print(msg)
x = helpers.somma(1, 2)
print(x)
if __name__ == '__main__':
main(sys.argv[1])
| [
"bianchimro@gmail.com"
] | bianchimro@gmail.com |
40d0f3711fc75767e77a31c5fdf441b71a49d137 | 89b7b6375226e5224321e8e467b1047830bd2073 | /easy/palindromeLinkedList.py | ecedabb47a8c88feecda91c0c12e7b75e6f9ff09 | [] | no_license | xiao-bo/leetcode | 9cf5ec1dd86faa699f51b3a616929da4ebdb3053 | 671383b9ee745ed84fbb6d76a91d8be353710096 | refs/heads/master | 2023-03-18T19:10:28.990610 | 2023-03-11T10:11:43 | 2023-03-11T10:11:43 | 154,341,943 | 0 | 0 | null | 2023-03-11T10:11:44 | 2018-10-23T14:24:15 | Python | UTF-8 | Python | false | false | 2,993 | py | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# Definition for singly-linked list.
# O(n) and space is O(n)
# Runtime 350 ms Beats 30.14% Memory 17 MB Beats 13.53%
nums = []
current = head
while current:
nums.append(current.val)
current = current.next
for i in range(0, int(len(nums)/2)):
if nums[i] == nums[len(nums)-1-i]:
continue
else:
return False
return True
## first method
## Runtime: 56 ms, faster than 98.70% of Python online submissions for Palindrome Linked List.
## Memory Usage: 32.3 MB, less than 6.90% of Python online submissions for Palindrome Linked List.
## time complexity is O(n)
## space complexity is O(n)
'''
num = []
while head:
num.append(head.val)
head = head.next
print(num)
flag = True
length = len(num)
for x in range(0,length):
print("nums[{}] = {} nums[{}] = {}".format(x,num[x],length-x-1,num[length-x-1]))
if num[x] == num[length-x-1]:
continue
else:
flag = False
break
return flag
'''
## second method
## Runtime: 76 ms, faster than 34.63% of Python online submissions for Palindrome Linked List.
## Memory Usage: 30.9 MB, less than 34.48% of Python online submissions for Palindrome Linked List.
slow = fast = head
## get midpoint
while fast and fast.next:
fast = fast.next.next
slow = slow.next
print(" slow = {}".format(slow.val))
slow = self.reverse(slow)
self.printAllnode(slow)
while head and slow:
if head.val != slow.val:
return False
else:
head = head.next
slow = slow.next
return True
def reverse(self,head):
prev = None
next = None
while head:
next = head.next
head.next = prev
prev = head
head = next
return prev
def printAllnode(self,head):
while head:
print(head.val)
head = head.next
def main():
a = Solution()
node1 = ListNode(1)
node2 = ListNode(3)
node3 = ListNode(1)
node4 = ListNode(3)
node5 = ListNode(1)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
ans = a.isPalindrome(node1)
#node1 = a.reverse(node1)
print(ans)
#a.printAllnode(node1)
if __name__ == '__main__':
main()
| [
"ay852852@gmail.com"
] | ay852852@gmail.com |
bd9c12207e291abf0c6e8140048b593d0520e4c7 | 9b20743ec6cd28d749a4323dcbadb1a0cffb281b | /07_Machine_Learning_Mastery_with_Python/05/correlation_matrix_generic.py | bef6f583b5a4eab07926d46ad4579350536cf8f3 | [] | no_license | jggrimesdc-zz/MachineLearningExercises | 6e1c7e1f95399e69bba95cdfe17c4f8d8c90d178 | ee265f1c6029c91daff172b3e7c1a96177646bc5 | refs/heads/master | 2023-03-07T19:30:26.691659 | 2021-02-19T08:00:49 | 2021-02-19T08:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 440 | py | # Correlation Matrix Plot (generic)
from matplotlib import pyplot
from pandas import read_csv
filename = 'pima-indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(filename, names=names)
correlations = data.corr()
# plot correlation matrix
fig = pyplot.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlations, vmin=-1, vmax=1)
fig.colorbar(cax)
pyplot.show()
| [
"jgrimes@jgrimes.tech"
] | jgrimes@jgrimes.tech |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.