Example #1
0
def get_adjacency_lists(in_file):
    edges = {}
    verts = {}
    edge_count = 0
    with open(in_file) as f:
        for line in f.readlines():
            vertex = line.split()
            v1 = int(vertex[0])
            for v2_s in vertex[1:]:
                v2 = int(v2_s)
                if v2 > v1:
                    # avoid adding duplicated edges in the loaded graph
                    try:
                        verts[v1].add(edge_count)  # edges in v1
                    except KeyError:
                        verts[v1] = set()
                        verts[v1].add(edge_count)
                    try:
                        verts[v2].add(edge_count)  # edges in v2
                    except KeyError:
                        verts[v2] = set()
                        verts[v2].add(edge_count)

                    edges[edge_count] = [v1, v2]
                    edge_count += 1

    return edges, verts
Example #2
0
def main():
    ptt_dir = '/tmp2/GorsachiusMelanolophus/ptt_posts_new/no_sponsored/'
    imgs_dir = '/tmp2/GorsachiusMelanolophus/ptt_imgs/no_sponsored/'
    start = int(sys.argv[1])
    end = int(sys.argv[2])
    fp = open('../img_num/' + str(start)+ '.txt', 'a')
    for i in range(start, end):
        try:
            post_path = ptt_dir + str(i) + '.p'
            post = pickle.load(open(post_path, 'rb'))
            url = ptt_url + post['href']
            webpage = get_webpage(url)
            imgs, blog_url = parse_post(webpage)
            if imgs:
                print(f'{i}:{len(imgs)}', file=fp)
                save(imgs, imgs_dir + str(i))
            elif blog_url:
                webpage = get_webpage(blog_url)
                imgs = get_imgs_blog(webpage)
                if imgs:
                    print(f'{i}:{len(imgs)}', file=fp)
                    save(imgs, imgs_dir + str(i))
        except KeyboardInterrupt:
            return 0
        except Exception as e:
            print(e)
            pass
Example #3
0
    def post(self):

        if not check_logged_in():
            self.redirect(users.create_login_url(self.request.uri))
            return

        # Grab user and user data
        user = get_user()
        user_data = UserData.query(UserData.user == user).fetch()[0]

        # Flips to true if any updates were made
        updated = False

        # Grab the payload from POST request and today's month
        user_dict = json.loads(self.request.body)

        if user_dict.get('duration'):
            user_data.last_duration = int(user_dict.get('duration'))
            updated = True

        if user_dict.get('goal'):
            user_data.last_goal = int(user_dict.get('goal'))
            updated = True

        user_data.put()

        # Let user know this was a success!
        response = {"status": "success"}
        self.response.write(json.dumps(response))        
Example #4
0
def search_json(request, database_name=settings.MONGO_DB_NAME,
                collection_name=settings.MONGO_MASTER_COLLECTION,
                skip=0, limit=settings.MONGO_LIMIT, sort=None, return_keys=(),
                query={}):
    

    
    result = prepare_search_results(request, database_name=database_name,
                collection_name=collection_name, skip=skip, sort=sort,
                limit=limit, return_keys=return_keys, query=query)

    if int(result['code'])==200:
        listresults=result['results']

    else:
        response = json.dumps(result, indent =4)
        return HttpResponse(response, status=int(result['code']),
                            mimetype="application/json")

    if settings.RESPECT_SOCIAL_GRAPH:
        listresults=filter_social_graph(request, listresults)


        len_results=len(listresults)
        if len_results < result['num_results']:
            result['ommitted-results']= result['num_results'] - len_results
            result['results']=listresults

        jsonresults=to_json(result)
        return HttpResponse(jsonresults, status=int(result['code']),
                            mimetype="application/json")
    else:
        jsonresults=to_json(normalize_results(result))
        return HttpResponse(jsonresults, status=int(result['code']),mimetype="application/json")
