function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def hello_app(environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('200 OK', headers) return [b'Hello!']
geertj/gruvi
[ 95, 11, 95, 2, 1355003397 ]
def perf_parsing_speed(self): transport = MockTransport() protocol = HttpProtocol() transport.start(protocol) r = b'HTTP/1.1 200 OK\r\nContent-Length: 10000\r\n\r\n' r += b'x' * 10000 reqs = 4 * r nbytes = 0 t0 = t1 = time.time() while t1 - t0 < 1.0: protocol.data_received(reqs) del protocol._queue._heap[:] nbytes += len(reqs) t1 = time.time() speed = nbytes / (t1 - t0) / (1024 * 1024) self.add_result(speed)
geertj/gruvi
[ 95, 11, 95, 2, 1355003397 ]
def __init__( self, plotly_name="symmetric", parent_name="scatter3d.error_y", **kwargs
plotly/python-api
[ 13052, 2308, 13052, 1319, 1385013188 ]
def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list( self, resource_group_name: str, resource_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): if not next_link:
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_long_running_output(pipeline_response): response = pipeline_response.http_response deserialized = self._deserialize('AgentPool', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {})
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_long_running_output(pipeline_response): response_headers = {} response = pipeline_response.http_response response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation'))
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def build(self, input_shape): """See tfkl.Layer.build.""" assert self._event_shape is not None, \ 'Unlike MADE, MAN require specified event_shape at __init__' # `event_shape` wasn't specied at __init__, so infer from `input_shape`. self._input_size = input_shape[-1] # Construct the masks. self._input_order = _create_input_order( self._input_size, self._input_order_param, ) units = [] if self._hidden_units is None else list(self._hidden_units) units.append(self._event_size) masks = _make_dense_autoregressive_masks( params=self._params, event_size=self._input_size, hidden_units=units, input_order=self._input_order, hidden_degrees=self._hidden_degrees, ) masks = masks[:-1] masks[-1] = np.reshape( np.tile(masks[-1][..., tf.newaxis], [1, 1, self._params]), [masks[-1].shape[0], self._event_size * self._params]) self._masks = masks # create placeholder for ouput inputs = tf.keras.Input((self._input_size,), dtype=self.dtype) outputs = [inputs] if self._conditional: conditional_input = tf.keras.Input((self._conditional_size,), dtype=self.dtype) inputs = [inputs, conditional_input] # Input-to-hidden, hidden-to-hidden, and hidden-to-output layers: # [..., self._event_size] -> [..., self._hidden_units[0]]. # [..., self._hidden_units[k-1]] -> [..., self._hidden_units[k]]. # [..., self._hidden_units[-1]] -> [..., event_size * self._params]. layer_output_sizes = list( self._hidden_units) + [self._event_size * self._params] for k in range(len(self._masks)): autoregressive_output = tf.keras.layers.Dense( layer_output_sizes[k], activation=None, use_bias=self._use_bias, kernel_initializer=_make_masked_initializer(self._masks[k], self._kernel_initializer), bias_initializer=self._bias_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, kernel_constraint=_make_masked_constraint(self._masks[k], self._kernel_constraint), bias_constraint=self._bias_constraint, dtype=self.dtype)(outputs[-1]) if (self._conditional and ((self._conditional_layers == 'all_layers') or ((self._conditional_layers == 'first_layer') and (k == 0)))): conditional_output = tf.keras.layers.Dense( layer_output_sizes[k], activation=None, use_bias=False, kernel_initializer=self._kernel_initializer, bias_initializer=None, kernel_regularizer=self._kernel_regularizer, bias_regularizer=None, kernel_constraint=self._kernel_constraint, bias_constraint=None, dtype=self.dtype)(conditional_input) outputs.append( tf.keras.layers.Add()([autoregressive_output, conditional_output])) else: outputs.append(autoregressive_output) # last hidden layer, activation if k + 1 < len(self._masks): outputs.append( tf.keras.layers.Activation(self._activation)(outputs[-1])) self._network = tf.keras.models.Model(inputs=inputs, outputs=outputs[-1]) # Allow network to be called with inputs of shapes that don't match # the specs of the network's input layers. self._network.input_spec = None # Record that the layer has been built. super(AutoregressiveNetwork, self).build(input_shape)
imito/odin
[ 20, 10, 20, 4, 1466893531 ]
def sample_get_operations(): # [START list_operations] from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer import DocumentModelAdministrationClient endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) operations = list(document_model_admin_client.list_operations()) print("The following document model operations exist under my resource:") for operation in operations: print("\nOperation ID: {}".format(operation.operation_id)) print("Operation kind: {}".format(operation.kind)) print("Operation status: {}".format(operation.status)) print("Operation percent completed: {}".format(operation.percent_completed)) print("Operation created on: {}".format(operation.created_on)) print("Operation last updated on: {}".format(operation.last_updated_on)) print("Resource location of successful operation: {}".format(operation.resource_location)) # [END list_operations] # [START get_operation] # Get an operation by ID if operations: print("\nGetting operation info by ID: {}".format(operations[0].operation_id)) operation_info = document_model_admin_client.get_operation(operations[0].operation_id) if operation_info.status == "succeeded": print("My {} operation is completed.".format(operation_info.kind)) result = operation_info.result print("Model ID: {}".format(result.model_id)) elif operation_info.status == "failed": print("My {} operation failed.".format(operation_info.kind)) error = operation_info.error print("{}: {}".format(error.code, error.message)) else: print("My operation status is {}".format(operation_info.status)) else: print("No operations found.") # [END get_operation]
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self): self.screen = curses.initscr() self.screen.clear()
manly-man/moodle-destroyer-tools
[ 7, 2, 7, 3, 1422642405 ]
def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__') curses.nocbreak() self.screen.keypad(False) curses.echo() curses.endwin()
manly-man/moodle-destroyer-tools
[ 7, 2, 7, 3, 1422642405 ]
def __init__( self, plotly_name="minexponent", parent_name="histogram.marker.colorbar", **kwargs
plotly/plotly.py
[ 13052, 2308, 13052, 1319, 1385013188 ]
def test_watch_bad_argument(self): """Should not reload a module""" self.assertFalse( reloading.refresh(datetime, force=True), Message('Should not reload not a module') )
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def test_watch_not_needed(self): """Don't reload modules that haven't changed.""" support.create_project(self, 'betty') project = cd.project.get_internal_project() project.current_step = project.steps[0] self.assertFalse( reloading.refresh(mime_text), Message('Expect no reload if the step has not been run before.') ) support.run_command('run') project.current_step = project.steps[0] self.assertFalse( reloading.refresh(mime_text), Message('Expect no reload if module has not changed recently.') )
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def test_get_module_name(self): """Should get the module name from the name of its spec.""" target = MagicMock() target.__spec__ = MagicMock() target.__spec__.name = 'hello' self.assertEqual('hello', reloading.get_module_name(target))
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def test_do_reload_error(self, reload: MagicMock, os_path: MagicMock): """Should fail to import the specified module and so return False.""" target = MagicMock() target.__file__ = None target.__path__ = ['fake'] os_path.getmtime.return_value = 10 reload.side_effect = ImportError('FAKE') self.assertFalse(reloading.do_reload(target, 0)) self.assertEqual(1, reload.call_count)
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def test_do_reload(self, reload: MagicMock, os_path: MagicMock): """Should import the specified module and return True.""" target = MagicMock() target.__file__ = 'fake' os_path.getmtime.return_value = 10 self.assertTrue(reloading.do_reload(target, 0)) self.assertEqual(1, reload.call_count)
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def test_do_reload_skip(self, reload: MagicMock, os_path: MagicMock): """ Should skip reloading the specified module because it hasn't been modified and return False. """ target = MagicMock() target.__file__ = 'fake' os_path.getmtime.return_value = 0 self.assertFalse(reloading.do_reload(target, 10)) self.assertEqual(0, reload.call_count)
sernst/cauldron
[ 78, 127, 78, 24, 1461686724 ]
def cfg(): name = 'kyle'
zzsza/TIL
[ 22, 8, 22, 1, 1486867877 ]
def greet(name): print('Hello {}! Nice to greet you!'.format(name))
zzsza/TIL
[ 22, 8, 22, 1, 1486867877 ]
def shout(): print('WHAZZZUUUUUUUUUUP!!!????')
zzsza/TIL
[ 22, 8, 22, 1, 1486867877 ]
def test_suggestion_url(self): client = self.client # self.assertEqual(client.suggestions.address.url, "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address") self.assertEqual(client.suggestions.address.url, "https://dadata.ru/api/v2/suggest/address")
tigrus/dadata-python
[ 11, 7, 11, 1, 1485256853 ]
def __init__(self, *a, **kw): test_web.DummyRequest.__init__(self, *a, **kw) self.requestHeaders = http_headers.Headers() self.content = StringIO()
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def setHeader(self, name, value): return server.Request.setHeader(self, name, value)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def setResponseCode(self, code, message=None): server.Request.setResponseCode(self, code, message)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def written_as_string(self): return ''.join(self.written)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def setUp(self): self.runtime_environment = processing.RuntimeEnvironment() self.service = service.IService(self.runtime_environment.application) self.dependency_manager = self.runtime_environment.dependency_manager self.configuration_manager = self.runtime_environment.configuration_manager self.resource_manager = self.runtime_environment.resource_manager self.dependency_manager.configure(self.runtime_environment)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def _create_configured_web_resource(self, routing, site_configuration=None): site_configuration = site_configuration or dict() web_site = web_provider.WebSite('site_name', site_configuration) web_resource = web_provider.WebResource(web_site, routing) web_resource.configure(self.runtime_environment) return web_resource
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def getResourceForFakeRequest(self, site, post_path=None, request=None): if not request: request = DummyRequest(post_path) return site.factory.getResourceFor(request)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_enabled_web_sites_provided(self): provider = web_provider.WebResourceProvider() self.configuration_manager.set('web.my_site.routing', dict(__config__=dict(processor='a_processor')) ) self.configuration_manager.set('web.another_site.enabled', False) self.configuration_manager.set('web.another_site.routing', dict(__config__=dict(processor='a_processor')) ) provider.configure(self.runtime_environment) self.assertEquals(len(provider.services), 1)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_no_resource_processor_routing(self): config = dict( routing = dict( __config__ = dict(processor='pipeline.root_pipeline', no_resource_processor='pipeline.root_no_resource_pipeline'), foo = dict( __config__ = dict(processor = 'pipeline.foo_pipeline') ), bar = dict( baz = dict( __config__ = dict(no_resource_processor = 'pipeline.baz_pipeline') ) ) ) ) web_site = self.getConfiguredWebSite(config) root_resource = self.getResourceForFakeRequest(web_site, ['']) self.assertConfiguredWithProcessor(root_resource, processor='pipeline.root_pipeline', no_resource_processor='pipeline.root_no_resource_pipeline') # nonexistent resources should be rendered by the closest matching no-resource-pipeline_dependency self.assertEquals(self.getResourceForFakeRequest(web_site, ['nonexistent']), root_resource) self.assertEquals(self.getResourceForFakeRequest(web_site, ['nonexistent', 'nested']), root_resource) # since foo does not have a no_resource_processor, its no_resources should be rendered by the root_resource self.assertEquals(self.getResourceForFakeRequest(web_site, ['foo', 'nonexistent']), root_resource) self.assertEquals(self.getResourceForFakeRequest(web_site, ['foo', 'nonexistent', 'nested']), root_resource) # since bar does not have a processor/no_resource_processor, it should be rendered by the root_resource self.assertEquals(self.getResourceForFakeRequest(web_site, ['bar']), root_resource) self.assertConfiguredWithProcessor(self.getResourceForFakeRequest(web_site, ['foo']), processor='pipeline.foo_pipeline') self.assertConfiguredWithProcessor(self.getResourceForFakeRequest(web_site, ['foo', '']), processor='pipeline.foo_pipeline') baz_resource = self.getResourceForFakeRequest(web_site, ['bar', 'baz']) self.assertConfiguredWithProcessor(baz_resource, no_resource_processor='pipeline.baz_pipeline') # since baz has a no_resource_processor, it is capable of rendering that itself doesn't have a "proper" resource/processor self.assertEquals(self.getResourceForFakeRequest(web_site, ['bar', 'baz', '']), baz_resource) self.assertEquals(self.getResourceForFakeRequest(web_site, ['bar', 'baz', 'nonexistent']), baz_resource) self.assertEquals(self.getResourceForFakeRequest(web_site, ['bar', 'baz', 'nonexistent', 'nested']), baz_resource)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def assertRequestRenderedWithPostPath(web_site, batons, request, post_path): self.getResourceForFakeRequest(web_site, request=request).render(request) self.assertEquals(batons, [dict(request=request)]) request = batons.pop()['request'] self.assertEquals(request.postpath, post_path)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_static_preprocessors(self): current_file = filepath.FilePath(__file__) config = dict( routing = dict( __config__ = dict( static = dict( path = current_file.dirname(), preprocessors = dict( foo = "request: request.setHeader('foo', 'bar')" ) ) ) ) ) web_site = self.getConfiguredWebSite(config) # send a request for this file: request = DummyRequest([current_file.basename()]) resource = web_site.factory.getResourceFor(request) resource.render(request) self.assertEquals(request.responseHeaders.getRawHeaders('foo'), ['bar'])
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_web_resource_simple_request_processing(self): web_resource = self._create_configured_web_resource(dict(__config__=dict(processor='pipeline.a_pipeline'))) request = DummyRequest(['']) batons = list() web_resource.processor_dependency.on_resource_ready(batons.append) # rendering the request should result in a baton being processed by the processor web_resource.render(request) self.assertEquals(batons, [dict(request=request)])
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def raiser(baton): raise Exception()
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_web_resource_processing_raises_with_debugging(self): routing = dict(__config__=dict(processor='pipeline.a_pipeline')) site_config = dict(debug=dict(allow=['localhost'])) web_resource = self._create_configured_web_resource(routing, site_config) request = DummyRequest(['']) request.client = address.IPv4Address('TCP', 'localhost', 1234) def raiser(baton): raise Exception() web_resource.processor_dependency.on_resource_ready(raiser) # rendering the request should result in an exception response web_resource.render(request) self.assertIn('web.Server Traceback (most recent call last)', ''.join(request.written)) self.assertEquals(request.code, 500)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_debug_handler_reaping(self): # reap all debuggers every reactor iteration: site_config = dict(routing=dict()) web_site = web_provider.WebSite('site_name', site_config) debug_handler = web_provider.WebDebugHandler(web_site, reap_interval=0, max_inactive_time=0) debug_handler.setServiceParent(self.service) self.service.startService() f = failure.Failure(Exception()) debug_handler.register_failure(f) self.assertEquals(len(debug_handler.children), 1) yield util.wait(0) # give the reaper one reactor iteration to reap the debugger self.assertEquals(len(debug_handler.children), 0)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_web_debugger(self): # create a failure instance with an actual traceback: foo = 42 # this will become part of the debuggers namespace try: raise Exception() except Exception as e: f = util.NonCleaningFailure() web_debugger = web_provider.WebDebugger(f) request = DummyRequest([]) request.addArg('expr', 'foo') result = web_debugger.render(request) # the result should be json-encoded self.assertEquals(result, json.dumps('42\n'))
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_request_finished_when_garbage_collected(self): web_site = web_provider.WebSite('site_name', dict(routing=dict(__config__=dict(processor='pipeline.test_pipeline')))) web_site.configure(self.runtime_environment) batons = list() web_resource = self.getResourceForFakeRequest(web_site, []) web_resource.processor_dependency = dependencies.InstanceDependency(batons.append) web_resource.processor_dependency.is_ready = True request = DummyRequest([]) web_resource.render(request) # the processor should have been asked to process a baton self.assertEquals(len(batons), 1) self.assertEquals(batons[0]['request'], request) # the processor didn't finish the request: self.assertEquals(request.finished, False) # .. however, when the processor loses the reference to the request, it should be # automatically finished: batons.pop() self.assertEquals(request.finished, True)
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_concatenating_files(self): test_data_path = filepath.FilePath(__file__).sibling('data') file_paths = [test_data_path.child('foo'), test_data_path.child('bar')] cf = web_provider.ConcatenatedFile('text/plain', file_paths) request = DummyRequest(['']) text = cf.render_GET(request) self.assertEquals(text, 'foo\nbar\n')
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def test_just_a_single_file(self): test_data_path = filepath.FilePath(__file__).sibling('data') file_paths = [test_data_path.child('foo')] cf = web_provider.ConcatenatedFile('text/plain', file_paths) request = DummyRequest(['']) text = cf.render_GET(request) self.assertEquals(text, 'foo\n')
foundit/Piped
[ 21, 4, 21, 5, 1308050379 ]
def __init__(self, *args, **kwargs): #method, initialisng tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_iconbitmap(self, default="favicon.ico") container = tk.Frame(self) #container for holding everything container.pack(side = "top", fill = None, expand = False) container.pack_propagate(0) # don't shrink container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) self.frames = {} #dictionary of frames for F in (StartPage, RadioPage, MapPage, DataPage, InvPage, StatsPage): #loop through the number of pages frame = F(container, self) self.frames[F] = frame frame.grid(row = 0, column = 0, sticky = "nsew") #alignment plus stretch self.show_frame(StartPage)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def music(self, uri): spotify = spotipy.Spotify() results = spotify.artist_top_tracks(uri) #getting the track and audio link to top song for track in results['tracks'][:1]: text2 = track['preview_url'] return text2
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def getTweets(self): x = t.statuses.home_timeline(screen_name="AndrewKLeech") return x
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def get_map(self,lat,lng): latString = str(lat) lngString = str(lng) #Map url from google maps, has marker and colors included url = ("https://maps.googleapis.com/maps/api/staticmap?center="+latString+","+lngString+"&size=450x250&zoom=16&style=feature:road.local%7Celement:geometry%7Ccolor:0x00ff00%7Cweight:1%7Cvisibility:on&style=feature:landscape%7Celement:geometry.fill%7Ccolor:0x000000%7Cvisibility:on&style=feature:landscape%7Celement:geometry.fill%7Ccolor:0x000000%7Cvisibility:on&style=feature:administrative%7Celement:labels%7Cweight:3.9%7Cvisibility:on%7Cinverse_lightness:true&style=feature:poi%7Cvisibility:simplified&markers=color:blue%7Clabel:H%7C"+latString+","+lngString+"&markers=size:tiny%7Ccolor:green%7CDelta+Junction,AK\&sensor=false") buffer = BytesIO(urllib.request.urlopen(url).read()) pil_image = PIL.Image.open(buffer) tk_image = ImageTk.PhotoImage(pil_image) # put the image in program mapLabel = Label(image=tk_image) mapLabel.pack() mainloop()
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def game(self): w, h = 500, 500 # Pack pygame in `embed`. root = tk.Tk() embed = tk.Frame(root, width=w, height=h) embed.pack() # Tell pygame's SDL window which window ID to use os.environ['SDL_WINDOWID'] = str(embed.winfo_id()) # Show the window so it's assigned an ID. root.update() # Game for Pip-Boy # Imports import pygame import random # Initialise PyGame pygame.init() # Set display width and height display_width = 500 display_height = 500 # Create a gameDisplay using display_width and display_height gameDisplay = pygame.display.set_mode((display_width, display_height)) # Set the caption of the window to Turret Defense pygame.display.set_caption('Tank War!') # Create colours using RGB values black = (0, 0, 0) green = (0, 150, 0) lightGreen = (0, 255, 0) # Create fonts smallFont = pygame.font.SysFont(None, 25) mediumFont = pygame.font.SysFont(None, 50) largeFont = pygame.font.SysFont(None, 75) # Initialise the clock for FPS clock = pygame.time.Clock() # Tank part dimensions tankWidth = 40 tankHeight = 20 turretWidth = 5 wheelWidth = 5 # Ground height ground = .85 * display_height # Load sounds fireSound = pygame.mixer.Sound("fireSound.wav") cannon = pygame.mixer.Sound("cannon.wav") def text_objects(text, color, size="smallFont"): # Function returns text for blitting if size == "smallFont": textSurface = smallFont.render(text, True, color) if size == "mediumFont": textSurface = mediumFont.render(text, True, color) if size == "largeFont": textSurface = largeFont.render(text, True, color) return textSurface, textSurface.get_rect() def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size="smallFont"): # Blits text to button textSurface, textRect = text_objects(msg, color, size) textRect.center = ((buttonx + buttonwidth / 2), buttony + (buttonheight / 2)) gameDisplay.blit(textSurface, textRect) def message_to_screen(msg, color, y_displace=0, size="smallFont"): # Blits the text returned from text_objects textSurface, textRect = text_objects(msg, color, size) textRect.center = (int(display_width / 2), int(display_height / 2) + y_displace) gameDisplay.blit(textSurface, textRect) def tank(x, y, turretPosition): # Draws the tank and turret # Casting x and y to be ints x = int(x) y = int(y) # Set possible turret positions turrets = [(x - 27, y - 2), (x - 26, y - 5), (x - 25, y - 8), (x - 23, y - 12), (x - 20, y - 14), (x - 18, y - 15), (x - 15, y - 17), (x - 13, y - 19), (x - 11, y - 21)] # Draw the tank pygame.draw.circle(gameDisplay, green, (int(x), int(y)), 10) pygame.draw.rect(gameDisplay, green, (x - tankHeight, y, tankWidth, tankHeight)) pygame.draw.line(gameDisplay, green, (x, y), turrets[turretPosition], turretWidth) # Draw the wheels pygame.draw.circle(gameDisplay, green, (x - 15, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x - 10, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x - 5, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 0, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 5, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 10, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 15, y + 20), wheelWidth) # Return the turret position return turrets[turretPosition] def enemyTank(x, y, turretPosition): # Draws the tank and turret # Casting x and y to be ints x = int(x) y = int(y) # Set possible turret positions turrets = [(x + 27, y - 2), (x + 26, y - 5), (x + 25, y - 8), (x + 23, y - 12), (x + 20, y - 14), (x + 18, y - 15), (x + 15, y - 17), (x + 13, y - 19), (x + 11, y - 21)] # Draw the tank pygame.draw.circle(gameDisplay, green, (int(x), int(y)), 10) pygame.draw.rect(gameDisplay, green, (x - tankHeight, y, tankWidth, tankHeight)) pygame.draw.line(gameDisplay, green, (x, y), turrets[turretPosition], turretWidth) pygame.draw.circle(gameDisplay, green, (x - 15, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x - 10, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x - 5, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 0, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 5, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 10, y + 20), wheelWidth) pygame.draw.circle(gameDisplay, green, (x + 15, y + 20), wheelWidth) return turrets[turretPosition] def explosion(x, y): # Draws an explosion on screen # Play a sound pygame.mixer.Sound.play(fireSound) explode = True while explode: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() choices = [green, lightGreen] magnitude = 1 while magnitude < 50: explodeBitX = x + random.randrange(-1 * magnitude, magnitude) explodeBitY = y + random.randrange(-1 * magnitude, magnitude) if explodeBitY > ground + 13: pygame.draw.circle(gameDisplay, black, (explodeBitX, explodeBitY), random.randrange(1, 5)) else: pygame.draw.circle(gameDisplay, choices[random.randrange(0, 2)], (explodeBitX, explodeBitY), random.randrange(1, 5)) magnitude += 1 pygame.display.update() clock.tick(100) explode = False def fire(pos, turretPos, gunPower, enemyTankX, enemyTankY): # Function for shooting and controlling bullet physics # Play a sound pygame.mixer.Sound.play(cannon) damage = 0 fire = True startingPos = list(pos) while fire: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() pygame.draw.circle(gameDisplay, green, (startingPos[0], startingPos[1]), 5) startingPos[0] -= (10 - turretPos) * 2 startingPos[1] += int((((startingPos[0] - pos[0]) * .015 / (gunPower / 50)) ** 2) - ( turretPos + turretPos / (12 - turretPos))) # If the explosion is on the ground if startingPos[1] > ground: hitX = int((startingPos[0])) hitY = int(startingPos[1]) # If the explosion hits the tank # Various damages for how close it was if enemyTankX + 10 > hitX > enemyTankX - 10: damage = 25 elif enemyTankX + 15 > hitX > enemyTankX - 15: damage = 20 elif enemyTankX + 20 > hitX > enemyTankX - 20: damage = 15 elif enemyTankX + 30 > hitX > enemyTankX - 30: damage = 5 explosion(hitX, hitY) fire = False pygame.display.update() clock.tick(60) return damage def enemyFire(pos, turretPos, gunPower, playerX, playerY): # Function for shooting and controlling bullet physics # Play a sound pygame.mixer.Sound.play(cannon) damage = 0 currentPower = 1 powerFound = False # How the AI decides what power to uses while not powerFound: currentPower += 1 if currentPower > 100: powerFound = True fire = True startingPos = list(pos) while fire: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() startingPos[0] += (10 - turretPos) * 2 # Make currentPower random between 80% and 120% of the chosen power gunPower = random.randrange(int(currentPower * .8), int(currentPower * 1.2)) startingPos[1] += int((((startingPos[0] - pos[0]) * .015 / (gunPower / 50)) ** 2) - ( turretPos + turretPos / (12 - turretPos))) # If the explosion is on the ground if startingPos[1] > ground: hitX = int((startingPos[0])) hitY = int(startingPos[1]) if playerX + 15 > hitX > playerX - 15: powerFound = True fire = False fire = True startingPos = list(pos) # When the power is decided, it shoots while fire: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() pygame.draw.circle(gameDisplay, green, (startingPos[0], startingPos[1]), 5) startingPos[0] += (10 - turretPos) * 2 startingPos[1] += int((((startingPos[0] - pos[0]) * .015 / (gunPower / 50)) ** 2) - ( turretPos + turretPos / (12 - turretPos))) # If the explosion is on the ground if startingPos[1] > ground: hitX = int((startingPos[0])) hitY = int(startingPos[1]) # If the explosion hits the tank # Various damages for how close it was if playerX + 10 > hitX > playerX - 10: damage = 25 elif playerX + 15 > hitX > playerX - 15: damage = 20 elif playerX + 20 > hitX > playerX - 20: damage = 15 elif playerX + 30 > hitX > playerX - 30: damage = 5 explosion(hitX, hitY) fire = False pygame.display.update() clock.tick(60) return damage def power(level): # Blits the power level text = smallFont.render("Power: " + str(level) + "%", True, green) gameDisplay.blit(text, [display_width * .75, 10]) def game_controls(): # Function for controls screen controls = True while controls: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(black) message_to_screen("Controls!", green, -100, size="largeFont") message_to_screen("Left and right arrow keys to move the tank!", green, 10, size="smallFont") message_to_screen("Up and down arrow keys to move the tank's turret!", green, 40, size="smallFont") message_to_screen("A and D keys change the turret's power!", green, 70, size="smallFont") message_to_screen("P to pause the game!", green, 100, size="smallFont") # Buttons button("Play", 25, 400, 100, 50, green, lightGreen, action="play") button("Quit", 375, 400, 100, 50, green, lightGreen, action="quit") pygame.display.update() clock.tick(15) def button(text, x, y, width, height, colour, active_colour, action): # Creates the button, both active and inactive cursor = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + width > cursor[0] > x and y + height > cursor[1] > y: pygame.draw.rect(gameDisplay, active_colour, (x, y, width, height)) if click[0] == 1 and action != None: if action == "play": gameLoop() if action == "controls": game_controls() if action == "quit": pygame.quit() quit() else: pygame.draw.rect(gameDisplay, colour, (x, y, width, height)) text_to_button(text, black, x, y, width, height) def pause(): # Pauses the game paused = True message_to_screen("Paused", green, -225, size="largeFont") message_to_screen("C to continue playing", green, -175, size="smallFont") message_to_screen("Q to quit", green, -150, size="smallFont") pygame.display.update() while paused: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: paused = False elif event.key == pygame.K_q: pygame.quit() quit() clock.tick(5) def game_intro(): # Function for game introduction screen intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(black) message_to_screen("Tank War!", green, -200, size="largeFont") message_to_screen("Kill the enemy tank before it kills you!", green, -50, size="smallFont") message_to_screen("Press play to play!", green, 0, size="smallFont") message_to_screen("Press controls to view the game's controls!", green, 50, size="smallFont") message_to_screen("Press quit to exit the game!", green, 100, size="smallFont") # Text on the buttons button("Play", 25, 400, 100, 50, green, lightGreen, action="play") button("Controls", 200, 400, 100, 50, green, lightGreen, action="controls") button("Quit", 375, 400, 100, 50, green, lightGreen, action="quit") pygame.display.update() clock.tick(15) def gameWin(): # Function for game introduction screen win = True while win: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(black) message_to_screen("You won!", green, -100, size="largeFont") message_to_screen("Your enemy's tank was destroyed!", green, 0, size="smallFont") message_to_screen("Replay to replay or quit to quit!", green, 100, size="smallFont") # Text on the buttons button("Replay", 25, 400, 100, 50, green, lightGreen, action="play") button("Quit", 375, 400, 100, 50, green, lightGreen, action="quit") pygame.display.update() clock.tick(15) def over(): # Function for game introduction screen over = True while over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(black) message_to_screen("Game over!", green, -100, size="largeFont") message_to_screen("Your tank was destroyed!", green, 0, size="smallFont") message_to_screen("Replay to replay or quit to quit!", green, 100, size="smallFont") # Text on the buttons button("Replay", 25, 400, 100, 50, green, lightGreen, action="play") button("Quit", 375, 400, 100, 50, green, lightGreen, action="quit") pygame.display.update() clock.tick(15) def health(playerHealth, enemyHealth, pX, eX): # Health bars # Player health if playerHealth > 50: playerColour = lightGreen else: playerColour = green # Enemy health if enemyHealth > 50: enemyColour = lightGreen else: enemyColour = green # Draw the health bars pygame.draw.rect(gameDisplay, playerColour, (pX - 100, display_height * .7, playerHealth, 10)) pygame.draw.rect(gameDisplay, enemyColour, (eX, display_height * .7, enemyHealth, 10)) def gameLoop(): # Main game loop gameExit = False gameOver = False FPS = 15 # Tank positioning mainTankX = display_width * .8 mainTankY = display_height * .8 tankMove = 0 curTurretPosition = 0 changeTurretPosition = 0 # Fire power firePower = 50 change = 0 # enemyTank positioning enemyTankX = display_width * .2 enemyTankY = display_height * .8 tankMove = 0 # Health playerHealth = 100 enemyHealth = 100 while not gameExit: if gameOver == True: pygame.display.update() while gameOver == True: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True gameOver = False for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True # Movement for tank if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: tankMove = -5 elif event.key == pygame.K_RIGHT: tankMove = 5 elif event.key == pygame.K_UP: changeTurretPosition = 1 elif event.key == pygame.K_DOWN: changeTurretPosition = -1 elif event.key == pygame.K_p: pause() elif event.key == pygame.K_SPACE: # Player's shot damage = fire(bullet, curTurretPosition, firePower, enemyTankX, enemyTankY) enemyHealth -= damage # Enemy moves movements = ['f', 'b'] move = random.randrange(0, 2) for x in range(random.randrange(0, 10)): if display_width * .33 > enemyTankX > display_width * .05: if movements[move] == "f": enemyTankX += 5 elif movements[move] == "r": enemyTankX -= 5 # If the tank moves, re draw the screen gameDisplay.fill(black) health(playerHealth, enemyHealth, pX, eX) bullet = tank(mainTankX, mainTankY, curTurretPosition) enemyBullet = enemyTank(enemyTankX, enemyTankY, 8) pygame.draw.rect(gameDisplay, green, (0, ground, display_width, 10)) pygame.display.update() clock.tick(FPS) # Enemy's shot damage = enemyFire(enemyBullet, 8, 33, mainTankX, mainTankY) playerHealth -= damage elif event.key == pygame.K_a: change = -1 elif event.key == pygame.K_d: change = 1 # If user stops pressing the button, stop moving the tank elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: tankMove = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: changeTurretPosition = 0 if event.key == pygame.K_a or event.key == pygame.K_d: change = 0 # Draw the game screen mainTankX += tankMove pX = mainTankX eX = enemyTankX gameDisplay.fill(black) health(playerHealth, enemyHealth, pX, eX) bullet = tank(mainTankX, mainTankY, curTurretPosition) enemyBullet = enemyTank(enemyTankX, enemyTankY, 8) pygame.draw.rect(gameDisplay, green, (0, ground, display_width, 10)) # Change power of the bullet firePower += change if firePower <= 1: firePower = 1 if firePower >= 100: firePower = 100 power(firePower) # Check if gameOver or gameWin if playerHealth < 1: over() elif enemyHealth < 1: gameWin() # Turret positioning curTurretPosition += changeTurretPosition if curTurretPosition > 8: curTurretPosition = 8 elif curTurretPosition < 0: curTurretPosition = 0 # Avoid tank and walls collision if mainTankX > display_width: mainTankX -= 5 if mainTankX < display_width * .66: mainTankX += 5 pygame.display.update() clock.tick(FPS) pygame.quit() quit() game_intro() gameLoop()
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0) image = Image.open("Pip Boy Images\mrPip.gif") photo = ImageTk.PhotoImage(image) label = tk.Label(self, image = photo, bg = "black", fg = "white", height = 40, width = 40) label.image = photo #keeping refrence label.pack(side = BOTTOM, padx = 10, pady = 10) #to make width for now label = tk.Label(self, width = 60, bg = "black") label.pack(side = BOTTOM, pady = 120)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0) #opening images for buttons bonjovi1 = Image.open("coverart\Bonjovi.gif") bonjovi = ImageTk.PhotoImage(bonjovi1) toto1 = Image.open("coverart\Toto.gif") toto = ImageTk.PhotoImage(toto1) tameimpala1 = Image.open("coverart\Tameimpala.gif") tameimpala = ImageTk.PhotoImage(tameimpala1) dmx1 = Image.open("coverart\Dmx.gif") dmx = ImageTk.PhotoImage(dmx1) daftpunk1 = Image.open("coverart\Daftpunk.gif") daftpunk = ImageTk.PhotoImage(daftpunk1) gorrillaz1 = Image.open("coverart\Gorrillaz.gif") gorrillaz = ImageTk.PhotoImage(gorrillaz1) estelle1 = Image.open("coverart\estelle.gif") estelle = ImageTk.PhotoImage(estelle1) mgmt1 = Image.open("coverart\Mgmt.gif") mgmt = ImageTk.PhotoImage(mgmt1) saintmotel1 = Image.open("coverart\Saintmotel.gif") saintmotel = ImageTk.PhotoImage(saintmotel1) music1 = tk.Button(self, image = bonjovi, fg = "white", bg = "black", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song1))) music1.image = bonjovi #keeping refrence music1.place(x = 70, y = 70) music2 = tk.Button(self, image = toto, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song2))) music2.image = toto music2.place(x = 70, y = 145) music3 = tk.Button(self, image = tameimpala, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song3))) music3.image = tameimpala music3.place(x = 70, y = 220) music4 = tk.Button(self, image = dmx, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song4))) music4.image = dmx music4.place(x = 175 , y = 70) music5 = tk.Button(self, image = daftpunk, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song5))) music5.image = daftpunk music5.place( x = 175 , y = 145) music6 = tk.Button(self, image = gorrillaz, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song6))) music6.image = gorrillaz music6.place(x = 175, y = 220) music7 = tk.Button(self, image = estelle, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song7))) music7.image = estelle music7.place(x = 280, y = 70) music8 = tk.Button(self, image = mgmt, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song8))) music8.image = mgmt music8.place(x = 280, y = 145) music9 = tk.Button(self, image = saintmotel, bg = "black", fg = "white", cursor = "hand2", width = 75, height = 75, command = lambda: webbrowser.open_new(controller.music(song9))) music9.image = saintmotel music9.place(x = 280, y = 220)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0) label = tk.Label(self, text = "map functionality", bg = "black", fg = "white") label.pack(side = BOTTOM) global entryWidget2 global mapLabel # Create a text frame to hold the text Label and the Entry widget textFrame = Frame(self) #Create a Label in textFrame entryLabel = Label(self) entryLabel["text"] = "Where are you?" entryLabel.pack(side=LEFT) # Create an Entry Widget in textFrame entryWidget2 = Entry(self) entryWidget2["width"] = 50 entryWidget2.pack(side=LEFT) textFrame.pack() mapLabel = Label(self) button = Button(self, text="Submit", command=controller.get_coordinates) button.pack(side=BOTTOM)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0) global entryWidget #Create a Label in textFrame #controller.showTweets(controller.getTweets(), numberOfTweets) entryLabel = Label(self) entryLabel["text"] = "Make a new Tweet:" entryLabel.pack(side = LEFT) # Create an Entry Widget in textFrame entryWidget = Entry(self) entryWidget["width"] = 50 entryWidget.pack(side=LEFT) buttonGet = Button(self, text="Get Tweets", command = lambda: controller.showTweets(controller.getTweets(), numberOfTweets)) buttonGet.pack() button = Button(self, text="Submit", command = controller.tweet) button.pack()
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Frame.configure(self, bg = "black") radio = tk.Button(self, text ="RADIO", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(RadioPage)) radio.place(x = 15, y = 0) map = tk.Button(self, text ="MAP", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(MapPage)) map.place(x = 95, y = 0) data = tk.Button(self, text="DATA", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(DataPage)) data.place(x = 175, y = 0) inv = tk.Button(self, text ="INV", bg="black", fg="green", width = 10, command = lambda: controller.game()) inv.place(x = 255, y = 0) stats = tk.Button(self, text ="STATS", bg="black", fg="green", width = 10, command = lambda: controller.show_frame(StatsPage)) stats.place(x = 335, y = 0) #new buttons strength = tk.Button(self, text ="STRENGTH", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Strength.gif")) strength.place(x = 35, y = 50) perception = tk.Button(self, text ="PERCEPTION", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Perception.gif")) perception.place(x = 35, y = 75) endurance = tk.Button(self, text ="ENDURANCE", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Endurance.gif")) endurance.place(x = 35, y = 100) charisma = tk.Button(self, text ="CHARISMA", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Charisma.gif")) charisma.place(x = 35, y = 125) intelligence = tk.Button(self, text ="INTELLIGENCE", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Intelligence.gif")) intelligence.place(x = 35, y = 150) agility = tk.Button(self, text ="AGILITY", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Agility.gif")) agility.place(x = 35, y = 175) luck = tk.Button(self, text ="LUCK", bg="black", fg="green", width = 20, command = lambda: self.ImageShow("Pip Boy Images\Luck.gif")) luck.place(x = 35, y = 200)
AndrewKLeech/Pip-Boy
[ 12, 2, 12, 1, 1455726425 ]
def __init__(self, xChart, chart): super(_BasePlot, self).__init__() self._element = xChart self._chart = chart
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def categories(self): """ Returns a |category.Categories| sequence object containing a |category.Category| object for each of the category labels associated with this plot. The |category.Category| class derives from ``str``, so the returned value can be treated as a simple sequence of strings for the common case where all you need is the labels in the order they appear on the chart. |category.Categories| provides additional properties for dealing with hierarchical categories when required. """ return Categories(self._element)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def chart(self): """ The |Chart| object containing this plot. """ return self._chart
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def data_labels(self): """ |DataLabels| instance providing properties and methods on the collection of data labels associated with this plot. """ dLbls = self._element.dLbls if dLbls is None: raise ValueError( "plot has no data labels, set has_data_labels = True first" ) return DataLabels(dLbls)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def has_data_labels(self): """ Read/write boolean, |True| if the series has data labels. Assigning |True| causes data labels to be added to the plot. Assigning False removes any existing data labels. """ return self._element.dLbls is not None
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def has_data_labels(self, value): """ Add, remove, or leave alone the ``<c:dLbls>`` child element depending on current state and assigned *value*. If *value* is |True| and no ``<c:dLbls>`` element is present, a new default element is added with default child elements and settings. When |False|, any existing dLbls element is removed. """ if bool(value) is False: self._element._remove_dLbls() else: if self._element.dLbls is None: dLbls = self._element._add_dLbls() dLbls.showVal.val = True
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def series(self): """ A sequence of |Series| objects representing the series in this plot, in the order they appear in the plot. """ return SeriesCollection(self._element)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def vary_by_categories(self): """ Read/write boolean value specifying whether to use a different color for each of the points in this plot. Only effective when there is a single series; PowerPoint automatically varies color by series when more than one series is present. """ varyColors = self._element.varyColors if varyColors is None: return True return varyColors.val
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def vary_by_categories(self, value): self._element.get_or_add_varyColors().val = bool(value)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def gap_width(self): """ Width of gap between bar(s) of each category, as an integer percentage of the bar width. The default value for a new bar chart is 150, representing 150% or 1.5 times the width of a single bar. """ gapWidth = self._element.gapWidth if gapWidth is None: return 150 return gapWidth.val
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def gap_width(self, value): gapWidth = self._element.get_or_add_gapWidth() gapWidth.val = value
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def overlap(self): """ Read/write int value in range -100..100 specifying a percentage of the bar width by which to overlap adjacent bars in a multi-series bar chart. Default is 0. A setting of -100 creates a gap of a full bar width and a setting of 100 causes all the bars in a category to be superimposed. A stacked bar plot has overlap of 100 by default. """ overlap = self._element.overlap if overlap is None: return 0 return overlap.val
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def overlap(self, value): """ Set the value of the ``<c:overlap>`` child element to *int_value*, or remove the overlap element if *int_value* is 0. """ if value == 0: self._element._remove_overlap() return self._element.get_or_add_overlap().val = value
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def bubble_scale(self): """ An integer between 0 and 300 inclusive indicating the percentage of the default size at which bubbles should be displayed. Assigning |None| produces the same behavior as assigning `100`. """ bubbleScale = self._element.bubbleScale if bubbleScale is None: return 100 return bubbleScale.val
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def bubble_scale(self, value): bubbleChart = self._element bubbleChart._remove_bubbleScale() if value is None: return bubbleScale = bubbleChart._add_bubbleScale() bubbleScale.val = value
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def PlotFactory(xChart, chart): """ Return an instance of the appropriate subclass of _BasePlot based on the tagname of *xChart*. """ try: PlotCls = { qn("c:areaChart"): AreaPlot, qn("c:area3DChart"): Area3DPlot, qn("c:barChart"): BarPlot, qn("c:bubbleChart"): BubblePlot, qn("c:doughnutChart"): DoughnutPlot, qn("c:lineChart"): LinePlot, qn("c:pieChart"): PiePlot, qn("c:radarChart"): RadarPlot, qn("c:scatterChart"): XyPlot, }[xChart.tag] except KeyError: raise ValueError("unsupported plot type %s" % xChart.tag) return PlotCls(xChart, chart)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def chart_type(cls, plot): """ Return the member of :ref:`XlChartType` that corresponds to the chart type of *plot*. """ try: chart_type_method = { "AreaPlot": cls._differentiate_area_chart_type, "Area3DPlot": cls._differentiate_area_3d_chart_type, "BarPlot": cls._differentiate_bar_chart_type, "BubblePlot": cls._differentiate_bubble_chart_type, "DoughnutPlot": cls._differentiate_doughnut_chart_type, "LinePlot": cls._differentiate_line_chart_type, "PiePlot": cls._differentiate_pie_chart_type, "RadarPlot": cls._differentiate_radar_chart_type, "XyPlot": cls._differentiate_xy_chart_type, }[plot.__class__.__name__] except KeyError: raise NotImplementedError( "chart_type() not implemented for %s" % plot.__class__.__name__ ) return chart_type_method(plot)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_area_3d_chart_type(cls, plot): return { ST_Grouping.STANDARD: XL.THREE_D_AREA, ST_Grouping.STACKED: XL.THREE_D_AREA_STACKED, ST_Grouping.PERCENT_STACKED: XL.THREE_D_AREA_STACKED_100, }[plot._element.grouping_val]
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_area_chart_type(cls, plot): return { ST_Grouping.STANDARD: XL.AREA, ST_Grouping.STACKED: XL.AREA_STACKED, ST_Grouping.PERCENT_STACKED: XL.AREA_STACKED_100, }[plot._element.grouping_val]
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_bar_chart_type(cls, plot): barChart = plot._element if barChart.barDir.val == ST_BarDir.BAR: return { ST_Grouping.CLUSTERED: XL.BAR_CLUSTERED, ST_Grouping.STACKED: XL.BAR_STACKED, ST_Grouping.PERCENT_STACKED: XL.BAR_STACKED_100, }[barChart.grouping_val] if barChart.barDir.val == ST_BarDir.COL: return { ST_Grouping.CLUSTERED: XL.COLUMN_CLUSTERED, ST_Grouping.STACKED: XL.COLUMN_STACKED, ST_Grouping.PERCENT_STACKED: XL.COLUMN_STACKED_100, }[barChart.grouping_val] raise ValueError("invalid barChart.barDir value '%s'" % barChart.barDir.val)
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_bubble_chart_type(cls, plot): def first_bubble3D(bubbleChart): results = bubbleChart.xpath("c:ser/c:bubble3D") return results[0] if results else None bubbleChart = plot._element bubble3D = first_bubble3D(bubbleChart) if bubble3D is None: return XL.BUBBLE if bubble3D.val: return XL.BUBBLE_THREE_D_EFFECT return XL.BUBBLE
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_doughnut_chart_type(cls, plot): doughnutChart = plot._element explosion = doughnutChart.xpath("./c:ser/c:explosion") return XL.DOUGHNUT_EXPLODED if explosion else XL.DOUGHNUT
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_line_chart_type(cls, plot): lineChart = plot._element def has_line_markers(): matches = lineChart.xpath('c:ser/c:marker/c:symbol[@val="none"]') if matches: return False return True if has_line_markers(): return { ST_Grouping.STANDARD: XL.LINE_MARKERS, ST_Grouping.STACKED: XL.LINE_MARKERS_STACKED, ST_Grouping.PERCENT_STACKED: XL.LINE_MARKERS_STACKED_100, }[plot._element.grouping_val] else: return { ST_Grouping.STANDARD: XL.LINE, ST_Grouping.STACKED: XL.LINE_STACKED, ST_Grouping.PERCENT_STACKED: XL.LINE_STACKED_100, }[plot._element.grouping_val]
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_pie_chart_type(cls, plot): pieChart = plot._element explosion = pieChart.xpath("./c:ser/c:explosion") return XL.PIE_EXPLODED if explosion else XL.PIE
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def _differentiate_radar_chart_type(cls, plot): radarChart = plot._element radar_style = radarChart.xpath("c:radarStyle")[0].get("val") def noMarkers(): matches = radarChart.xpath("c:ser/c:marker/c:symbol") if matches and matches[0].get("val") == "none": return True return False if radar_style is None: return XL.RADAR if radar_style == "filled": return XL.RADAR_FILLED if noMarkers(): return XL.RADAR return XL.RADAR_MARKERS
scanny/python-pptx
[ 1718, 400, 1718, 404, 1353495811 ]
def __init__( self, url, # type: str **kwargs # type: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def _send_request( self, request, # type: HttpRequest **kwargs # type: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def close(self): # type: () -> None self._client.close()
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list( self, resource_group_name, # type: str circuit_name, # type: str peering_name, # type: str **kwargs # type: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'circuitName': self._serialize.url("circuit_name", circuit_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def _any_conditions(modified_access_conditions=None, **kwargs): # pylint: disable=unused-argument return any([ modified_access_conditions.if_modified_since, modified_access_conditions.if_unmodified_since, modified_access_conditions.if_none_match, modified_access_conditions.if_match ])
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list( self, resource_group_name: str, account_name: str, maxpagesize: Optional[str] = None, filter: Optional[str] = None, include: Optional[Union[str, "_models.ListContainersInclude"]] = None, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): if not next_link:
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def __init__(self, configurations): self.jobs = [] for config in configurations: print("CONFIG:", config) self.jobs.append(AsyncTask(TotalScatteringReduction, args=(config,), success_cb=self.on_success, error_cb=self.on_error, finished_cb=self.on_finished))
neutrons/FastGR
[ 5, 5, 5, 38, 1460053228 ]
def start(self): if not self.jobs: raise RuntimeError('Cannot start empty job list') self._start_next()
neutrons/FastGR
[ 5, 5, 5, 38, 1460053228 ]
def on_error(self, task_result): # TODO should emit a signal print('ERROR!!!') self.task_exc_type = task_result.exc_type self.task_exc = task_result.exc_value self.task_exc_stack = traceback.extract_tb(task_result.stack) traceback.print_tb(task_result.stack) print(task_result)
neutrons/FastGR
[ 5, 5, 5, 38, 1460053228 ]
def test_api_basic_publish(self): api = ManagementApi(HTTP_URL, USERNAME, PASSWORD) api.queue.declare(self.queue_name) try: self.assertEqual(api.basic.publish(self.message, self.queue_name), {'routed': True}) finally: api.queue.delete(self.queue_name)
eandersson/amqpstorm
[ 173, 37, 173, 9, 1408606339 ]
def test_api_basic_get_message(self): api = ManagementApi(HTTP_URL, USERNAME, PASSWORD) api.queue.declare(self.queue_name) self.assertEqual(api.basic.publish(self.message, self.queue_name), {'routed': True}) result = api.basic.get(self.queue_name, requeue=False) self.assertIsInstance(result, list) self.assertIsInstance(result[0], Message) self.assertEqual(result[0].body, self.message) # Make sure the message wasn't re-queued. self.assertFalse(api.basic.get(self.queue_name, requeue=False))
eandersson/amqpstorm
[ 173, 37, 173, 9, 1408606339 ]
def test_api_basic_get_message_requeue(self): api = ManagementApi(HTTP_URL, USERNAME, PASSWORD) api.queue.declare(self.queue_name) self.assertEqual(api.basic.publish(self.message, self.queue_name), {'routed': True}) result = api.basic.get(self.queue_name, requeue=True) self.assertIsInstance(result, list) self.assertIsInstance(result[0], Message) self.assertEqual(result[0].body, self.message) # Make sure the message was re-queued. self.assertTrue(api.basic.get(self.queue_name, requeue=False))
eandersson/amqpstorm
[ 173, 37, 173, 9, 1408606339 ]
def E_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., orientation='X', kappa=0., epsr=1.): """ Computing Analytic Electric fields from Plane wave in a Wholespace TODO: Add description of parameters """ XYZ = Utils.asArray_N_x_Dim(XYZ, 3) # Check if XYZ.shape[0] > 1 & t.shape[0] > 1: raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.") mu = mu_0*(1+kappa) if orientation == "X": z = XYZ[:, 2] bunja = -E0*(mu*sig)**0.5 * z * np.exp(-(mu*sig*z**2) / (4*t)) bunmo = 2 * np.pi**0.5 * t**1.5 Ex = bunja / bunmo Ey = np.zeros_like(z) Ez = np.zeros_like(z) return Ex, Ey, Ez else: raise NotImplementedError()
geoscixyz/em_examples
[ 8, 7, 8, 9, 1453777337 ]
def __init__(self,parent): self.parent = parent
iitis/PyLTEs
[ 17, 24, 17, 5, 1427202276 ]
def findPowersRR(self, objectiveFunction="averageThr", sgaGenerations = 100, numberOfThreads = 11, numOfIndividuals = 10, evolveTimes = 10, method="global", x_arg=None, y_arg=None, expectedSignalLoss_arg=None): if method == "local": if x_arg == None: x = self.parent.constraintAreaMaxX/2 else: x = x_arg if y_arg == None: y = self.parent.constraintAreaMaxY/2 else: y = y_arg if expectedSignalLoss_arg == None: maxDistance = min(self.parent.constraintAreaMaxX/2, self.parent.constraintAreaMaxY/2) else: maxDistance = returnDistanceFromSNR(expectedSignalLoss_arg) localBsVector = [] for bs in self.parent.bs: if math.sqrt((bs.x - x)**2 + (bs.y - y)**2) < maxDistance: row = [] row.append(int(bs.ID)) row.append(math.sqrt((bs.x - x)**2 + (bs.y - y)**2)) localBsVector.append(row) localBsVector = np.asarray(localBsVector) if objectiveFunction == "averageThr": if method == "local": localListBS = [] for i in range(len(localBsVector)): localListBS.append(localBsVector[i,0]) prob = pg.problem(local_maximalThroughputProblemRR(dim=len(localBsVector), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower, localListBS=localListBS))
iitis/PyLTEs
[ 17, 24, 17, 5, 1427202276 ]
def returnDistanceFromSNR(expectedSignalLoss): lambda_val = 0.142758313333 a = 4.0 b = 0.0065 c = 17.1 d = 10.8 s = 15.8
iitis/PyLTEs
[ 17, 24, 17, 5, 1427202276 ]