repo_name
stringlengths 5
92
| path
stringlengths 4
221
| copies
stringclasses 19
values | size
stringlengths 4
6
| content
stringlengths 766
896k
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 32
997
| alpha_frac
float64 0.25
0.96
| autogenerated
bool 1
class | ratio
float64 1.5
13.6
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
andreashorn/lead_dbs | ext_libs/SlicerNetstim/WarpDrive/WarpDriveLib/Effects/Effect.py | 1 | 4254 | import vtk, qt, slicer
class AbstractEffect():
"""
One instance of this will be created per-view when the effect
is selected. It is responsible for implementing feedback and
label map changes in response to user input.
This class observes the editor parameter node to configure itself
and queries the current view for background and label volume
nodes to operate on.
"""
def __init__(self,sliceWidget):
# sliceWidget to operate on and convenience variables
# to access the internals
self.sliceWidget = sliceWidget
self.sliceLogic = sliceWidget.sliceLogic()
self.sliceView = self.sliceWidget.sliceView()
self.interactor = self.sliceView.interactorStyle().GetInteractor()
self.renderWindow = self.sliceWidget.sliceView().renderWindow()
self.renderer = self.renderWindow.GetRenderers().GetItemAsObject(0)
#self.editUtil = EditUtil.EditUtil()
# optionally set by users of the class
self.undoRedo = None
# actors in the renderer that need to be cleaned up on destruction
self.actors = []
# the current operation
self.actionState = None
# set up observers on the interactor
# - keep track of tags so these can be removed later
# - currently all editor effects are restricted to these events
# - make the observers high priority so they can override other
# event processors
self.interactorObserverTags = []
events = ( vtk.vtkCommand.LeftButtonPressEvent,
vtk.vtkCommand.LeftButtonReleaseEvent,
vtk.vtkCommand.MiddleButtonPressEvent,
vtk.vtkCommand.MiddleButtonReleaseEvent,
vtk.vtkCommand.RightButtonPressEvent,
vtk.vtkCommand.RightButtonReleaseEvent,
vtk.vtkCommand.LeftButtonDoubleClickEvent,
vtk.vtkCommand.MouseMoveEvent,
vtk.vtkCommand.KeyPressEvent,
vtk.vtkCommand.KeyReleaseEvent,
vtk.vtkCommand.EnterEvent,
vtk.vtkCommand.LeaveEvent,
vtk.vtkCommand.MouseWheelForwardEvent,
vtk.vtkCommand.MouseWheelBackwardEvent)
for e in events:
tag = self.interactor.AddObserver(e, self.processEvent, 1.0)
self.interactorObserverTags.append(tag)
self.sliceNodeTags = []
sliceNode = self.sliceLogic.GetSliceNode()
tag = sliceNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.processEvent, 1.0)
self.sliceNodeTags.append(tag)
# spot for tracking the current cursor while it is turned off for paining
self.savedCursor = None
def processEvent(self, caller=None, event=None):
"""Event filter that lisens for certain key events that
should be responded to by all events.
Currently:
'\\' - pick up paint color from current location (eyedropper)
"""
if event == "KeyPressEvent":
key = self.interactor.GetKeySym()
if key.lower() == 's':
return True
return False
def cursorOff(self):
"""Turn off and save the current cursor so
the user can see the background image during editing"""
qt.QApplication.setOverrideCursor(qt.QCursor(10))
#self.savedCursor = self.sliceWidget.cursor
#qt_BlankCursor = 10
#self.sliceWidget.setCursor(qt.QCursor(qt_BlankCursor))
def cursorOn(self):
"""Restore the saved cursor if it exists, otherwise
just restore the default cursor"""
qt.QApplication.restoreOverrideCursor()
#if self.savedCursor:
# self.sliceWidget.setCursor(self.savedCursor)
#else:
# self.sliceWidget.unsetCursor()
def abortEvent(self,event):
"""Set the AbortFlag on the vtkCommand associated
with the event - causes other things listening to the
interactor not to receive the events"""
# TODO: make interactorObserverTags a map to we can
# explicitly abort just the event we handled - it will
# be slightly more efficient
for tag in self.interactorObserverTags:
cmd = self.interactor.GetCommand(tag)
cmd.SetAbortFlag(1)
def cleanup(self):
"""clean up actors and observers"""
for a in self.actors:
self.renderer.RemoveActor2D(a)
self.sliceView.scheduleRender()
for tag in self.interactorObserverTags:
self.interactor.RemoveObserver(tag)
sliceNode = self.sliceLogic.GetSliceNode()
for tag in self.sliceNodeTags:
sliceNode.RemoveObserver(tag)
| gpl-3.0 | 2,148,631,814,116,157,400 | 35.358974 | 85 | 0.718853 | false | 3.971989 | false | false | false |
clagiordano/projectDeploy | modules/utils.py | 1 | 1458 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import shlex
import socket
import modules.outputUtils as out
def getSessionInfo():
info = {}
output = subprocess.Popen(["who", "am", "i"], stdout=subprocess.PIPE).communicate()
output = output[0].strip().split(' ')
info['username'] = os.getlogin()
info['ipaddress'] = output[-1][1:-1]
info['hostname'] = socket.gethostname()
if info['ipaddress'] != ":0":
try:
info['hostname'] = socket.gethostbyaddr(info['ipaddress'])
except:
try:
info['hostname'] = getNetbiosHostname(info['ipaddress'])
except:
info['hostname'] = info['ipaddress']
return info
def getNetbiosHostname(ipaddress):
output = runShellCommand("nmblookup -A " + ipaddress, False)
hostname = output[0].split('\n')[1].split(' ')[0].strip()
if hostname == 'No':
hostname = output[0]
return hostname
def runShellCommand(command, shell=True):
try:
p = subprocess.Popen( \
shlex.split(command), \
shell=shell, \
stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE)
command_output, command_error = p.communicate()
exit_status = p.returncode
except:
out.fatalError("Failed to execute command " + command)
return command_output, exit_status, command_error
| lgpl-3.0 | -8,159,037,422,695,601,000 | 27.588235 | 87 | 0.59465 | false | 4.027624 | false | false | false |
m4dcoder/cortex | setup.py | 1 | 1799 | #!/usr/bin/env python2.7
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from setuptools import setup, find_packages
PKG_ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
PKG_REQ_FILE = '%s/requirements.txt' % PKG_ROOT_DIR
os.chdir(PKG_ROOT_DIR)
def get_version_string():
version = None
sys.path.insert(0, PKG_ROOT_DIR)
from cortex import __version__
version = __version__
sys.path.pop(0)
return version
def get_requirements():
with open(PKG_REQ_FILE) as f:
required = f.read().splitlines()
# Ignore comments in the requirements file
required = [line for line in required if not line.startswith('#')]
return required
setup(
name='cortex',
version=get_version_string(),
packages=find_packages(exclude=[]),
install_requires=get_requirements(),
license='Apache License (2.0)',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7'
]
)
| apache-2.0 | 2,384,394,651,823,324,000 | 28.983333 | 74 | 0.67871 | false | 3.997778 | false | false | false |
Kwentar/ImageDownloader | vk.py | 1 | 7993 | import json
import random
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.request import urlopen, http, Request
import time
from datetime import date
from Profiler import Profiler
import __setup_photo__ as setup
class VkError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class VkUser:
def __init__(self, uid, name, last_name, day_b, month_b, sex, city_id, age=-1, year_b=-1):
self.uid = uid
self.name = name
self.last_name = last_name
self.day_b = day_b
self.month_b = month_b
if year_b == -1:
year_b = date.today().year - age
if month_b < date.today().month or month_b == date.today().month and day_b < date.today().day:
year_b -= 1
self.year_b = year_b
self.sex = sex
self.city_id = city_id
def __str__(self):
return ";".join([self.uid, self.name, self.last_name,
self.day_b.__str__(), self.month_b.__str__(),
self.year_b.__str__(), self.sex.__str__(),
self.city_id.__str__()])
def get_age(self):
return date.today().year - self.year_b
class Vk:
tokens = setup.user_tokens
curr_token = ''
p = Profiler()
@staticmethod
def check_time(value=0.5):
if Vk.p.get_time() < value:
time.sleep(value)
Vk.p.start()
@staticmethod
def set_token(token):
Vk.tokens.clear()
Vk.tokens.append(token)
@staticmethod
def get_token():
while True:
el = random.choice(Vk.tokens)
if el != Vk.curr_token:
test_url = 'https://api.vk.com/method/getProfiles?uid=66748&v=5.103&access_token=' + el
Vk.check_time(1)
try:
response = urlopen(test_url).read()
result = json.loads(response.decode('utf-8'))
if 'response' in result.keys():
print('now I use the ' + el + ' token')
Vk.curr_token = el
return el
except http.client.BadStatusLine as err_:
print("".join(['ERROR Vk.get_token', err_.__str__()]))
raise VkError('all tokens are invalid: ' + result['error']['error_msg'].__str__())
@staticmethod
def call_api(method, params):
Vk.check_time()
while not Vk.curr_token:
Vk.get_token()
if isinstance(params, list):
params_list = params[:]
elif isinstance(params, dict):
params_list = params.items()
else:
params_list = [params]
params_list += [('access_token', Vk.curr_token), ('v', '5.103')]
url = 'https://api.vk.com/method/%s?%s' % (method, urlencode(params_list))
try:
req = Request(url=url, headers={'User-agent': random.choice(setup.user_agents)})
response = urlopen(req).read()
result = json.loads(response.decode('utf-8'))
try:
if 'response' in result.keys():
return result['response']
else:
raise VkError('no response on answer: ' + result['error']['error_msg'].__str__())
except VkError as err_:
print(err_.value)
Vk.curr_token = Vk.get_token()
# Vk.call_api(method, params)
except URLError as err_:
print('URLError: ' + err_.errno.__str__() + ", " + err_.reason.__str__())
except http.client.BadStatusLine as err_:
print("".join(['ERROR Vk.call_api', err_.__str__()]))
except ConnectionResetError as err_:
print("".join(['ERROR ConnectionResetError', err_.__str__()]))
except ConnectionAbortedError as err_:
print("".join(['ERROR ConnectionAbortedError', err_.__str__()]))
return list()
@staticmethod
def get_uids(age, month, day, city_id, fields='sex'):
search_q = list()
search_q.append(('offset', '0'))
search_q.append(('count', '300'))
search_q.append(('city', city_id))
search_q.append(('fields', fields))
search_q.append(('age_from', age))
search_q.append(('age_to', age))
search_q.append(('has_photo', '1'))
search_q.append(('birth_day', day))
search_q.append(('birth_month', month))
r = Vk.call_api('users.search', search_q)
count = r['count']
users = list()
for el in r['items']:
if 'id' in el.keys() and not el['is_closed']:
user = VkUser(uid=el['id'].__str__(), name=el['first_name'],
last_name=el['last_name'], sex=el['sex'],
day_b=day, month_b=month, age=age, city_id=city_id)
users.append(user)
if count > 1000:
Vk.warning('''Count more than 1000, count = {}, age = {},
month = {}, day = {}'''.format(count, age, month, day))
return users
@staticmethod
def create_user_from_response(response):
if 'user_id' in response.keys():
uid = response['user_id'].__str__()
elif 'uid' in response.keys():
uid = response['uid'].__str__()
else:
return None
if 'deactivated' in response.keys():
return None
last_name = 'None'
sex = 'None'
name = 'None'
city_id = 'None'
day, month, age = [0, 0, 0]
if 'last_name' in response.keys():
last_name = response['last_name'].__str__()
if 'first_name' in response.keys():
name = response['first_name'].__str__()
if 'sex' in response.keys():
sex = response['sex'].__str__()
if 'city' in response.keys():
city_id = response['city'].__str__()
if 'bdate' in response.keys():
bdate = response['bdate'].__str__().split('.')
if len(bdate) > 2:
day, month, age = map(int, bdate)
age = date.today().year - age
else:
day, month = map(int, bdate)
user = VkUser(uid=uid, name=name, last_name=last_name, sex=sex, day_b=day,
month_b=month, age=age, city_id=city_id)
return user
@staticmethod
def get_user_info(uid, fields='city,bdate,sex'):
search_q = list()
search_q.append(('user_id', uid))
search_q.append(('fields', fields))
r = Vk.call_api('users.get', search_q)
for el in r:
user = Vk.create_user_from_response(el)
if user is not None:
return user
@staticmethod
def get_friends(uid, fields='city,bdate,sex'):
search_q = list()
search_q.append(('user_id', uid))
search_q.append(('offset', '0'))
search_q.append(('count', '1000'))
search_q.append(('fields', fields))
r = Vk.call_api('friends.get', search_q)
count = len(r)
users = list()
for el in r:
user = Vk.create_user_from_response(el)
if user is not None:
users.append(user)
if count > 1000:
Vk.warning('Count more than 1000')
return users
@staticmethod
def get_profile_photos(id_):
q = list()
q.append(('owner_id', id_))
q.append(('count', '10'))
q.append(('rev', '1'))
q.append(('extended', '1'))
q.append(('photos_size', '0'))
r = Vk.call_api('photos.getAll', q)
images = []
for photo in r['items']:
max_photo = max(photo['sizes'], key=lambda x: x['width']*x['height'])
images.append(max_photo['url'])
return images
@staticmethod
def warning(msg):
print(msg)
| mit | -8,803,733,512,979,355,000 | 34.524444 | 106 | 0.505067 | false | 3.754345 | false | false | false |