Example #5
0
 def equ(*args):
     Visor = '' + N1.get()
     if Visor.find('²') != -1:
         try:
             A = int(Visor[:Visor.find('x²')])
         except ValueError:
             A = 1
         B = int(Visor[ Visor.find('²')+1 : Visor.find('x', Visor.find('²'))])
         C = int(Visor[ Visor.find('x', Visor.find('²'))+1 : Visor.find('=')])+int(Visor[ Visor.find('=')+1:])
         D = B**2 - 4 * A * C
         #D = B**2 – 4 * A * C parece igual a linha de cima mas não é
         if D > 0:
             X1 = ((-1*B)+sqrt(D))/2*A
             X2 = ((-1*B)-sqrt(D))/2*A
             Resultado = ('X\' = ',X1,'X\" = ',X2)
             N1.set(Resultado)
 
         elif D == 0:
             X = ((-1*B)+sqrt(D))/2*A
             Resultado = ('X\' = ',X,'X\" = ',X)
             N1.set(Resultado)
         else:
             N1.set('Não há raízes reais')
         Historico.set(Historico.get() + Visor + ' = ' + N1.get() + '\n')                 
     else:
         pass
Example #6
0
def event_update_participant_status(profile, event):
    if request.is_xhr:
        if profile.userid not in g.user.user_organizations_owned_ids():
            abort(403)
        participantid = int(request.form['participantid'])
        status = int(request.form['status'])
        participant = Participant.query.get(participantid)

        if participant.event != event:
            abort(403)
        if participant.status == PARTICIPANT_STATUS.WITHDRAWN:
            abort(403)
        if participant.status != status:
            participant.status = status
            try:
                text_message = unicode(getattr(event, (participants_email_attrs[status] + '_text')))
                text_message = text_message.replace("*|FULLNAME|*", participant.user.fullname)
                message = unicode(getattr(event, participants_email_attrs[status]))
                message = message.replace("*|FULLNAME|*", participant.user.fullname)
                if message and g.user.email:
                    send_email(sender=(g.user.fullname, g.user.email), to=participant.email,
                    subject="%s - Hacknight participation status" % event.title , body=text_message, html=message)
            except KeyError:
                pass
            db.session.commit()
        return "Done"
    abort(403)
Example #7
0
    def _load_zabbix_config(self,config_file):
        # Load zabbix agent configuration as default values
        # Default values are set in self._config
        # - ServerActive (default: 127.0.0.1)
        # - LogFile (default: /tmp/zabbix_agentd.log)
        # - DebugLevel (default: 3, Allowed: 0-4)
        #               0 -> logging.NOTSET
        #               1 -> logging.CRITICAL
        #               2 -> logging.ERROR
        #               3 -> logging.WARNING
        #               4 -> logging.DEBUG
        # - Timeout (default: 3, Allowed: 1-30)
        tmp_config = configobj.ConfigObj(config_file, list_values=False)

        if 'ServerActive' in tmp_config:
            tmp_server = tmp_config['ServerActive'][0] \
                         if isinstance(tmp_config['ServerActive'], list) \
                         else list(tmp_config['ServerActive'])[0]
            self._config['server'], self._config['port'] = tmp_server.split(':') \
                         if ":" in tmp_server else (tmp_server, 10051)

        if 'LogFile' in tmp_config:
            self._config['log_output'] = tmp_config['LogFile']

        if 'DebugLevel' in tmp_config:
            self._config['log_level'] = int(tmp_config['DebugLevel'])

        if 'Timeout' in tmp_config:
            self._config['timeout'] = int(tmp_config['Timeout'])
Example #8
0
 def RandomGraph(self, nodes, edges, maxweight = 100.0):
     """
     Generates a graph of random edges.
     
     @param nodes: list of nodes or number of nodes in the random graph
     @param edges: number of edges to generate in the random graph
     @type edges: integer
     @param maxweight: maximum weight of each edge. default = 100.0
     @type maxweight: float
     """
     import random
     nodes_size = 0
     if type(nodes) == int:
         adjacency = [range(nodes)]
         nodes_size = nodes
         for node in range(nodes):
             adjacency.append([0 for x in range(nodes)])
     elif type(nodes) == list:
         adjacency = nodes
         nodes_size = len(nodes)
         for node in range(nodes_size):
             adjacency.append([0 for x in range(nodes_size)])
     else: raise FunctionParameterTypeError('nodes can only be a list \
             or integer')
     count = 0
     while count <= edges:
         edge = (int(random.uniform(0, nodes_size)) + 1, 
                 int(random.uniform(0, nodes_size)),
                 int(random.uniform(0, 1) * maxweight))
         if adjacency[edge[0]][edge[1]] == 0:
             adjacency[edge[0]][edge[1]] = edge[2]
             count = count + 1
     self.makeGraphFromAdjacency(adjacency)
