Example #1
0
 def countRows(self,csv1):
     self.dayCounter = 0
     for i in range(len(csv1)):
         self.dayCounter +=1
     print('days in the file:',self.dayCounter)
     print()
     return self.dayCounter
Example #2
0
def fastq_filter(in_file, pos_file, neg_file, wanted):
    """FASTQ filter."""
    from Bio.SeqIO.QualityIO import FastqGeneralIterator
    handle = open(in_file, "r")
    if pos_file is not None and neg_file is not None:
        print "Generating two FASTQ files"
        positive_handle = open(pos_file, "w")
        negative_handle = open(neg_file, "w")
        print in_file
        for title, seq, qual in FastqGeneralIterator(handle):
            print("%s --> %s" % (title, clean_name(title.split(None, 1)[0])))
            if clean_name(title.split(None, 1)[0]) in wanted:
                positive_handle.write("@%s\n%s\n+\n%s\n" % (title, seq, qual))
            else:
                negative_handle.write("@%s\n%s\n+\n%s\n" % (title, seq, qual))
        positive_handle.close()
        negative_handle.close()
    elif pos_file is not None:
        print "Generating matching FASTQ file"
        positive_handle = open(pos_file, "w")
        for title, seq, qual in FastqGeneralIterator(handle):
            if clean_name(title.split(None, 1)[0]) in wanted:
                positive_handle.write("@%s\n%s\n+\n%s\n" % (title, seq, qual))
        positive_handle.close()
    elif neg_file is not None:
        print "Generating non-matching FASTQ file"
        negative_handle = open(neg_file, "w")
        for title, seq, qual in FastqGeneralIterator(handle):
            if clean_name(title.split(None, 1)[0]) not in wanted:
                negative_handle.write("@%s\n%s\n+\n%s\n" % (title, seq, qual))
        negative_handle.close()
    handle.close()
Example #3
0
 def cli_add(self, path):
     print("Loading %s..." %path)
     path = self.fs.selected_get()
     deb = path
     mimetype = mimetypes.guess_type (deb, strict=1)[0]
     print("Starting initial check...")
     if mimetype == "application/x-debian-package":
         try:
             self.deb = debianfile.DebPackage(path, None)
         except:
             return False
         chk_fail = self.deb.check()
         if chk_fail != True:
             print("Initial check failed.")
             self.fs.selected_set(HOME)
             self.fs.path_set(HOME)
             checks.not_installable_popup(self.win, chk_fail)
         else:
             print("Initial check passed.\n")
             self.chk = checks.Checks(path, self.win)
             self.chk.check_file(self.fs, self.win, self.deb)
     elif path == HOME or path == "%s/" %HOME:
         self.fs.selected_set(HOME)
         self.fs.path_set(HOME)
     else:
         print("Invalid file.")
         self.fs.selected_set(HOME)
         self.fs.path_set(HOME)
         checks.generic_error_popup(self.win, "<b>Invalid File Format</><br><br>That is <em>not</> a .deb file!")
     self.n.delete()
Example #4
0
 def key():
     if Player.hasKey == True:
         print("You unlock the door and proceed!")
         Player.hasKey = False
     else:
         print("You have no key! You'll have to find one to proceed!")
         Player.isLocked = True
Example #5
0
 def init_wait(self, fs, path):
     fullpath = self.fs.selected_get()
     if fullpath == HOME or fullpath == "%s/" %HOME:
         self.fs.selected_set(HOME)
         self.fs.path_set(HOME)
         return
     elif path:
         deb = path
         mimetype = mimetypes.guess_type (deb, strict=1)[0]
         if mimetype == "application/x-debian-package":
             self.et = ecore.Timer(0.03, self.init_check, path)
             self.n = n = elm.Notify(self.win)
             lb = elm.Label(self.win)
             lb.text = "<b>Loading Package Information...</b>"
             lb.size_hint_align = 0.0, 0.5
             lb.show()
             n.orient = 1
             n.allow_events_set(False)
             n.content = lb
             n.show()
             return
         else:
             print("Invalid file!")
             self.fs.selected_set(HOME)
             self.fs.path_set(HOME)
             checks.generic_error_popup(self.win, "<b>Invalid File Format</><br><br>That is <em>not</> a .deb file!")
             return
     else:
         self.fs.selected_set(fullpath)
         self.fs.path_set(fullpath)
         return
Example #6
0
def day_is_complete(day_str):
	# Return true if there are evenly spaced logs throughout the day
	day_start = datetime.strptime(day_str + " 00:00", "%Y-%m-%d %H:%M")
	day_end = datetime.strptime(day_str + " 23:59", "%Y-%m-%d %H:%M")
	arp_logs = ArpLog.objects.filter(runtime__gt=day_start, runtime__lt=day_end).order_by('runtime')
	print(arp_logs.count())
	return True
def get_number(lower, upper):
    number = input("Enter a number between ({} - {}):")

    if number < lower or number > upper or number.isdecimal():
        print("Invalid number!")
        number = input("Enter a number between ({} - {}):")
    return int(number)
def formatTemplate(line):
    lastIndex = 0
    index = 0
    isAtPairBegin = False
    templateNames = []
    while index < len(line):
        index = str.find(line, "$", index)
        if index != -1:
            if isAtPairBegin:
                templateNames.append(line[lastIndex+1:index])
                isAtPairBegin = False
            else:
                isAtPairBegin = True
            lastIndex = index
            index = index + 1
        else:
            break
    # line = re.sub(r'[1-9]\.[0-9]+\.[0-9]+', newVersion, line)
    for template in templateNames:
        old = "${0}$".format(template)
        print(type(template))
        new = "%d" % (templateDict[template])
        print(type(new))
        line = str.replace(line, old, new)

    return line
Example #9
0
 def symbolize(self, symbols):
     arg = "+".join(symbols)
     result = subprocess.check_output(
       ["curl",
        "--silent",
        "-d",
        arg,
        self.pprof_url_ + "/symbol"])
     lines = result.split("\n")
     for line in lines:
         # Use whitespace as the delimiter, and produce no more than two parts
         # (i.e. max of 1 split). The symbolized function name may itself contain
         # spaces. A few examples below (the latter two are example with spaces
         # in the name of the function).
         #
         # 0x7fff950fcd23  std::__1::basic_string<>::append()
         # 0x7fff950f943e  operator new()
         # 0x102296ceb     yb::tserver::(anonymous namespace)::SetLastRow()
         parts = line.split(None, 1)
         num_parts = len(parts)
         if num_parts == 0:
             continue
         elif num_parts == 2:
             addr = parts[0]
             symbol = parts[1]
             self.symbols_[addr] = symbol
         else:
             print("Unexpected output line: " + line)
Example #10
0
    def configure_event(self, widget, event):
        rect = widget.get_allocation()
        x, y, width, height = rect.x, rect.y, rect.width, rect.height

        # This is a workaround for a strange bug in Gtk 3
        # where we get multiple configure callbacks even though
        # the size hasn't changed.  We avoid creating a new surface
        # if there is an old surface with the exact same size.
        # This prevents some flickering of the display on focus events.
        wwd, wht = self.get_window_size()
        if (wwd == width) and (wht == height):
            return True
        print("allocation is %d,%d %dx%d" % (x, y, width, height))
        
        win = widget.get_window()
        cr = win.cairo_create()

        # set clip area for exposed region
        cr.rectangle(0, 0, width, height)
        #cr.clip()

        cr.set_source_rgb(*self.bg_rgb)
        cr.paint()
        print("painted")
        #self.configure(width, height)
        return True
Example #11
0
def main(parser, flags, args):
    """Main entry of this Python program.

    Dispatches to the appropriate command.

    Args:
      parser: Parser used to process the command-line arguments.
      flags: Namespace object with the parsed flags.
      args: Unknwon command-line arguments that were not parsed by parser.
    Returns:
      Shell exit code.
    """
    cli = ExpressCLI(flags=flags, args=args, env=os.environ)
    if flags.command is None:
        parser.print_help()
        return os.EX_USAGE
    elif flags.command == "classpath":
        return cli.classpath()
    elif flags.command == "jar":
        return cli.jar()
    elif flags.command == "job":
        return cli.job()
    elif flags.command == "shell":
        return cli.shell()
    elif flags.command == "schema-shell":
        return cli.schema_shell()
    else:
        print("Invalid command: %r" % flags.command)
        parser.print_help()
        return os.EX_USAGE
