def downloadMovie(self, url, path, title, extension): if not os.path.exists(path): common.log('Path does not exist') return None if title == '': common.log('No title given') return None file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) # Overwrite existing file? if os.path.isfile(file_path): self.pDialog = xbmcgui.Dialog() if not common.ask('File already exists. Overwrite?\n' + os.path.basename(file_path)): title = common.showOSK(urllib.unquote_plus(title), common.translate(30102)) if not title: return None file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) success = self.__download(url, file_path) if success: return file_path else: return None
def downloadMovie(self, url, path, title, extension): if not os.path.exists(path): common.log('Path does not exist') return None if title == '': common.log('No title given') return None file_path = xbmc.makeLegalFilename( os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) # Overwrite existing file? if os.path.isfile(file_path): self.pDialog = xbmcgui.Dialog() if not common.ask('File already exists. Overwrite?\n' + os.path.basename(file_path)): title = common.showOSK(urllib.unquote_plus(title), common.translate(30102)) if not title: return None file_path = xbmc.makeLegalFilename( os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) success = self.__download(url, file_path) if success: return file_path else: return None
def add_predef(self, button): name = common.ask(_('What is the name of this export ?')) if not name: return ir_export = rpc.RPCProxy('ir.exports') iter = self.model2.get_iter_root() fields = [] while iter: field_name = self.model2.get_value(iter, 1) fields.append(field_name) iter = self.model2.iter_next(iter) ir_export.create({'name' : name, 'resource' : self.model, 'export_fields' : [(0, 0, {'name' : f}) for f in fields]}) self.predef_model.append((fields, name, ','.join([self.fields_data[f]['string'] for f in fields])))
def add_predef(self, button): name = common.ask(_('What is the name of this export ?')) if not name: return ir_export = rpc.RPCProxy('ir.exports') iter = self.model2.get_iter_root() fields = [] while iter: field_name = self.model2.get_value(iter, 1) fields.append(field_name) iter = self.model2.iter_next(iter) ir_export.create({ 'name': name, 'resource': self.model, 'export_fields': [(0, 0, { 'name': f }) for f in fields] }) self.predef_model.append( (fields, name, ','.join([self.fields_data[f]['string'] for f in fields])))
def on_event(self, event): if event.type in common.MOUSE_EVENTS: self.mouse.send_event(event) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_b: self.table.blink_checkers_that_can_move() elif event.key == pygame.K_u: #for DEBUG mov = ask(self.world.screen, "Convertir a Dama") regular = re.compile(r'^([0-7]),([0-7])$') if not regular.match(mov): message = 'Fichas ' + mov + ' invalida' self.update_view() else: r, _, c = tuple(mov) try: if self.table.square_occupied((int(r),int(c))): self.table.convert_to_king((int(r),int(c))) except ValueError, mesg: print mesg finally: self.update_view()
def main(): common.start() common.CONF['data_to_fetch'] = common.ask('Fetch Tweet Data or User Data? 1/Tweet 2/User', answer=list, default='2', options=[1, 2]) request_params = {} if common.CONF['data_to_fetch'] == '2': print("You requested User Data") common.CONF['query'] = common.ask('Search terms? ' + 'Found here: https://dev.twitter.com/rest/public/search', answer=common.str_compat) request_params['q'] = common.CONF['query'] url = 'https://api.twitter.com/1.1/users/search.json?' else: print("You requested Tweet Data") common.CONF['query'] = common.ask('Search terms? ' + 'Found here: https://dev.twitter.com/rest/public/search', answer=common.str_compat) request_params['q'] = common.CONF['query'] result_data_type = common.ask('Type of search results? 1/Popular 2/Recent 3/Mixed', answer=list, default='1', options=[1, 2, 3]) request_params['result_type'] = common.RESULT_MAP[result_data_type] location = common.ask('Location? Eg. 1600 Amphitheatre Parkway, Mountain View, CA', answer=common.str_compat, default=" ") if location.strip(): encode_location = urllib.urlencode({'address': location}) response_location = requests.get('https://maps.googleapis.com/maps/api/geocode/json?' + encode_location) try: location_json = response_location.json() location_data = location_json['results'][0]['geometry']['location'] location_array = [str(value) for value in location_data.itervalues()] if location_array: radius_mi = common.ask('Distance to search within in miles', answer=common.str_compat) location_array.append(radius_mi + u'mi') common.CONF['geocode'] = ",".join(location_array) request_params['geocode'] = common.CONF['geocode'] except: print('Unable to fetch lat and long for location') # date = common.ask('Include tweets before? eg. 2015-07-19', answer=dateObject, default=" ") # if date.strip(): # request_params['until'] = date url = 'https://api.twitter.com/1.1/search/tweets.json?' output_file_name = common.ask('Output file name', answer=common.str_compat, default="output") print('Sending request to API...') json_search_data = get_json_data(url, request_params, common.CONF['consumer_key'], common.CONF['consumer_secret'], common.CONF['api_key'], common.CONF['api_secret']) if json_search_data['nodes']: print('API response received.') with open('json_dump.json', 'w') as outfile: json.dump(json_search_data, outfile) outline = gen_outline.make_outline('json_dump.json', False, 'nodes') print('Generating outline file..') outfile = 'outline.json' with open(outfile, 'w') as f: json.dump(outline, f, indent=2, sort_keys=True) print('Outline file generation done.') with open(outfile) as f: key_map = json.load(f) loader = json2csv.Json2Csv(key_map) outfile = output_file_name + '.csv' if os.path.isfile(outfile): os.remove(outfile) print('Writing to %s' % outfile) with open('json_dump.json') as f: loader.load(f) loader.write_csv(filename=outfile, make_strings=True) print('Output file generated.') else: print('Search yield no results')
#!/usr/bin/env python import common from datetime import datetime date_format = "%Y,%m,%d" start = common.ask("Enter the start date:", answer=common.dateObject, dateformat='%Y,%m,%d') end = common.ask("Enter the end date:", answer=common.dateObject, dateformat='%Y,%m,%d') start_date = datetime.strptime(start, date_format) end_date = datetime.strptime(end, date_format) delta = end_date - start_date print(delta.days)
#!/usr/bin/env python import common array_size = common.ask("Enter array size : ", answer=int, l=0) array_input = common.ask("Enter {0} array element : ".format(array_size), answer=list, l=array_size) print("Original array is : {0}".format(" ".join(array_input))) print("New array is : {0}".format(" ".join(list(set(array_input))))) # Test Cases # Input 1: Integers, strings, -ve numbers, 0 # Input 2: matching size entered, non-matching values, strings/numbers allowed as no criteria # specified in question
#!/usr/bin/env python import common input_string = common.ask("Enter input string:", answer=common.str_compat) search_string = common.ask("Enter search string:", answer=common.str_compat) location = common.ask("Enter location to search from:", answer=int, l=-1) def find(s, sub, index): trun_s = s[index:] for i, _ in enumerate(trun_s): if trun_s.startswith(sub, i): return i+index return -1 print(find(input_string, search_string, location))
def main(): sizex, sizey = terminalsize.get_terminal_size() init(autoreset=True) color = True numb = 1 common.start() parameters = {'sort': 'stars', 'order': 'desc'} topic = common.ask( 'What topic would you want your project in? Eg. AI, Machine Learning, Image Processing?', answer=common.str_compat, default="Machine Learning") language = common.ask('Any specific language?', answer=common.str_compat, default=" ") if topic: search_term = 'topic:' + topic if language.strip(): search_term += ' language:' + language.strip() parameters['q'] = search_term project_request = requests.get( 'https://api.github.com/search/repositories', params=parameters).json() if 'items' in project_request: git_details = project_request['items'] for project in git_details: if color: prefix = Fore.RED + Style.BRIGHT + '*' * (sizex / 4) else: prefix = Fore.MAGENTA + Style.BRIGHT + '*' * (sizex / 4) wrapper = textwrap.TextWrapper(initial_indent=prefix, width=sizex, subsequent_indent=' ') print wrapper.fill('*' * (sizex / 4)) print('{} . Project Name: {}'.format(str(numb), project['name'])) print('-' * (sizex / 8)) print('Project Description: \n%s' % project['description']) print('-' * (sizex / 8)) print('Project Url: %s' % project['html_url']) color = not color numb += 1 print('\n\n') clone_index = common.ask( 'Select one of the Projects to clone. Enter index. Eg. 1 for first', answer=list, default="1", options=range(1, len(git_details))) clone_path = common.ask('Path to clone? Leave blank if same path.', answer=common.str_compat, default=' ') if subprocess.check_call('git --version', shell=True) != 0: print( 'git not installed installed, please read link ' + 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.') exit() else: clone_url = git_details[int(clone_index)]['clone_url'] command = 'git clone ' + clone_url if clone_path.strip(): if os.path.isdir(clone_path): command += ' ' + clone_path print('Cloning..') subprocess.check_call(command, shell=True)
def download_media(params): from slugify import slugify #validate path download_folder = Addon().get_setting('download_folder') if not download_folder: common.popup( "Veuillez configurer un répertoire de téléchargement dans les paramètres du plugin" ) common.plugin.log_error("download_media: No directory set") return False #get media details mid = int(params.get('media_id', None)) media = api.get_media_details(mid) media_title = media.get('title') media_subtitle = media.get('subtitle') #media URL stream_node = media.get('url_streaming') if stream_node: media_url = stream_node.get('url', '').encode('utf-8').strip() if not media_url: common.plugin.log_error("unable to get a downloadable stream URL.") common.popup("Impossible de trouver un flux media téléchargeable") return False #filename remote_path = urlparse.urlparse(media_url).path #full path remote_file = media_url.rsplit('/', 1)[-1] #only what's after the last '/' remote_filename = os.path.splitext(remote_file)[0] remote_ext = os.path.splitext(remote_file)[1] if media_subtitle: file_title = "%s - %s" % (media_title, media_subtitle) else: file_title = media_title file_title = slugify(file_title) file_name = file_title + remote_ext file_path = xbmc.makeLegalFilename(os.path.join(download_folder, file_name)) file_path = urllib2.unquote(file_path) common.plugin.log("download_media #{0} - filename:{1} - from:{2}".format( mid, file_name, media_url)) # Overwrite existing file? if os.path.isfile(file_path): do_override = common.ask( 'Le fichier [B]%s[/B] existe déjà. Écraser ?' % (file_name)) if not do_override: return # Download size = 1024 * 1024 start = time.clock() f = open(file_path, 'wb') u = urllib2.urlopen(media_url) bytes_so_far = 0 error = False # Get file size try: total_size = u.info().getheader('Content-Length').strip() total_size = int(total_size) except AttributeError: total_size = 0 # a response doesn't always include the "Content-Length" header if total_size < 1: common.popup( "Erreur lors du téléchargement: Impossible de déterminer la taille du fichier." ) return False # Progress dialog progressdialog = xbmcgui.DialogProgress() progressdialog.create("Téléchargement du média...") #Title while True: # Aborded by user if progressdialog.iscanceled(): error = True break try: buff = u.read(size) if not buff: break else: bytes_so_far += len(buff) f.write(buff) percent = min(100 * bytes_so_far / total_size, 100) speed_str = str( int((bytes_so_far / 1024) / (time.clock() - start))) + ' KB/s' percent_str = str(percent) + '%' progressdialog.update(percent, file_name, percent_str, speed_str) except Exception, e: error = True break
try: if self.table.square_occupied((int(r),int(c))): self.table.convert_to_king((int(r),int(c))) except ValueError, mesg: print mesg finally: self.update_view() #TODO: esto no esta bien, solo lo hago porque este metodo #es para debug self.table._create_path_dictionary() elif event.key == pygame.K_d: #for DEBUG mov = ask(self.world.screen, "Borrar") regular = re.compile(r'^([0-7]),([0-7])$') if not regular.match(mov): message = 'Fichas ' + mov + ' invalida' self.update_view() else: r, _, c = tuple(mov) try: self.table.remove_checker_at((int(r),int(c))) except ValueError, mesg: print mesg finally: self.update_view() #TODO: esto no esta bien, solo lo hago porque este metodo
def download_media(params): from slugify import slugify title= params.get('title'); url= params.get('url'); #validate path download_folder = Addon().get_setting('download_folder') if not download_folder: common.popup("Veuillez configurer un répertoire de téléchargement dans les paramètres du plugin") common.plugin.log_error("download_media: No directory set") return False if not url: common.popup("Impossible de télécharger ce média") plugin.log_error("download_media: Missing URL") return False #filename remote_path = urlparse.urlparse(url).path #full path remote_file = url.rsplit('/', 1)[-1] #only what's after the last '/' remote_filename = os.path.splitext(remote_file)[0] remote_ext = os.path.splitext(remote_file)[1] file_name = slugify(title) + remote_ext file_path = xbmc.makeLegalFilename(os.path.join(download_folder, file_name)) file_path = urllib2.unquote(file_path) common.plugin.log('download_media - filename: %s from %s' % (file_name,url)) # Overwrite existing file? if os.path.isfile(file_path): do_override = common.ask('Le fichier [B]%s[/B] existe déjà. Écraser ?' % (file_name)) if not do_override: return # Download size = 1024 * 1024 start = time.clock() f = open(file_path, 'wb') u = urllib2.urlopen(url) bytes_so_far = 0 error = False # Get file size try: total_size = u.info().getheader('Content-Length').strip() total_size = int(total_size) except AttributeError: total_size = 0 # a response doesn't always include the "Content-Length" header if total_size < 1: common.popup("Erreur lors du téléchargement: Impossible de déterminer la taille du fichier.") return False # Progress dialog progressdialog = xbmcgui.DialogProgress() progressdialog.create("Téléchargement du média...") #Title while True: # Aborded by user if (progressdialog.iscanceled()): error = True break try: buff = u.read(size) if not buff: break else: bytes_so_far += len(buff) f.write(buff) percent = min(100 * bytes_so_far / total_size, 100) speed_str = str(int((bytes_so_far / 1024) / (time.clock() - start))) + ' KB/s' percent_str = str(percent) + '%' progressdialog.update(percent, file_name,percent_str,speed_str) except Exception, e: error = True break