Example #9
0
    def mouseMoveEvent (self, event):
        if self.moving:
            _myDigitalNewWidth, _siblingWidth = Endstop.mouseMoveEvent (self, event)

            _lhs = _myDigitalNewWidth
            _middle = self.layoutWidth - _myDigitalNewWidth - _siblingWidth
            _rhs = _siblingWidth

            self._parent.sliderBarLayout.setStretchFactor (self, _lhs)
            self._parent.sliderBarLayout.setStretchFactor (self.slider, _middle)
            self._parent.sliderBarLayout.setStretchFactor (self.sibling, _rhs)

            _oldStart = self._parent.startPosition
            _oldFinish = self._parent.finishPosition
            self._parent.startPosition = int (((_lhs - self.endstopWidth) * (self._parent._steps - 1.0) / (self.layoutWidth - 2.0 * self.endstopWidth)))
            self._parent.finishPosition = self._parent._steps - int (((_rhs - self.endstopWidth) * (self._parent._steps - 1.0) / (self.layoutWidth - 2.0 * self.endstopWidth))) - 1
            self._parent.slider.setRange (self._parent.startPosition, self._parent.finishPosition)
            self._parent.lower.setText (self.root.tss.series () [0].getAllTimes () [self._parent.startPosition])

            if (_oldStart != self._parent.startPosition) or (_oldFinish != self._parent.finishPosition):
                self.root.redrawAll ()

                if (self._parent.finishPosition - self._parent.startPosition) < 20:
                    self._parent.slider.setTickInterval (1)
                else:
                    self._parent.slider.setTickInterval (0)
    def _on_headers(self, data):
        data = native_str(data.decode("latin1"))
        first_line, _, header_data = data.partition("\n")
        match = re.match("HTTP/1.[01] ([0-9]+) ([^\r]*)", first_line)
        assert match
        code = int(match.group(1))
        self.headers = HTTPHeaders.parse(header_data)
        if 100 <= code < 200:
            self._handle_1xx(code)
            return
        else:
            self.code = code
            self.reason = match.group(2)

        if "Content-Length" in self.headers:
            if "," in self.headers["Content-Length"]:
                # Proxies sometimes cause Content-Length headers to get
                # duplicated.  If all the values are identical then we can
                # use them but if they differ it's an error.
                pieces = re.split(r',\s*', self.headers["Content-Length"])
                if any(i != pieces[0] for i in pieces):
                    raise ValueError("Multiple unequal Content-Lengths: %r" %
                                     self.headers["Content-Length"])
                self.headers["Content-Length"] = pieces[0]
            content_length = int(self.headers["Content-Length"])
        else:
            content_length = None

        if self.request.header_callback is not None:
            # re-attach the newline we split on earlier
            self.request.header_callback(first_line + _)
            for k, v in self.headers.get_all():
                self.request.header_callback("%s: %s\r\n" % (k, v))
            self.request.header_callback('\r\n')

        if self.request.method == "HEAD" or self.code == 304:
            # HEAD requests and 304 responses never have content, even
            # though they may have content-length headers
            self._on_body(b"")
            return
        if 100 <= self.code < 200 or self.code == 204:
            # These response codes never have bodies
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
            if ("Transfer-Encoding" in self.headers or
                    content_length not in (None, 0)):
                raise ValueError("Response with code %d should not have body" %
                                 self.code)
            self._on_body(b"")
            return

        if (self.request.use_gzip and
                self.headers.get("Content-Encoding") == "gzip"):
            self._decompressor = GzipDecompressor()
        if self.headers.get("Transfer-Encoding") == "chunked":
            self.chunks = []
            self.stream.read_until(b"\r\n", self._on_chunk_length)
        elif content_length is not None:
            self.stream.read_bytes(content_length, self._on_body)
        else:
            self.stream.read_until_close(self._on_body)