Example #12
0
def calcPoints(path) :
    predictor_path = '/Users/vovanmozg/Downloads/bigdata/shape_predictor_68_face_landmarks.dat'
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(predictor_path)

    print("Processing file: {}".format(path))
    img = io.imread(path)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    if len(dets) != 1 :
        return False;

    print("Number of faces detected: {}".format(len(dets)))
    points = [];
    for k, d in enumerate(dets):
        #print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
        #    k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = predictor(img, d)
        #print(numpy.matrix([[p.x, p.y] for p in shape.parts()]))
        for p in shape.parts():
            points.append((p.x, p.y))

    return points
Example #13
0
   def read(self,filename):
      observation=[]
      MPC = open(filename, "r")
      n = 0
      for ast in MPC.readlines():
	if len(ast)!=81 and len(ast)!=82 :
		print "FAIL",len(ast)
		continue
	print ast[:-1]
        n += 1
        MPnumber=ast[0:5]
	Provisional=ast[5:12]
	Discovery=ast[12]
        Note1=ast[13]
        Note2=ast[14]
	Date=ast[15:32]
	RA=ast[32:44]
	DEC=ast[44:56]
	Mag=float(ast[65:70])
	Band=ast[70]
	Observatory=ast[77:80]

	obs=[MPnumber,Provisional,Discovery,Note1,Note2,Date,RA,DEC,Mag,Band,Observatory]

	observation.append(obs)
      print("\n Numero de observaciones:",n)

      self.observations.extend(observation)
Example #14
0
    def contour(self, data):
        """
        Overlay a contour-plot

        @param data: 2darray with the 2theta values in radians...
        """
        if self.fig is None:
            logging.warning("No diffraction image available => not showing the contour")
        else:
            while len(self.msp.images) > 1:
                self.msp.images.pop()
            while len(self.ct.images) > 1:
                self.ct.images.pop()
            while len(self.ct.collections) > 0:
                self.ct.collections.pop()

            if self.points.dSpacing and  self.points._wavelength:
                angles = list(2.0 * numpy.arcsin(5e9 * self.points._wavelength / numpy.array(self.points.dSpacing)))
            else:
                angles = None
            try:
                xlim, ylim = self.ax.get_xlim(), self.ax.get_ylim()
                self.ct.contour(data, levels=angles)
                self.ax.set_xlim(xlim);self.ax.set_ylim(ylim);
                print("Visually check that the curve overlays with the Debye-Sherrer rings of the image")
                print("Check also for correct indexing of rings")
            except MemoryError:
                logging.error("Sorry but your computer does NOT have enough memory to display the 2-theta contour plot")
            self.fig.show()
Example #15
0
def test():
    #hushen_score=-5
    #chye_score=-5
    for hushen_score in range(-5,6):
        for chye_score in range(-5,6):
            print('hushen_score=',hushen_score,'chye_score=',chye_score)
            position,sys_score,is_sys_risk=sys_risk_analyse(max_position=0.85,ultimate_coefficient=0.25,shzh_score=hushen_score,chy_score=chye_score)  
Example #16
0
 def _wait_read(self):
     assert self.__readable.ready(), "Only one greenlet can be waiting on this event"
     self.__readable = AsyncResult()
     # timeout is because libzmq cannot always be trusted to play nice with libevent.
     # I can only confirm that this actually happens for send, but lets be symmetrical
     # with our dirty hacks.
     # this is effectively a maximum poll interval of 1s
     tic = time.time()
     dt = self._gevent_bug_timeout
     if dt:
         timeout = gevent.Timeout(seconds=dt)
     else:
         timeout = None
     try:
         if timeout:
             timeout.start()
         self.__readable.get(block=True)
     except gevent.Timeout as t:
         if t is not timeout:
             raise
         toc = time.time()
         # gevent bug: get can raise timeout even on clean return
         # don't display zmq bug warning for gevent bug (this is getting ridiculous)
         if self._debug_gevent and timeout and toc-tic > dt and \
                 self.getsockopt(zmq.EVENTS) & zmq.POLLIN:
             print("BUG: gevent may have missed a libzmq recv event on %i!" % self.FD, file=sys.stderr)
     finally:
         if timeout:
             timeout.cancel()
         self.__readable.set()
Example #17
0
    def execute(self, context):
        # bpy.ops.object.duplicate()実行後に複製オブジェクトが選択されるため、選択中のオブジェクトを保存
        src_obj_name = context.active_object.name
        bpy.ops.object.duplicate()
        active_obj = context.active_object

        # 複製したオブジェクトを配置位置に移動
        if self.location == '3D_CURSOR':
            # Shallow copyを避けるため、copy()によるDeep copyを実行
            active_obj.location = context.scene.cursor_location.copy()
        elif self.location == 'ORIGIN':
            active_obj.location = Vector((0.0, 0.0, 0.0))
        elif self.location[0:4] == 'OBJ_':
            objs = bpy.data.objects
            active_obj.location = objs[self.location[4:]].location.copy()

        # 複製したオブジェクトの拡大率を設定
        active_obj.scale.x = active_obj.scale.x * self.scale[0]
        active_obj.scale.y = active_obj.scale.y * self.scale[1]
        active_obj.scale.z = active_obj.scale.z * self.scale[2]

        # 複製したオブジェクトの回転角度を設定
        rot_euler = active_obj.rotation_euler
        active_obj.rotation_euler.x = rot_euler.x + self.rotation[0]
        active_obj.rotation_euler.y = rot_euler.y + self.rotation[1]
        active_obj.rotation_euler.z = rot_euler.z + self.rotation[2]

        # 複製したオブジェクトの最終位置を設定
        active_obj.location = active_obj.location + Vector(self.offset)

        self.report({'INFO'}, "サンプル2-6: 「%s」を複製しました。" % (src_obj_name))
        print("サンプル2-6: オペレーション「%s」が実行されました。" % (self.bl_idname))

        return {'FINISHED'}
Example #18
0
def main():
	s = list(raw_input().strip())
	s.sort()
	while True:
		print(''.join(s))
		if not next_permutation(s):
			break
Example #19
0
 def _wait_write(self):
     assert self.__writable.ready(), "Only one greenlet can be waiting on this event"
     self.__writable = AsyncResult()
     # timeout is because libzmq cannot be trusted to properly signal a new send event:
     # this is effectively a maximum poll interval of 1s
     tic = time.time()
     dt = self._gevent_bug_timeout
     if dt:
         timeout = gevent.Timeout(seconds=dt)
     else:
         timeout = None
     try:
         if timeout:
             timeout.start()
         self.__writable.get(block=True)
     except gevent.Timeout as t:
         if t is not timeout:
             raise
         toc = time.time()
         # gevent bug: get can raise timeout even on clean return
         # don't display zmq bug warning for gevent bug (this is getting ridiculous)
         if self._debug_gevent and timeout and toc-tic > dt and \
                 self.getsockopt(zmq.EVENTS) & zmq.POLLOUT:
             print("BUG: gevent may have missed a libzmq send event on %i!" % self.FD, file=sys.stderr)
     finally:
         if timeout:
             timeout.cancel()
         self.__writable.set()
Example #20
0
def parts_prompt():
    print('These are the assignment parts that you can submit:')

    for i, name in enumerate(part_friendly_names):
        print('  %d) %s' % (i+1, name))

    return input('\nWhich parts do you want to submit? (Ex: 1, 4-7): ')
 def validation_engine(self, input_list):
     validations = Game.answer_validator(self, input_list)
     for validation in validations:
         validation(input_list)
     print("Hit: {0}, Blow: {1}".format(self.hit, self.blow))
     self.hit = 0
     self.blow = 0