Example #11
0
    def next(self):
        """
        Increment the iterator and yield the new value. Also, store the
        current value for use in the comparison function.
        """
        if not self.finishedReadingFile:

            try:
                line = self.theFile.next()
                cols = line.strip().split("\t")
                chrom = cols[0]

                # Where possible, convert chromosome names into
                # integers for sorting. If not possible, use
                # original names.
                try:
                    chrom = int(chrom.upper().strip("CHR"))
                except:
                    pass

                pos = int(cols[1])
                heapq.heappush(self.heap, (chrom, pos, line))

            except StopIteration:
                self.finishedReadingFile = True

        if len(self.heap) != 0:
            # Now take the top line
            self.chrom, self.pos, self.line = heapq.heappop(self.heap)
        else:
            raise StopIteration
  def IncrementVersion(self):
    """Updates the version file by incrementing the patch component.

    Args:
      message: Commit message to use when incrementing the version.
      dry_run: Git dry_run.
    """
    if not self.incr_type or self.incr_type not in self.VALID_INCR_TYPES:
      raise VersionUpdateException('Need to specify the part of the version to'
                                   ' increment')

    if self.incr_type == 'chrome_branch':
      self.chrome_branch = str(int(self.chrome_branch) + 1)

    # Increment build_number for 'chrome_branch' incr_type to avoid
    # crbug.com/213075.
    if self.incr_type in ('build', 'chrome_branch'):
      self.build_number = str(int(self.build_number) + 1)
      self.branch_build_number = '0'
      self.patch_number = '0'
    elif self.incr_type == 'branch' and self.patch_number == '0':
      self.branch_build_number = str(int(self.branch_build_number) + 1)
    else:
      self.patch_number = str(int(self.patch_number) + 1)

    return self.VersionString()
Example #13
0
def check_compatible(client, min_version=None, max_version=None):
    """Checks if a kazoo client is backed by a zookeeper server version.

    This check will verify that the zookeeper server version that the client
    is connected to satisfies a given minimum version (inclusive) and
    maximum (inclusive) version range. If the server is not in the provided
    version range then a exception is raised indiciating this.
    """
    server_version = None
    if min_version:
        server_version = tuple((int(a) for a in client.server_version()))
        min_version = tuple((int(a) for a in min_version))
        if server_version < min_version:
            pretty_server_version = ".".join([str(a) for a in server_version])
            min_version = ".".join([str(a) for a in min_version])
            raise exc.IncompatibleVersion("Incompatible zookeeper version"
                                          " %s detected, zookeeper >= %s"
                                          " required" % (pretty_server_version,
                                                         min_version))
    if max_version:
        if server_version is None:
            server_version = tuple((int(a) for a in client.server_version()))
        max_version = tuple((int(a) for a in max_version))
        if server_version > max_version:
            pretty_server_version = ".".join([str(a) for a in server_version])
            max_version = ".".join([str(a) for a in max_version])
            raise exc.IncompatibleVersion("Incompatible zookeeper version"
                                          " %s detected, zookeeper <= %s"
                                          " required" % (pretty_server_version,
                                                         max_version))
Example #14
0
def get_messages(request, pk):
    error_code = 0
    error_text = ''
    channel = 'channel_' + str(pk)
    SSE.redis_channel = channel
    if request.is_ajax():
        r = redis.Redis('127.0.0.1')
        messages_list = []
        count = 0
        messages = r.lrange(SSE.redis_channel, 0, r.llen(SSE.redis_channel))
        for message in messages:
            messages_list.append(json.loads(message.replace('\'', '\"').replace('u"', '"')))
        for obj in messages_list:
            if not int(request.user.profile.pk) in obj['read']:
                i = messages_list.index(obj)
                obj['read'].append(int(request.user.profile.pk))
                r.lset(SSE.redis_channel, i, obj)
                count += 1
        if messages_list.__len__() > 20:
            if count == 0:
                messages_list = messages_list[-20:]
            else:
                messages_list = messages_list[-count-5:]
        return HttpResponse(json.dumps({'error_code': error_code, 'error_text': error_text, 'messages': messages_list}), content_type="application/json")
    return render(request, 'accounts/chat.html')
    def load_small_box_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.3
        box_length_meters = 32.*0.4

        box_image = pygame.image.load('resources/waterOffset.png')

        (box_image_width, box_image_height) = box_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(box_image_width/2.)

        new_size = (int(round(scale_down_ratio*box_image_width)), int(round(scale_down_ratio*box_image_height)))

        box = pygame.transform.smoothscale(box_image,new_size)

        self.small_box_image = box

        return
Example #16
0
 def crop(self, left, top, right, bottom):
     self.image = self.image.crop((
         int(left),
         int(top),
         int(right),
         int(bottom)
     ))
    def load_goal_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.2
        box_length_meters = 32.*0.2

        flag_image = pygame.image.load('resources/finishFlag.png')

        (flag_image_width, flag_image_height) = flag_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(flag_image_width/2.)

        new_size = (int(round(scale_down_ratio*flag_image_width)), int(round(scale_down_ratio*flag_image_height)))

        flag = pygame.transform.smoothscale(flag_image,new_size)

        self.goal_image = flag

        return
Example #18
0
File: popup.py Project: fuinha/kiwi
    def _on__button_press_event(self, window, event):
        # If we're clicking outside of the window
        # close the popup
        toplevel = event.window.get_toplevel()
        parent = self.main_widget.get_parent_window()
        if toplevel != parent:
            self.popdown()
            return True

        # Gtk 2.x
        if hasattr(self, 'allocation'):
            out = self.allocation.intersect(
                gtk.gdk.Rectangle(x=int(event.x), y=int(event.y),
                                  width=1, height=1))
        else:
            rect = gtk.gdk.Rectangle()
            (rect.x, rect.y,
             rect.width, rect.height) = (int(event.x), int(event.y), 1, 1)
            out = gtk.gdk.Rectangle()
            self.intersect(rect, out)

        if (out.x, out.y, out.width, out.height) == (0, 0, 0, 0):
            self.popdown()
            return True

        return False
Example #19
0
 def _altCrop(self, source, desc):
     """PIL image for the described crop"""
     w, h = source.size
     return source.crop((int(w * desc[PHO.x1].toPython()),
                         int(h * desc[PHO.y1].toPython()),
                         int(w * desc[PHO.x2].toPython()),
                         int(h * desc[PHO.y2].toPython())))
Example #20
0
def page_extract(start, end, SUBSECTION):

    PDF_IN = PdfFileReader(open(PDF_DIR, 'rb'))

#    for i in xrange(PDF_IN.numPages): # for all pages
    for i in range(int(start) - 1, int(end)):

        output = PdfFileWriter()
        output.addPage(PDF_IN.getPage(i))
        
        base, name_ext = os.path.split(PDF_DIR)
        name, ext      = os.path.splitext(name_ext)
        PDF_OUT        = '{}{}'.format(TMP_DIR, '{}-{}{}'.format(name, str(i).zfill(6), ext))
        
        with open(PDF_OUT, 'wb') as outputStream:
            output.write(outputStream)
        
        gs_pdf_to_png(PDF_OUT)
        os.remove(PDF_OUT)
    
    png_list = group(os.listdir(TMP_DIR), 2)
    for tup in png_list:
        print tup
        card_front = os.path.join(TMP_DIR, tup[0])
        card_back  = os.path.join(TMP_DIR, tup[1])
        make_cards(card_front, card_back, SUBSECTION)
Example #21
0
 def __helpsort(self, h1, h2):
     if int(h1[2]) < int(h2[2]):
         return -1
     elif int(h1[2]) > int(h2[2]):
         return 1
     else:
         return 0