Example #22
0
 def get_experimentIDAndLineageNameAndSampleNameAndTimePoint_analysisID_dataStage01ResequencingAnalysis(self,analysis_id_I):
     '''Query rows that are used from the analysis'''
     try:
         data = self.session.query(data_stage01_resequencing_analysis.experiment_id,
                 data_stage01_resequencing_analysis.lineage_name,
                 data_stage01_resequencing_analysis.sample_name,
                 data_stage01_resequencing_analysis.time_point).filter(
                 data_stage01_resequencing_analysis.analysis_id.like(analysis_id_I),
                 data_stage01_resequencing_analysis.used_.is_(True)).group_by(
                 data_stage01_resequencing_analysis.experiment_id,
                 data_stage01_resequencing_analysis.lineage_name,
                 data_stage01_resequencing_analysis.sample_name,
                 data_stage01_resequencing_analysis.time_point).order_by(
                 data_stage01_resequencing_analysis.experiment_id.asc(),
                 data_stage01_resequencing_analysis.lineage_name.asc(),
                 data_stage01_resequencing_analysis.sample_name.asc(),
                 data_stage01_resequencing_analysis.time_point.asc()).all();
         experiment_id_O = []
         lineage_name_O = []
         sample_name_O = []
         time_point_O = []
         if data: 
             for d in data:
                 experiment_id_O.append(d.experiment_id);
                 lineage_name_O.append(d.lineage_name); 
                 sample_name_O.append(d.sample_name);    
                 time_point_O.append(d.time_point);              
         return  experiment_id_O,lineage_name_O,sample_name_O,time_point_O;
     except SQLAlchemyError as e:
         print(e);
Example #23
0
 def get_row_experimentIDAndSampleName_dataStage01ResequencingEndpoints(self,experiment_id_I,sample_name_I):
     '''Query samples names from resequencing endpoints'''
     try:
         data = self.session.query(data_stage01_resequencing_endpoints).filter(
                 data_stage01_resequencing_endpoints.experiment_id.like(experiment_id_I),
                 data_stage01_resequencing_endpoints.sample_name.like(sample_name_I)).all();
         data_O = [];
         for d in data: 
             data_tmp = {};
             data_tmp['id']=d.id;
             data_tmp['experiment_id']=d.experiment_id;
             data_tmp['analysis_id']=d.analysis_id;
             data_tmp['sample_name']=d.sample_name;
             data_tmp['mutation_frequency']=d.mutation_frequency;
             data_tmp['mutation_type']=d.mutation_type;
             data_tmp['mutation_position']=d.mutation_position;
             data_tmp['mutation_data']=d.mutation_data;
             data_tmp['isUnique']=d.isUnique;
             data_tmp['mutation_annotations']=d.mutation_annotations;
             data_tmp['mutation_genes']=d.mutation_genes;
             data_tmp['mutation_locations']=d.mutation_locations;
             data_tmp['mutation_links']=d.mutation_links;
             data_tmp['comment_']=d.comment_;
             data_O.append(data_tmp);
         return data_O;
     except SQLAlchemyError as e:
         print(e);
Example #24
0
def pull_content_length(image_url):
    print(image_url)
    try:
        fileSize = urllib2.urlopen(image_url, timeout=2)
        return int(fileSize.headers.get("content-length"))
    except Exception, exc:
        raise pull_content_length.retry(exc=exc)
Example #25
0
 def get_mutations_experimentIDAndSampleName_dataStage01ResequencingMutations(self,experiment_id_I,sample_name_I,
           frequency_criteria=0.1):
     '''Query mutation data
     NOTES:
     1. JSON is not a standard type across databases, therefore the key/values of the JSON
         object will be filtered post-query'''
     #1 filter sample_names that do not meet the frequency criteria
     try:
         data = self.session.query(data_stage01_resequencing_mutations).filter(
                 data_stage01_resequencing_mutations.experiment_id.like(experiment_id_I),
                 data_stage01_resequencing_mutations.sample_name.like(sample_name_I)).all();
         data_O = [];
         for d in data: 
             data_dict = {};
             data_dict['experiment_id'] = d.experiment_id;
             data_dict['sample_name'] = d.sample_name;
             data_dict['mutation_id'] = d.mutation_id;
             data_dict['parent_ids'] = d.parent_ids;
             data_dict['mutation_data'] = d.mutation_data;
             #data_dict['mutation_data'] = json.loads(d.mutation_data);
             data_O.append(data_dict);
         # filter:
         data_filtered = [];
         for d in data_O:
             if 'frequency' in d['mutation_data'] and d['mutation_data']['frequency'] >= frequency_criteria:
                 data_filtered.append(d);
             #note: frequency is only provided for population resequences
             elif 'frequency' not in d['mutation_data']:
                 data_filtered.append(d);
         return data_filtered;
     except SQLAlchemyError as e:
         print(e);
Example #26
0
 def _act_on_pillows(self, action):
     # Used to stop or start pillows
     service = Pillowtop(self.environment, AnsibleContext(None))
     exit_code = service.run(action=action)
     if not exit_code == 0:
         print("ERROR while trying to {} pillows. Exiting.".format(action))
         sys.exit(1)
Example #27
0
    def __getDuplicates(self, songLibrary):
        progress = 0
        log.info("%s files to process" % self.nb_songs)
        while songLibrary:
            # Remove processed song
            song = songLibrary.pop(0)

            song_name = song.name
            song_folder = song.folder
            artist = song.artist
            song_size = song.size
            cleaned_song_name = re.sub("^[\d]{2}", '', song_name)
            song_path = ('/').join(song.path)

            for index, song__toCompare in enumerate([x for x in songLibrary if x.artist == artist]):

                song_name_to_compare = song__toCompare.name
                song_folder_to_compare = song__toCompare.folder
                song_size_to_compare = song__toCompare.size
                song_path_to_compare = ('/').join(song__toCompare.path)

                if song_name_to_compare.find(cleaned_song_name) != -1:
                    dup = Duplicates()
                    dup.artist = artist
                    dup.songs = [song_name, song_name_to_compare]
                    dup.sizes = [song_size, song_size_to_compare]
                    dup.folders = [song_folder, song_folder_to_compare]
                    dup.paths = [song_path, song_path_to_compare]

                    self.duplicates.append(dup)
                    self.nb_duplicates += 1

            progress += 1  # songs processed so far. to be used as a counter

        print('%s duplicates found' % self.nb_duplicates + '\n')
Example #28
0
 def get_analysis_analysisID_dataStage01ResequencingAnalysis(self,analysis_id_I):
     '''Query rows that are used from the analysis'''
     try:
         data = self.session.query(data_stage01_resequencing_analysis).filter(
                 data_stage01_resequencing_analysis.analysis_id.like(analysis_id_I),
                 data_stage01_resequencing_analysis.used_.is_(True)).all();
         analysis_id_O = []
         experiment_id_O = []
         lineage_name_O = []
         sample_name_O = []
         analysis_type_O = []
         analysis_O = {};
         if data: 
             for d in data:
                 analysis_id_O.append(d.analysis_id);
                 experiment_id_O.append(d.experiment_id);
                 lineage_name_O.append(d.lineage_name);
                 sample_name_O.append(d.sample_name);
                 analysis_type_O.append(d.analysis_type);
             analysis_id_O = list(set(analysis_id_O))
             experiment_id_O = list(set(experiment_id_O))
             lineage_name_O = list(set(lineage_name_O))
             sample_name_O = list(set(sample_name_O))
             analysis_type_O = list(set(analysis_type_O))
             analysis_O={
                     'analysis_id':analysis_id_O,
                     'experiment_id':experiment_id_O,
                     'lineage_name':lineage_name_O,
                     'sample_name':sample_name_O,
                     'analysis_type':analysis_type_O};
             
         return analysis_O;
     except SQLAlchemyError as e:
         print(e);
Example #29
0
    def new_func():

        starttime = datetime.now()

        func()

        print("exectime: ", datetime.now() - starttime)