def checkHash(hashnum):
        checkByte = 0;
        flag = 0;

        HashStr = '%s' % hashnum
        length = len(HashStr)

        for i in range(0, length):
            Re = int(HashStr[(length - 1) - i])
            if (1 == (flag % 2)):
                Re += Re
                Re = int((Re / 10) + (Re % 10))

            checkByte += int(Re)
            flag = flag + 1

        checkByte %= 10
        if (0 != checkByte):
            checkByte = 10 - checkByte
            if (1 == (flag % 2)):
                if (1 == (checkByte % 2)):
                    checkByte += 9

                checkByte >>= 1
        return '7%s%s' % (checkByte, HashStr)
Example #23
0
def search_csv(request, database_name=settings.MONGO_DB_NAME,
                collection_name=settings.MONGO_MASTER_COLLECTION,
                skip=0, sort=None, limit=settings.MONGO_LIMIT, return_keys=(), query={}):
    
    result = prepare_search_results(request, database_name=database_name,
                collection_name=collection_name, sort=sort, skip=skip,
                limit=limit, return_keys=return_keys, query=query)

    #print result.keys()

    if int(result['code']) == 200:
        listresults=result['results']
        if settings.RESPECT_SOCIAL_GRAPH:
            listresults = filter_social_graph(request, listresults)
            len_results = len(listresults)
            if len_results < result['num_results']:
                result['ommitted-results']= result['num_results'] - len_results

        keylist = []
        for i in listresults:
            for j in i.keys():
                if not keylist.__contains__(j):
                    keylist.append(j)


        return convert_to_csv(keylist, listresults)

    else:
        jsonresults=to_json(result)
        return HttpResponse(jsonresults, status=int(result['code']),
                            mimetype="application/json")
Example #24
0
def hamiltonkreis(graph):
    kreisExistiert = False
    startKnoten = graph[0][0]
    wege = [[startKnoten]]
    wegeErweitert = []
    zaehler = 0
    while wege != [] and not kreisExistiert: 
        aktuellerWeg = wege[0]
        wege = wege[1:]

        letzterKnoten = aktuellerWeg[len(aktuellerWeg)-1]
        # bestimme die Nachbarn von letzterKnoten
        knotenGefunden = False
        
        if len(aktuellerWeg) == len(graph):
            # Test, ob zu Hamiltonkreis erweiterbar
            zaehler = zaehler + 1
            

            listeNachbarknoten = graph[int(letzterKnoten)-1][1]
            
            # teste, ob es eine Kante zum startKnoten gibt
            if startKnoten in listeNachbarknoten:
                kreisExistiert = True
                #print(aktuellerWeg+[startKnoten])
        else:
            listeNachbarknoten = graph[int(letzterKnoten)-1][1]
            
            for nachbarKnoten in listeNachbarknoten:
                zaehler = zaehler + 1
                if not nachbarKnoten in aktuellerWeg:
                    erweiterterWeg = aktuellerWeg + [nachbarKnoten]
                    wege = [erweiterterWeg] + wege
    return (kreisExistiert, zaehler)
Example #25
0
	def route(self, minz):
		try:
			self.paths = []
			self.sub_terminal_collision_lines()
			visited = set()
			for index in xrange(1, len(self.terminals)):
				visited |= set([(int(self.terminals[index - 1][2][0]+0.5), int(self.terminals[index - 1][2][1]+0.5), z) for z in xrange(self.pcb.depth)])
				ends = [(int(self.terminals[index][2][0]+0.5), int(self.terminals[index][2][1]+0.5), z) for z in xrange(self.pcb.depth)]
				self.pcb.mark_distances(self.pcb.routing_flood_vectors, self.radius, self.via, self.gap, visited, ends)
				ends = [(self.pcb.get_node(node), node) for node in ends]
				ends.sort()
				_, end = ends[0]
				path = [end]
				while path[-1] not in visited:
					nearer_nodes = self.pcb.all_not_shorting(self.pcb.all_nearer_sorted, \
								(self.pcb.routing_path_vectors, path[-1], end, self.pcb.dfunc), path[-1], self.radius, self.via, self.gap)
					next_node = next(nearer_nodes)
					if minz:
						for node in nearer_nodes:
							if node[2] == path[-1][2]:
								next_node = node
								break
					path.append(next_node)
				visited |= set(path)
				self.paths.append(path)
				self.pcb.unmark_distances()
			self.paths = self.optimise_paths(self.paths)
			self.add_paths_collision_lines()
			self.add_terminal_collision_lines()
			return True
		except StopIteration:
			self.pcb.unmark_distances()
			self.remove()
			return False