Example #30
0
 def get_rows_analysisID_dataStage01ResequencingHeatmap(self,analysis_id_I):
     '''Query rows from data_stage01_resequencing_heatmap'''
     try:
         data = self.session.query(data_stage01_resequencing_heatmap).filter(
                 data_stage01_resequencing_heatmap.analysis_id.like(analysis_id_I),
                 data_stage01_resequencing_heatmap.used_).all();
         data_O = [];
         for d in data: 
             data_dict = {'analysis_id':d.analysis_id,
                 'col_index':d.col_index,
                 'row_index':d.row_index,
                 'value':d.value,
                 'col_leaves':d.col_leaves,
                 'row_leaves':d.row_leaves,
                 'col_label':d.col_label,
                 'row_label':d.row_label,
                 'col_pdist_metric':d.col_pdist_metric,
                 'row_pdist_metric':d.row_pdist_metric,
                 'col_linkage_method':d.col_linkage_method,
                 'row_linkage_method':d.row_linkage_method,
                 'value_units':d.value_units,
                 'used_':d.used_,
                 'comment_':d.comment_};
             data_O.append(data_dict);
         return data_O;
     except SQLAlchemyError as e:
         print(e);
Example #31
0
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

for number in the_count:
    print(f"This is count {number}")
# same as above
for fruit in fruits:
    print(f"A fruit of type: {fruit}")

# also we can go through mixed lists too
for i in change:
    print(f"I got {i}")

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)

# now we can print them out too
for i in elements:
    print(f"Element was: {i}")
Example #32
0
 def getEvent(self):
     #1.获取所有事件
     eventList = pygame.event.get()
     #2.对事件进行判断处理(1、点击关闭按钮  2、按下键盘上的某个按键)
     for event in eventList:
         #判断event.type 是否QUIT,如果是退出的话,直接调用程序结束方法
         if event.type == pygame.QUIT:
             self.endGame()
         #判断事件类型是否为按键按下,如果是,继续判断按键是哪一个按键,来进行对应的处理
         if event.type == pygame.KEYDOWN:
             #点击ESC按键让我方坦克重生
             if event.key == pygame.K_ESCAPE and not MainGame.TANK_P1:
                 #调用创建我方坦克的方法
                 self.creatMyTank()
             if MainGame.TANK_P1 and MainGame.TANK_P1.live:
                 # 具体是哪一个按键的处理
                 if event.key == pygame.K_LEFT:
                     print("坦克向左调头,移动")
                     # 修改坦克方向
                     MainGame.TANK_P1.direction = 'L'
                     MainGame.TANK_P1.stop = False
                 elif event.key == pygame.K_RIGHT:
                     print("坦克向右调头,移动")
                     # 修改坦克方向
                     MainGame.TANK_P1.direction = 'R'
                     MainGame.TANK_P1.stop = False
                 elif event.key == pygame.K_UP:
                     print("坦克向上调头,移动")
                     # 修改坦克方向
                     MainGame.TANK_P1.direction = 'U'
                     MainGame.TANK_P1.stop = False
                 elif event.key == pygame.K_DOWN:
                     print("坦克向下掉头,移动")
                     # 修改坦克方向
                     MainGame.TANK_P1.direction = 'D'
                     MainGame.TANK_P1.stop = False
                 elif event.key == pygame.K_SPACE:
                     print("发射子弹")
                     if len(MainGame.Bullet_list) < 3:
                         # 产生一颗子弹
                         m = Bullet(MainGame.TANK_P1)
                         # 将子弹加入到子弹列表
                         MainGame.Bullet_list.append(m)
                         music = Music('img/fire.wav')
                         music.play()
                     else:
                         print("子弹数量不足")
                     print("当前屏幕中的子弹数量为:%d" % len(MainGame.Bullet_list))
         #结束游戏方法
         if event.type == pygame.KEYUP:
             #松开的如果是方向键,才更改移动开关状态
             if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                 if MainGame.TANK_P1 and MainGame.TANK_P1.live:
                     # 修改坦克的移动状态
                     MainGame.TANK_P1.stop = True
				if y == ")" :
					Bangalore_area_code.add(number[1][:x+1])


		elif " " in number[1]:
			Bangalore_area_code.add(number[1][:4])

		elif number[1][:3] == "140" :
			Bangalore_area_code.add("140")

sorted_list = sorted(list(Bangalore_area_code))


''' Let's print the codes now'''

print("The numbers called by people in Bangalore have codes:")
for sort_code in sorted_list:
	print(sort_code)

# Solution for Part B

calls_in_bangalore = 0
calls_from_bang_to_elsehere = 0

for number in calls:
	if number[0][:5] == "(080)" :
		if number[1][:5] == "(080)" :
			calls_in_bangalore += 1
			calls_from_bang_to_elsehere += 1

		else:
Example #34
0
from subprocess import Popen

p_list = []
max_clients = 3

while True:
    user = input(
        '(s) Start {} clients\n(t) Send message to server\n(x) Terminate clients\n(q) Quit\n'
        .format(max_clients))
    if user.lower() == 'q':
        break
    elif user.lower() == 's':
        for _ in range(max_clients):
            p_list.append(
                Popen(
                    'exec /usr/bin/python3 client.py --username=JohnDoe --secret=123 --message msg -r',
                    shell=True))
        print('Started {} clients'.format(max_clients))
    elif user.lower() == 't':
        msg = input('Message to chat: ')
        Popen(
            'exec python3 client.py --username=JohnDoe --secret=123 --message "{}" -w'
            .format(msg),
            shell=True)
    elif user.lower() == 'x':
        for p in p_list:
            p.kill()
        p_list.clear()
        print('Clients terminated')
Example #35
0
print(SynthDefs)

Clock.bpm = 120

var.off = var([3, 5, 6], dur=8)

p1 >> keys(P[0:16:4].shuffle().offadd(var.off), scale=Scale.minor)

# doesn't work as expected
# var.bass = var(p1.pitch[1], dur=4)
# p2 >> bass(var.bass, dur=[2,1,1/2,1], oct=4)

p2 >> bass(p1.pitch[1], dur=4, oct=3)

d1 >> play("x[x ]x[x x]x[[x ] ]x[  x]")

d4 >> play("  o  o [oo]")

d2 >> play("s s( s)")

d3 >> play("--------")

d5 >> play("(T ) ")

# d5 >> play("1! !1 1!")

# d5 >> play("$$ $ $ ( !)")

print(Samples)
Example #36
0
    parser = argparse.ArgumentParser(description='spikes')
    parser.add_argument('--S', default=[], type=str, help='spiking matrix')
    parser.add_argument('--ops', default=[], type=str, help='options file')
    parser.add_argument('--iscell', default=[], type=str, help='which cells to use')
    args = parser.parse_args()

    if len(args.S)>0:
        S = np.load(args.S)
        ops = np.load(args.ops)
        ops = ops.item()
        if len(args.iscell) > 0:
            iscell = np.load(args.iscell)
            if iscell.ndim > 1:
                iscell = iscell[:, 0].astype(np.bool)
            else:
                iscell = iscell.astype(np.bool)
            if iscell.size == S.shape[0]:
                S = S[iscell, :]
                print('iscell found and used to select neurons')
        print(S.shape)
        S = zscore(S,axis=1)
        model = Rastermap(ops['n_components'], ops['n_X'], ops['n_Y'], ops['nPC'],
                          ops['sig_Y'], ops['init'], ops['alpha'], ops['K'])
        model.fit(S)
        proc  = {'embedding': model.embedding, 'usv': [model.u, model.sv, model.v],
                 'cmap': model.cmap, 'A': model.A, 'ops': ops, 'filename': args.S}
        basename, fname = os.path.split(args.S)
        np.save(os.path.join(basename, 'embedding.npy'), proc)
    else:
        gui.run()
vote_count = int(input())
votes = input()
a, b = 0, 0
for vote in votes:
  if vote == "A": a += 1
  if vote == "B": b += 1
if a > b: print("A")
elif a < b: print("B")
else: print("Tie")
Example #38
0
from twostring import ValueComparsions

if __name__ == '__main__':
    try:
        str1 = input('Enter a string Number 1\n')
        str2 = input('Enter a string Number 2 \n')
        result = ValueComparsions(str1, str2)
        if str1 == str2:
            print(result.equal())
            print(
                '{0} and {1} are not greater or \nlesser to each other'.format(
                    str1, str2))
        else:
            print(result.greater())
            print(result.equal())
            print(result.lesser())

    except ValueError:
        print('\n')
        print('_' * 42)
        print('Characters, strings are not allowed\n'
              "Please Enter only numbers \n{0}".format('_' * 42))
Example #39
0
def fibonacci_series(number):
    if number == 0:
        return 0
    if number == 1:
        return 1
    else:
        return fibonacci_series(number - 2) + fibonacci_series(number - 1)


num = int(input("Enter a number:"))

for i in range(0, num):
    print(fibonacci_series(i), end=" ")
Example #40
0
    for i in range(0x21, 0x7f):
        w = chr(i)
        flag[x] = w

        tmp = f"""
#!/usr/bin/rarun2
program=./vtr-alternate
stdin="{''.join(flag)}"
stdout=
        """

        with open('vtr-alternate.rr2', 'w') as f:
            f.write(tmp)
        f.close()

        r2.cmd('doo')
        r2.cmd('dc')

        r8 = r2.cmdj('drj')['r8']
        r8a = r8 - 160

        if r2.cmdj(f'pxwj @{r8}')[x] == r2.cmdj(f'pxwj @{r8a}')[x]:
            x += 1
            print(''.join(flag))
            break

print(''.join(flag))

# rarctf{See,ThatWasn'tSoHard-1eb519ed}
Example #41
0
                changed = True
                newRow[col] = True

        nested[row - 1] = prev
        prev = newRow[:]

    nested[-2] = prev

    return changed


if __name__ == "__main__":
    seats = [
        ([None] +
         [True if x == "#" else (False if x == "L" else None)
          for x in row] + [None])
        for row in open("input.txt").read().strip().split("\n")
    ]

    seats.insert(0, [None for x in seats[0]])
    seats.append([None for x in seats[0]])

    cont = True
    while cont:
        cont = iterate(seats)

    for row in range(len(seats)):
        for col in range(len(seats[row])):
            seats[row][col] = 0 if seats[row][col] == None else seats[row][col]
    print(sum([sum(row) for row in seats]))
Example #42
0
#coding:utf-8
a = 5
while (a > 0):
    print(a)
    a = a - 1

while (a == 0):
    a = a + 5
    print(a)

if (a < 10):
    print(a - 3)
elif a > 5:
    print a
else:
    print('厉害至极')
print '结束了啊'
Example #43
0
# -*- coding: utf-8 -*-
import base64, struct
bmp_data = base64.b64decode('Qk1oAgAAAAAAADYAAAAoAAAAHAAAAAoAAAABABAAAAAAADICAAASCwAAEgsAAAAAAAAAAAAA/3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9/AHwAfAB8AHwAfAB8AHwAfP9//3//fwB8AHwAfAB8/3//f/9/AHwAfAB8AHz/f/9//3//f/9//38AfAB8AHwAfAB8AHwAfAB8AHz/f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9//3//f/9/AHwAfP9//3//f/9//3//f/9//38AfAB8AHwAfAB8AHwAfP9//3//f/9/AHwAfP9//3//f/9//38AfAB8/3//f/9//3//f/9//3//fwB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8/3//f/9//3//fwB8AHz/f/9//3//f/9//3//f/9/AHwAfP9//3//f/9/AHwAfP9//3//fwB8AHz/f/9/AHz/f/9/AHwAfP9//38AfP9//3//f/9/AHwAfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfP9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9//38AfAB8AHwAfAB8AHwAfAB8/3//f/9/AHwAfAB8AHz/fwB8AHwAfAB8AHwAfAB8AHz/f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//3//f/9//38AAA==')
def bmp_info(data):
    templist = struct.unpack('<ccIIIIIIHH', data[:30])
    if templist[:2] == b'BM':
        return {
            'width': templist[-4],
            'height': templist[-3],
            'color': templist[-1]
        }
    else:
        return None

# 测试
bi = bmp_info(bmp_data)
assert bi['width'] == 28
assert bi['height'] == 10
assert bi['color'] == 16
print('ok')
def main():
    print(count_rotations([10, 15, 1, 3, 8]))
    print(count_rotations([4, 5, 7, 9, 10, -1, 2]))
    print(count_rotations([1, 3, 8, 10]))