Example #26
0
    def test_command_line_ignores_draft_page(self):
        # we need to create a superuser (the db is empty)
        User.objects.create_superuser('djangocms', 'cms@example.com', '123456')

        create_page("The page!", "nav_playground.html", "en", published=False)

        pages_from_output = 0
        published_from_output = 0

        with StdoutOverride() as buffer:
            # Now we don't expect it to raise, but we need to redirect IO
            com = publisher_publish.Command()
            com.handle_noargs()
            lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work

        for line in lines:
            if 'Total' in line:
                pages_from_output = int(line.split(':')[1])
            elif 'Published' in line:
                published_from_output = int(line.split(':')[1])

        self.assertEqual(pages_from_output,0)
        self.assertEqual(published_from_output,0)

        self.assertEqual(Page.objects.public().count(), 0)
Example #27
0
    def post(self):

        if not check_logged_in():
            self.redirect(users.create_login_url(self.request.uri))
            return

        # Grab user
        user = get_user()

        # Grab the payload from POST request and today's month
        session_dict = json.loads(self.request.body)

        # Pre-process received data, including escaping HTML chars
        safe_session_dict = {} # Escaped / processed data will go in here

        safe_session_dict['user'] = user
        safe_session_dict['duration'] = int(session_dict.get('duration'), 0)
        safe_session_dict['goal'] = int(session_dict.get('goal'), 0)
        safe_session_dict['reached_goal'] = bool(session_dict.get('reachedGoal'), False)

        # Begin validity check
        # validity_check = self.verify_data_integrity(safe_session_dict)

        new_session = Session()

        # Populate the entity with cleaned dictionary values and save
        new_session.populate(**safe_survey_dict)
        new_session.put()

        # Let user know this was a success!
        response = {"status": "success"}
        self.response.write(json.dumps(response))
Example #28
0
 def output_shape(self):
     channels, height, width = self.input_shape
     out_height = (height - self.pool_shape[0]) / self.stride + 1
     out_width = (width - self.pool_shape[1]) / self.stride + 1
     assert out_height % 1 == 0
     assert out_width % 1 == 0
     return channels, int(out_height), int(out_width)
Example #29
0
def make_video(events, t0=0.0, t1=None, dt_frame=0.01, tau=0.01):
    if t1 is None:
        t1 = events["t"].max()

    ts = events["t"]
    dt = 1e-3
    nt = int((t1 - t0) / dt) + 1
    # nt = min(nt, 1000)  # cap at 1000 for now

    image = np.zeros((128, 128))
    images = np.zeros((nt, 128, 128))

    for i in range(nt):
        # --- decay image
        image *= np.exp(-dt / tau) if tau > 0 else 0
        # image *= 0

        # --- add events
        ti = t0 + i * dt
        add_to_image(image, events[close(ts, ti)])

        images[i] = image

    # --- average in frames
    nt_frame = int(dt_frame / dt)
    nt_video = int(nt / nt_frame)

    video = np.zeros((nt_video, 128, 128))
    for i in range(nt_video):
        slicei = slice(i * nt_frame, (i + 1) * nt_frame)
        video[i] = np.sum(images[slicei], axis=0)

    return video
Example #30
0
def ip_in_subnet(ip, subnet):
    """Does IP exists in a given subnet utility. Returns a boolean"""
    ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16)
    netstr, bits = subnet.split('/')
    netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16)
    mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
    return (ipaddr & mask) == (netaddr & mask)