Example #45
0
def main():
    parser = argparse.ArgumentParser(description='Train script')
    parser.add_argument('--batchsize', type=int, default=64)
    parser.add_argument('--max_iter', type=int, default=100000)
    parser.add_argument('--gpu', '-g', type=int, default=0, help='GPU ID (negative value indicates CPU)')
    parser.add_argument('--out', '-o', default='result', help='Directory to output the result')
    parser.add_argument('--snapshot_interval', type=int, default=10000, help='Interval of snapshot')
    parser.add_argument('--evaluation_interval', type=int, default=10000, help='Interval of evaluation')
    parser.add_argument('--display_interval', type=int, default=100, help='Interval of displaying log to console')
    parser.add_argument('--n_dis', type=int, default=1, help='number of discriminator update per generator update') # 5
    parser.add_argument('--gamma', type=float, default=0.5, help='hyperparameter gamma')
    parser.add_argument('--lam', type=float, default=10, help='gradient penalty')
    parser.add_argument('--adam_alpha', type=float, default=0.0002, help='alpha in Adam optimizer')
    parser.add_argument('--adam_beta1', type=float, default=0.5, help='beta1 in Adam optimizer') # 0.0
    parser.add_argument('--adam_beta2', type=float, default=0.9, help='beta2 in Adam optimizer') # 0.9
    parser.add_argument('--output_dim', type=int, default=256, help='output dimension of the discriminator (for cramer GAN)')
    parser.add_argument('--data-dir', type=str, default="")
    parser.add_argument('--image-npz', type=str, default="")
    parser.add_argument('--n-hidden', type=int, default=128)
    parser.add_argument('--resume', type=str, default="")
    parser.add_argument('--ch', type=int, default=512)
    parser.add_argument('--snapshot-iter', type=int, default=0)

    args = parser.parse_args()
    record_setting(args.out)
    report_keys = ["loss_dis", "loss_gen"]

    # Set up dataset
    if args.image_npz != '':
        from c128dcgan.dataset import NPZColorDataset
        train_dataset = NPZColorDataset(npz=args.image_npz)
    elif args.data_dir != '':
        from c128dcgan.dataset import Color128x128Dataset
        train_dataset = Color128x128Dataset(args.data_dir)
    train_iter = chainer.iterators.SerialIterator(train_dataset, args.batchsize)

    # Setup algorithm specific networks and updaters
    models = []
    opts = {}
    updater_args = {
        "iterator": {'main': train_iter},
        "device": args.gpu
    }

    # fixed algorithm
    #from c128gan import Updater
    generator = common.net.C128Generator(ch=args.ch, n_hidden=args.n_hidden)
    discriminator = common.net.SND128Discriminator(ch=args.ch)
    models = [generator, discriminator]
    from dcgan.updater import Updater

    if args.gpu >= 0:
        chainer.cuda.get_device_from_id(args.gpu).use()
        print("use gpu {}".format(args.gpu))
        for m in models:
            m.to_gpu()

    # Set up optimizers
    opts["opt_gen"] = make_optimizer(generator, args.adam_alpha, args.adam_beta1, args.adam_beta2)
    opts["opt_dis"] = make_optimizer(discriminator, args.adam_alpha, args.adam_beta1, args.adam_beta2)

    updater_args["optimizer"] = opts
    updater_args["models"] = models

    # Set up updater and trainer
    updater = Updater(**updater_args)
    trainer = training.Trainer(updater, (args.max_iter, 'iteration'), out=args.out)

    # Set up logging
    for m in models:
        trainer.extend(extensions.snapshot_object(
            m, m.__class__.__name__ + '_{.updater.iteration}.npz'), trigger=(args.snapshot_interval, 'iteration'))
    trainer.extend(extensions.LogReport(keys=report_keys,
                                        trigger=(args.display_interval, 'iteration')))
    trainer.extend(extensions.PrintReport(report_keys), trigger=(args.display_interval, 'iteration'))
    trainer.extend(sample_generate(generator, args.out), trigger=(args.evaluation_interval, 'iteration'),
                   priority=extension.PRIORITY_WRITER)
    trainer.extend(sample_generate_light(generator, args.out), trigger=(args.evaluation_interval // 10, 'iteration'),
                   priority=extension.PRIORITY_WRITER)
    trainer.extend(extensions.ProgressBar(update_interval=10))
    if args.snapshot_iter == 0:
        snap_iter= args.max_iter // 100
    else:
        snap_iter = args.snapshot_iter
    trainer.extend(extensions.snapshot(), trigger=(snap_iter , 'iteration'))

    # resume
    if args.resume != "":
        chainer.serializers.load_npz(args.resume, trainer)

    # Run the training
    trainer.run()
Example #46
0
def main():
    """Invoke unit test code."""
    print('TestMaxMunchGen.py script version "%s", dated %s' % (__version__, __date__))
    print('Author: %s' % __author__)
    print(__rights__)
    print()
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hl:", ["help",])
    except getopt.GetoptError:
        usage()
        print('ERROR: Invalid options!')
        sys.exit(1)
    logLevel = logging.INFO
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(2)
        elif o == '-l':
            logLevel = int(a)
    if len(args) != 0:
        usage()
        print('ERROR: Wrong number of arguments!')
        sys.exit(1)
    # Initialise logging etc.
    logging.basicConfig(level=logLevel,
                    format='%(asctime)s %(levelname)-8s %(message)s',
                    #datefmt='%y-%m-%d % %H:%M:%S',
                    stream=sys.stdout)
    clkStart = time.clock()
    unitTest()
    clkExec = time.clock() - clkStart
    print('CPU time = %8.3f (S)' % clkExec)
    print('Bye, bye!')
def api_filter():  # lets the end-user filter by id, published, and author.
    query_parameters = request.args  # defining the query parameters:
    # print('these are the request.args')
    # print(query_parameters)

    id = query_parameters.get(
        'id')  # chains the supported queries to the appropriate variable.
    print('id:', id)
    published = query_parameters.get(
        'published'
    )  # chains the supported queries to the appropriate variable.
    print('published:', published)
    author = query_parameters.get(
        'author')  # chains the supported queries to the appropriate variable.
    print('author:', author)

    query = "SELECT * FROM books WHERE"  # the function translates Python code into a format SQL can understand.
    to_filter = []
    print('to_filter before: ', to_filter)

    if id:
        query += ' id=? AND'
        to_filter.append(id)
    if published:
        query += ' published=? AND'
        to_filter.append(published)
    if author:
        query += ' author=? AND'
        to_filter.append(author)
    if not (
            id or published or author
    ):  # If the user hasn’t used any of these queries, they’ll be redirected to a 404 page.
        return page_not_found(404)

    print('to_filter after: ', to_filter)
    print("query before:", query)
    query = query[:-4] + ';'
    print("query after:", query)

    # Then the results are paired with appropriate variables, same as before.
    conn = sqlite3.connect('books.db')
    conn.row_factory = dict_factory
    cur = conn.cursor()

    results = cur.execute(query, to_filter).fetchall()

    return jsonify(
        results)  # Finally, those results are returned in JSON format
Example #48
0
import requests

res = requests.get(
    "https://docs.python.org/3.5/")  # функция get реализует http get запрос
print(res.status_code)
print(res.headers['Content-Type'])  # проверяем тип содержимого
# 200
# text/html
print(res.content
      )  # b'\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n
#  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n<html xmlns="http://www.w3.org/1999/xhtml">\n
#  <head>\n    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />\n    <meta http-equiv="Content-Type"
#  content="text/html; charset=utf-8" /><title>3.5.10 Documentation</title>\n    <link rel="stylesheet"
#  href="_static/pydoctheme.css" type="text/css" />\n    <link rel="stylesheet" href="_static/pygments.css"
#  type="text/css" />\n    \n    <script type="text/javascript" id="documentation_options" data-url_root="./"
#  src="_static/documentation_options.js"></script>\n    <script type="text/javascript"
#  src="_static/jquery.js"></script>\n    <script type="text/javascript" src="_static/underscore.js"></script>\n
#  <script type="text/javascript" src="_static/doctools.js"></script>\n    <script async="async" type="text/javascript"
#  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>\n    \n
#  <script type="text/javascript" src="_static/sidebar.js"></script>\n    \n
#  <link rel="search" type="application/opensearchdescription+xml"\n
#  title="Search within Python 3.5.10 documentation"\n          href="_static/opensearch.xml"/>\n
#  <link rel="author" title="About these documents" href="about.html" />\n
#  <link rel="index" title="Index" href="genindex.html" />\n
#  <link rel="search" title="Search" href="search.html" />\n
#  <link rel="copyright" title="Copyright" href="copyright.html" />\n
#  <link rel="shortcut icon" type="image/png" href="_static/py.png" />\n
#  <link rel="canonical" href="https://docs.python.org/3/index.html" />\n    \n
#  <script type="text/javascript" src="_static/copybutton.js"></script>\n    \n    \n    \n \n\n  </head><body>\n  \n
#  <div class="related" role="navigation" aria-label="related navigation">\n      <h3>Navigation</h3>\n      <ul>\n
#  <li class="right" style="margin-right: 10px">\n          <a href="genindex.html" title="General Index"\n
print("Welcome to the Python Guessing Game! You have 3 tries.")
guess = input("Please enter your answer: ")
answer = "shazbot"
no_of_tries = 2
attempts = 0

while guess != answer and attempts != no_of_tries:
    guess = input("Incorrcet. Please try again: ")
    attempts += 1

if guess == answer:
    print("You win!")
else:
    print("You lose!")
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn import svm


iris = datasets.load_iris()

X = iris.data
y = iris.target

classes = ["Iris Setosa", "Iris Versicolour", "Iris Virginica"]

X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)

model = svm.SVC()

model.fit(X_train, y_train)

prediction = model.predict(X_test)
acc = accuracy_score(y_test, prediction)
print("Acctual:    ", y_test)
print("Prediction: ", prediction)
print("Accuracy: ", acc)
Example #51
0
                    continue
                else:
                    water -= level
                    fire_put_out += level
                    effort += 0.25 * level
                    cells_put_out.append(level)
            else:
                counter += 1
        elif fire_type == 'Low':
            if 1 <= level <= 50:
                counter += 1
                if water - level < 0:
                    continue
                else:
                    water -= level
                    fire_put_out += level
                    effort += 0.25 * level
                    cells_put_out.append(level)
            else:
                counter += 1
        else:
            continue
        if counter == 2:
            break
    for n in range(2):
        value_type_fire_final.pop(0)
print('Cells:')
for x in cells_put_out:
    print(f'- {x}')
print(f'Effort: {effort:.2f}')
print(f'Total Fire: {fire_put_out}')
Example #52
0
"""
Задание 5 (№1804).
На вход алгоритма подаётся натуральное число N. Алгоритм строит по нему новое число R следующим образом.
1) Строится двоичная запись числа 2N.
2) К этой записи дописываются справа ещё два разряда по следующему правилу:
а) складываются все цифры двоичной записи числа N, и остаток от деления суммы на 2 дописывается в конец числа (справа).
Например, запись 10000 преобразуется в запись 100001;
б) над этой записью производятся те же действия – справа дописывается остаток от деления суммы её цифр на 2.

Полученная таким образом запись (в ней на два разряда больше, чем в записи исходного числа N)
является двоичной записью искомого числа R. Укажите такое наименьшее число N,
для которого результат работы данного алгоритма больше числа 249.
"""
for n in range(2, 512):
    binary = bin(2 * n)[2:]
    b = bin(n)[2:]
    s = b.count('1')
    binary += str(s % 2)
    s = binary.count('1')
    binary += str(s % 2)
    if int(binary, 2) > 249:
        print(n)
        break
Example #53
0
x= 50
def func():
    global x
    # print('x is:',x)
    x = 1000
    # print('local x changed to:',x)

# func(x)
func()
print(x)
Example #54
0
    seat_id = (row * 8 + col)

    return (row, col, seat_id)

def test():
    answers = [
        (70, 7, 567),
        (14, 7, 119),
        (102, 4, 820)
    ]

    boarding_passes = read_input('test_input.txt')
    seats = [get_seat(boarding_pass) for boarding_pass in boarding_passes]
    for i in range(3):
        assert seats[i] == answers[i]

def run():
    test()

    boarding_passes = read_input('input.txt')
    seats = [get_seat(boarding_pass) for boarding_pass in boarding_passes]
    print(max(seats)[2]) # part1

    seat_ids = sorted([seat[2] for seat in seats])
    
    for i in range(len(seat_ids) - 2):
        if seat_ids[i + 1] != seat_ids[i] + 1:
            return seat_ids[i] + 1

print(run())
Example #55
0
def OptionMenu_SelectionEvent(
        event):  # I'm not sure on the arguments here, it works though
    ## do something
    global robot_adres, socket, recive_flag, flag_inet_work, robot_adres_inet
    print(FgBlue, event)

    # if event == "none" or robot_adres != "-1":
    #     print("return")
    #     return

    if event[0] == "scan":
        ScanRobots(event)
        return

    if event[0] == "scan_inet":
        ip_adress_s = sc.gethostbyname(sc.gethostname())
        print(ip_adress_s)
        print("connect to server...")
        ic.connect()
        print("take list")
        list = ic.take_list()
        # print(list)
        # print(ic.take_list())
        # list_combobox_inet = []
        # list_combobox_inet.append(["scan_inet", " "])
        for r in list:
            print(r)
            if r[2] == "robot":
                list_combobox.append(r)
        if len(list) == 0:
            print("no robots in server list")

        dropVar = StringVar()
        dropVar.set(list_combobox_inet[0])

        combobox_inet = OptionMenu(panelFrame,
                                   dropVar,
                                   *(list_combobox),
                                   command=OptionMenu_SelectionEvent)
        combobox_inet.place(x=260, y=10, width=150,
                            height=40)  # Позиционируем Combobox на форме
        # print("end take")
        return

    if event[3] == "l":
        robot_adres = event[1]
        robot_adres_inet = event[0]
        # socket = context.socket(zmq.REP)
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://" + robot_adres + ":%s" % port)

        ip_adress = sc.gethostbyname(sc.gethostname())

        # s = socket.recv_string(zmq.NOBLOCK)

        print("Taking robot..", robot_adres)
        try:
            socket.send_string("take|" + ip_adress)
            print("Connected to robot: " + BgGreen + socket.recv_string() +
                  Reset)
        except:
            pass

        # recive_flag = 1
        flag_inet_work = False

    if event[3] == "i":
        robot_adres_inet = event[0]
        robot_adres = event[0]
        print(robot_adres_inet)
        flag_inet_work = True
        print("Connected to robot: " + BgGreen + event[1] + Reset)
        pass
    connect_keyboard(robot_adres)
    pass
Example #56
0
        :type nums: List[int]
        :rtype: int
        """
        # sum = nums[0]
        # lens = len(nums)
        # for i in range(1, lens+1):
        #     for j in range(lens - i + 1):
        #         sum_temp = 0
        #         for k in range(i):
        #             sum_temp += nums[j + k]
        #         if sum_temp > sum:
        #             sum = sum_temp
        # return sum
        lens = len(nums)
        sum = nums[0]
        maxnum = max(nums)
        for i in range(1, lens):
            if nums[i] < 0:
                sum += nums[i]
            else:
                if sum < 0:
                    sum = 0
                sum += nums[i]
                if maxnum < sum:
                    maxnum = sum
        return maxnum


s = Solution()
print(s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
Example #57
0
def send_event():
    global socket3, started_flag, ic_key, recive_flag, key_started, key_pressed, mouse_x, mouse_y
    context3 = zmq.Context()
    socket3 = context3.socket(zmq.REQ)
    ic_key = InetConnection.InetConnect(sc.gethostname() + "_key", "client")
    while 1:
        if key_started == -1:
            time.sleep(0.1)
            continue

        if key_started == 0:
            if flag_inet_work:
                ic_key.connect()
                # print("start key client")
            else:
                socket3.connect("tcp://" + robot_adres + ":5559")
            key_started = 1
            break

    while 1:
        data = ""
        if key_pressed != 0:
            data = key_pressed
            key_pressed = 0
        else:
            if mouse_x != -1 and mouse_y != -1:
                data = "m," + str(mouse_x) + "," + str(mouse_y)
                mouse_x = -1
                mouse_y = -1

        # if data!="":
        #     print(data, recive_flag)

        if data != "" and recive_flag == 1:
            if flag_inet_work == True:
                ic_key.send_key(robot_adres_inet, str(data))
            else:

                # socket3.send_string(str(data))
                # print("send",data)
                try:
                    socket3.send_string(str(data), zmq.NOBLOCK)  # zmq.NOBLOCK
                except:
                    pass

                message = ""
                count = 0
                while 1:
                    count += 1
                    try:
                        # print("s1")
                        # socket2.send_string("p", zmq.NOBLOCK)
                        message = socket3.recv_string(zmq.NOBLOCK)
                        # print("....ok")
                    except zmq.ZMQError as e:
                        pass
                    # print(message)
                    if message == "1":
                        break
                    time.sleep(0.01)
                    if count > 100:
                        print(BgRed + "reconnect key" + Reset)
                        socket3.close()
                        # context3 = zmq.Context()
                        socket3 = context3.socket(zmq.REQ)
                        socket3.connect("tcp://" + robot_adres + ":5559")
                        break

        time.sleep(0.01)
Example #58
0
def ScanRobots(ev):
    global panelFrame, socket, robot_adres, video_show

    ip_adress_s = sc.gethostbyname(sc.gethostname())
    print(ip_adress_s)
    ip_adress = ip_adress_s.split(".")
    ip_adress[0] = "192"
    ip_adress[1] = "168"
    ip_adress[2] = "88"
    if robot_adres != "-1":
        Stop(ev)
        print("drop robot")
        socket = context.socket(zmq.REQ)
        print(robot_adres)
        socket.connect("tcp://" + robot_adres + ":%s" % port)
        print("send", "tcp://" + robot_adres + ":%s" % port)
        try:
            socket.send_string("drop")
            print(socket.recv_string())
        except:
            pass

        robot_adres = "0"
        video_show = 0

    list_combobox = ["none"]
    dropVar = StringVar()
    dropVar.set(list_combobox[0])

    for i in range(20, 30):

        socket = context.socket(zmq.REQ)
        ip_adress_ping = str(ip_adress[0] + "." + ip_adress[1] + "." +
                             ip_adress[2] + "." + str(i))
        # socket.connect("tcp://"+ip_adress[0]+"."+ip_adress[1]+"."+ip_adress[2]+"."+str(i)+":%s" % port)
        socket.connect("tcp://" + ip_adress_ping + ":%s" % port)
        print("ping", ip_adress_ping)
        # print("send")
        try:
            socket.send_string("ping")
        except:
            pass
        time.sleep(0.7)

        s = ""
        try:
            # print("recv...")
            s = socket.recv_string(zmq.NOBLOCK)
            # print("....ok")
        except zmq.ZMQError as e:
            if e.errno == zmq.ETERM:
                return  # shutting down, quit
                print("no server")

        data = s.split("|")
        if len(data) > 1:
            s = data[0] + " " + data[1] + " " + str(ip_adress_ping) + "\n"
            if len(s) > 2:
                print(FgMagenta + s + Reset)

            if data[1] == ip_adress_s:
                dropVar.set(ip_adress_ping)
                robot_adres = ip_adress_ping
                socket = context.socket(zmq.REQ)
                socket.connect("tcp://" + robot_adres + ":%s" % port)
                # data[1] = "Connected"
                list_combobox.append(data[1])
                connect_keyboard(robot_adres)
                print(FgBlue + "Connected to robot: " + BgGreen + data[0] +
                      Reset)
                # дальше не ищем
                break

            if data[1] == "0":
                data[1] = ip_adress_ping
                list_combobox.append(data)

    # combobox = OptionMenu(panelFrame, dropVar, *list)
    # combobox.place(x=250, y=10, width=250, height=40)  # Позиционируем Combobox на форме

    # var = StringVar()
    # combobox = OptionMenu(panelFrame, dropVar, *(list), command=OptionMenu_SelectionEvent)
    combobox = OptionMenu(panelFrame,
                          dropVar,
                          *(list_combobox),
                          command=OptionMenu_SelectionEvent)
    combobox.place(x=260, y=10, width=150,
                   height=40)  # Позиционируем Combobox на форме

    # fn = tkFileDialog.SaveAs(root, filetypes=[('*.py files', '.py')]).show()
    # if fn == '':
    #     return
    # if not fn.endswith(".txt"):
    #     fn += ".txt"
    # open(fn, 'wt').write(textbox.get('1.0', 'end'))
    pass
Example #59
0
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

flag_inet_work = False

port = "5557"

context = zmq.Context()
print(FgBlue + "Start robot API")

list_combobox = []
robot_adres = "-1"
robot_adres_inet = "-1"

# vd = vsc.VideoClient().inst()
# socket.connect ("tcp://192.168.88.19:%s" % port)

selected_file = ""
selected_file_no_dir = ""
video_show = 0
video_show2 = 3
video_show2_global = 0
video_show_work = False
started_flag = 0
Example #60
0
def robot_recive_work():
    global socket, video_show2, recive_flag, started_flag, flag_inet_work, ic, selected_file_no_dir, selected_file
    color_log = FgBlack
    # ic = InetConnection.InetConnect(sc.gethostname() + "_r", "client")
    # ic.connect()
    time_recive = time.time()
    while 1:
        # print("recive_flag", recive_flag)
        # time.sleep(1)
        if recive_flag == 1:
            message_s = ""
            if flag_inet_work == True:
                message_s = ic.send_and_wait_answer(robot_adres_inet, "d")
                time_recive = time.time()
                pass
            else:
                # try:
                #     #print("send..")
                #     socket.send_string("data")
                #     message_s = str(socket.recv_string())
                #     #print("recive ok")
                # except:
                #     pass

                t = time.time()
                while 1:
                    f = 0
                    try:
                        socket.send_string("data", zmq.NOBLOCK)  # zmq.NOBLOCK
                        f = 1
                    except zmq.ZMQError as e:
                        if e.errno == zmq.ETERM:
                            # print("error", e)
                            pass
                    if f == 1:
                        break
                    if time.time() - t > 1:
                        break
                message_s = ""
                t = time.time()
                while 1:
                    f = 0
                    try:
                        message_s = socket.recv_string(zmq.NOBLOCK)
                        time_recive = time.time()
                        f = 1
                    except zmq.ZMQError as e:
                        if e.errno == zmq.ETERM:
                            pass
                            # print("error", e)
                    if message_s != "" or f == 1:
                        break

                    if time.time() - t > 1:
                        break
            # print(message_s.encode('utf-8'))
            # message_s=message_s.replace("/n", "")

            if message_s == None:
                time.sleep(0.01)
                continue

            if time.time() - time_recive > 10:
                print("lost connect ..", time.time() - time_recive)
                if flag_inet_work == True:
                    ic.disconnect()
                    ic.connect()
                    pass
                else:
                    time_recive = time.time()
                    socket.close()
                    socket = context.socket(zmq.REQ)
                    socket.connect("tcp://" + robot_adres + ":%s" % port)
                    socket.send_string("take|" + robot_adres)
                    print("Connected to robot: " + BgGreen +
                          socket.recv_string() + Reset)
                print("reconected")
                if started_flag:
                    recive_flag = 1
                else:
                    recive_flag = 0

            if message_s.find("stoping") >= 0:
                recive_flag = -1

            if message_s.find("STOPED") >= 0 or message_s.find("stoping") >= 0:

                if started_flag == 1:
                    message_s = message_s.replace("STOPED",
                                                  FgRed + "STOPED" + Reset)
                    print(color_log + message_s.rstrip())

                # print("reciv1_stope")
                # message_s = ""
                # video_show2 = -1
                color_log = FgBlack

                # if video_show2 != 3:
                #     video_show2 = -1
                video_show2 = -1
                time.sleep(0.3)
                # while video_show2 != 3 or video_show2 != 0:
                #     print("stop_wideo", video_show2 )
                #     time.sleep(0.3)
                cv2.destroyAllWindows()

                recive_flag = 0
                started_flag = 0
                time.sleep(0.01)
                continue

            if message_s != "" and len(message_s) > 0:
                # обрезаем конец сообщения, спец символ
                if message_s.find("Traceback") >= 0 or message_s.find(
                        "Error:") >= 0:
                    color_log = FgRed
                    video_show2 = -1

                print(color_log + message_s.rstrip())

            time.sleep(0.01)

        if recive_flag == -1:
            # print("reciv-1")
            color_log = FgBlack
            ret = ""
            if flag_inet_work == True:
                ret = ic.send_and_wait_answer(robot_adres_inet, "stop")
                ic.send_and_wait_answer(robot_adres_inet, "stopvideo")
                pass
            else:
                try:
                    socket.send_string("stop")
                    ret = socket.recv_string()
                except:
                    pass
            # if started_flag == 1:
            #     print(ret.replace("STOPED", FgRed + "STOPED" + Reset))
            # recive_flag = 0
            recive_flag = 1
            time.sleep(0.01)

        if recive_flag == 3:
            if flag_inet_work:
                time.sleep(0.5)
                ic.send_and_wait_answer(robot_adres_inet,
                                        "start|" + selected_file_no_dir)
                time.sleep(0.5)
                ic.send_and_wait_answer(robot_adres_inet, "startvideo")
            else:
                try:
                    socket.send_string("start|" + selected_file_no_dir)
                    res = socket.recv_string()
                except:
                    pass
                if res == 0:
                    print(FgRed + "Start fail... try again" + Reset)
            recive_flag = 0

        if recive_flag == 4:
            if flag_inet_work == True:
                with open(selected_file, 'rb') as myfile:
                    data = myfile.read()
                    # print(ic.send_and_wait_answer(robot_adres_inet, "file|" + selected_file_no_dir + "|" + data.decode("utf-8")))
                #        z = zlib.compress(data, 1).decode("utf-8")
                ic.send_and_wait_answer(
                    robot_adres_inet,
                    "file|" + selected_file_no_dir + "|" + str(
                        base64.b64encode(zlib.compress(data,
                                                       1)).decode("utf-8")))
            else:
                try:
                    socket.send_string("file|" + selected_file_no_dir)
                    res = socket.recv_string()
                except:
                    pass
                if res == 0:
                    print(FgRed + "Fail send name file.. try again" + Reset)
                    return
            recive_flag = 0

        if recive_flag == 5:
            if flag_inet_work == True:
                pass
            else:
                with open(selected_file, 'rb') as myfile:
                    data = myfile.read()
                # print(data)
                # s1 = fastlz.compress(data)
                # s2 = fastlz.decompress(s1)
                # print(len(data), len(s1), len(s2))

                # data = zlib.compress(data, 1)
                data = zlib.compress(data, 1)
                res = 0
                try:
                    socket.send(data)
                    res = socket.recv_string()
                except:
                    pass

                if res == 0:
                    print(FgRed + "Fail send file.. try again" + Reset)
                    return
            recive_flag = 0

        # if recive_flag == 0:
        #     #print("recive flag=0")
        #     time.sleep(0.05)

        time.sleep(0.05)