コード例 #1
0
    def get_connected_devices(self):
        '''Get a list of attached Saleae devices.

		Note, this will never be an empty list. If no actual Saleae devices are
		connected, then Logic will return the four fake devices shown in the
		example.

		:returns: A list of ``saleae.ConnectedDevice`` objects

		>>> s.get_connected_devices() #doctest:+ELLIPSIS
		[<saleae.ConnectedDevice #1 LOGIC_4_DEVICE Logic 4 (...) **ACTIVE**>, <saleae.ConnectedDevice #2 LOGIC_8_DEVICE Logic 8 (...)>, <saleae.ConnectedDevice #3 LOGIC_PRO_8_DEVICE Logic Pro 8 (...)>, <saleae.ConnectedDevice #4 LOGIC_PRO_16_DEVICE Logic Pro 16 (...)>]
		'''
        devices = self._cmd('GET_CONNECTED_DEVICES')
        # command response is sometimes not the expected one : a non-empty string starting with a digit (index)
        while ('' == devices or not devices[0].isdigit()):
            time.sleep(0.1)
            devices = self._cmd('GET_CONNECTED_DEVICES')

        self.connected_devices = []
        for dev in devices.split('\n')[:-1]:
            active = False
            try:
                index, name, type, id, active = list(
                    map(str.strip, dev.split(',')))
            except ValueError:
                index, name, type, id = list(map(str.strip, dev.split(',')))
            self.connected_devices.append(
                ConnectedDevice(type, name, id, index, active))
        return self.connected_devices
コード例 #2
0
    def get_active_channels(self):
        '''Get the active digital and analog channels.

		:returns: A 2-tuple of lists of integers, the active digital and analog channels respectively

		>>> s.get_active_channels()
		([0, 1, 2, 3], [0])
		'''
        # If an old Logic8 is connected this command does not work, but all 8
        # digital channels are always active so return that.
        device = self.get_active_device()
        if device.type == "LOGIC_DEVICE":
            return range(8), []

        channels = self._cmd('GET_ACTIVE_CHANNELS')
        # Work around possible bug in Logic8
        # https://github.com/ppannuto/python-saleae/pull/19
        while not channels.startswith('digital_channels'):
            time.sleep(0.1)
            channels = self._cmd('GET_ACTIVE_CHANNELS')
        msg = list(map(str.strip, channels.split(',')))
        assert msg.pop(0) == 'digital_channels'
        i = msg.index('analog_channels')
        digital = list(map(int, msg[:i]))
        analog = list(map(int, msg[i + 1:]))

        return digital, analog
コード例 #3
0
def ChooseFeatures (Filename):

    FirstFeatureList=list()
    SecodFeatureList=list()
    ThirdFeatureList=list()
    FourthFeatureList=list()
    ThisnewLabel=[]
    LabelList=list()
    File=open(Filename)
    Lines = File.readlines()
    for eachline in Lines:
        X1 = (eachline.split(','))[0]
        X2 = (eachline.split(','))[1]
        X3 = (eachline.split(','))[2]
        X4 = (eachline.split(','))[3]
        ThisLabel=(eachline.split(','))[4]
        if ThisLabel=="C1" + "\n":
            ThisnewLabel=([0,0,1])
        elif ThisLabel=="C2" + "\n":
            ThisnewLabel=([0,1,0])
        elif ThisLabel=="C3" + "\n":
            ThisnewLabel=([1,0,0])
        FirstFeatureList.append(X1)
        SecodFeatureList.append(X2)
        ThirdFeatureList.append(X3)
        FourthFeatureList.append(X4)

        LabelList.append(ThisnewLabel)

    # FourthFeatureList = np.array(FourthFeatureList)
    LabelList = np.array(LabelList)
    return (FirstFeatureList,SecodFeatureList,ThirdFeatureList,FourthFeatureList,LabelList)
コード例 #4
0
ファイル: SVM.py プロジェクト: Rorolas/Proyecto-Tesis
    def procesartexto(tweet):
        listatokenizada = preprocess(tweet)
        listatokenizada = list(set(listatokenizada))
        listaEliminar = []

        for i in range(len(listatokenizada)):
            if es_numero(listatokenizada[i]):
                listaEliminar.append(listatokenizada[i])
            if len(listatokenizada[i]) <= 1:
                listaEliminar.append(listatokenizada[i])
            if listatokenizada[i].startswith('@'):
                listaEliminar.append(listatokenizada[i])
            if listatokenizada[i].startswith('x'):
                listaEliminar.append(listatokenizada[i])
            if listatokenizada[i].startswith('#'):
                listaEliminar.append(listatokenizada[i])
            if listatokenizada[i].startswith('http'):
                listaEliminar.append(listatokenizada[i])

        listaEliminar = list(set(listaEliminar))
        textoprocesado = ''
        for x in range(len(listaEliminar)):
            valor_eliminar = listaEliminar[x]
            listatokenizada.remove(listaEliminar[x])
        for j in range(len(listatokenizada)):
            textoprocesado = textoprocesado + ' ' + sno.stem(
                listatokenizada[j])
        print(textoprocesado)
        del listatokenizada, listaEliminar
        return textoprocesado
コード例 #5
0
ファイル: message.py プロジェクト: ashleyse2016/SpamPAD
 def __init__(self, global_context, raw_msg):
     """Parse the message, extracts and decode all headers and all
     text parts.
     """
     super(Message, self).__init__(global_context)
     self.raw_msg = self.translate_line_breaks(raw_msg)
     self.msg = email.message_from_string(self.raw_msg)
     self.headers = _Headers()
     self.raw_headers = _Headers()
     self.addr_headers = _Headers()
     self.name_headers = _Headers()
     self.mime_headers = _Headers()
     self.received_headers = list()
     self.raw_mime_headers = _Headers()
     self.header_ips = _Headers()
     self.text = ""
     self.raw_text = ""
     self.uri_list = set()
     self.score = 0
     self.rules_checked = dict()
     self.interpolate_data = dict()
     self.plugin_tags = dict()
     # Data
     self.sender_address = ""
     self.hostname_with_ip = list()
     self.internal_relays = []
     self.external_relays = []
     self.last_internal_relay_index = 0
     self.last_trusted_relay_index = 0
     self.trusted_relays = []
     self.untrusted_relays = []
     self._parse_message()
     self._hook_parsed_metadata()
コード例 #6
0
ファイル: data_utils.py プロジェクト: wumpus/eht-dmc
def gain_account(obs):
    """ Determine the total number of gains that need to be solved for

       Args:
           obs (obsdata): eht-imaging obsdata object containing VLBI data
           
       Returns:
           T_gains: list of gain timestamps
           A_gains: list of gain stations
    
    """

    # get arrays of station names
    ant1 = obs.data['t1']
    ant2 = obs.data['t2']

    # get array of timestamps
    time = obs.data['time']
    timestamps = np.unique(time)

    # Determine the total number of gains that need to be solved for
    N_gains = 0
    T_gains = list()
    A_gains = list()
    for it, t in enumerate(timestamps):
        ind_here = (time == t)
        N_gains += len(np.unique(np.concatenate((ant1[ind_here],ant2[ind_here]))))
        stations_here = np.unique(np.concatenate((ant1[ind_here],ant2[ind_here])))
        for ii in range(len(stations_here)):
            A_gains.append(stations_here[ii])
            T_gains.append(t)
    T_gains = np.array(T_gains)
    A_gains = np.array(A_gains)

    return T_gains, A_gains
コード例 #7
0
def args_tptnfpfn(*args, **kwargs):
    """Convert kwargs for tp, tn, fp, fn to ordered tuple of args
    If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args
    >>> args_tptnfpfn(1, 2, 3, 4)
    (1, 2, 3, 4)
    >>> args_tptnfpfn((1, 2, 3, 4))
    (1, 2, 3, 4)
    >>> args_tptnfpfn([1, 2, 3, 4])
    (1, 2, 3, 4)
    >>> args_tptnfpfn(3, 4, tp=1, tn=2)
    (1, 2, 3, 4)
    >>> args_tptnfpfn(tp=1, tn=2)
    (1, 2, 0, 0)
    >>> args_tptnfpfn(tp=1, tn=2, fp=3, fn=4)
    (1, 2, 3, 4)
    >>> args_tptnfpfn(1)
    (1, 0, 0, 0)
    """
    if len(args) == 4:
        tp, tn, fp, fn = args
    elif len(kwargs) == 0:
        if len(args) == 1:
            args = listify(args[0])
        tp, tn, fp, fn = list(list(args) + [0] * (4 - len(args)))
    else:
        args = list(args)
        tp = kwargs['tp'] if 'tp' in kwargs else args.pop(0) if len(
            args) else 0
        tn = kwargs['tn'] if 'tn' in kwargs else args.pop(0) if len(
            args) else 0
        fp = kwargs['fp'] if 'fp' in kwargs else args.pop(0) if len(
            args) else 0
        fn = kwargs['fn'] if 'fn' in kwargs else args.pop(0) if len(
            args) else 0
    return tp, tn, fp, fn
コード例 #8
0
    def test_extendable_enum(self):
        class Foobar(utils.Enum):
            AAA = 1
            BBB = 2
            CCC = 3

        self.assertSequenceEqual(builtins.list(Foobar.__members__.keys()), ['AAA', 'BBB', 'CCC'])
        self.assertSequenceEqual([value.value for value in Foobar.__members__.values()], [1, 2, 3])

        with self.assertRaises(AttributeError):
            Foobar.register_value('CCC', 5)

        self.assertSequenceEqual(builtins.list(Foobar.__members__.keys()), ['AAA', 'BBB', 'CCC'])
        self.assertSequenceEqual([value.value for value in Foobar.__members__.values()], [1, 2, 3])

        Foobar.register_value('DDD', 4)

        self.assertSequenceEqual(builtins.list(Foobar.__members__.keys()), ['AAA', 'BBB', 'CCC', 'DDD'])
        self.assertSequenceEqual([value.value for value in Foobar.__members__.values()], [1, 2, 3, 4])

        self.assertEqual(Foobar['DDD'], 'DDD')
        self.assertEqual(Foobar(4), 'DDD')

        Foobar.register_value('EEE', 4)

        self.assertSequenceEqual(builtins.list(Foobar.__members__.keys()), ['AAA', 'BBB', 'CCC', 'DDD', 'EEE'])
        self.assertSequenceEqual([value.value for value in Foobar.__members__.values()], [1, 2, 3, 4, 4])

        self.assertEqual(Foobar['EEE'], 'DDD')
        self.assertEqual(Foobar(4), 'DDD')
コード例 #9
0
def simulate_NHP(run_time, T, Y, dt_, track):
    #run_time = 30

    #T = np.arange((run_time * 0.9) * 5, dtype=float) / 5
    #Y = np.maximum(
    #    15 * np.sin(T) * (np.divide(np.ones_like(T),
    #                                np.sqrt(T + 1) + 0.1 * T)), 0.001)

    tf = TimeFunction((T, Y), dt=dt_)

    # We define a 1 dimensional inhomogeneous Poisson process with the
    # intensity function seen above
    in_poi = SimuInhomogeneousPoisson([tf],
                                      end_time=run_time,
                                      verbose=True,
                                      seed=3)  #, max_jumps=sum(Y))

    # We activate intensity tracking and launch simulation
    in_poi.track_intensity(track)
    in_poi.threshold_negative_intensity(allow=True)

    in_poi.simulate()

    # We plot the resulting inhomogeneous Poisson process with its
    # intensity and its ticks over time
    plot_point_process(in_poi)
    return list(in_poi.tracked_intensity[0]), list(
        in_poi.intensity_tracked_times)
コード例 #10
0
def get_AnsibleHostsDic(args):
    dic = {}
    pattern = r'^\s*\[.+\]'

    with open(args) as f:
        for line in f:
            temp = line.split()
            if temp:
                m = re.search(pattern, line)

                if (m is not None):
                    g = m.group().strip().strip('[').strip(']')
                    dic[g] = []
                else:
                    try:
                        dic[g].append(line)
                    except:
                        pass

    list_key = []
    dic_list = list(dic.items())
    list_group_key = list(dic.keys())
    for key in list_group_key:
        list_key.append(key[0])
    list_key_set = list(set(list_key))
    list_key_set.sort()
    list_group_key.sort()

    return dic_list, list_key_set, list_group_key
コード例 #11
0
ファイル: views.py プロジェクト: MikaPower/flutterDjango
def get_post_race(request, id=''):
    database_pilot = ""
    if request.method == 'POST':
        pilot = json.loads(request.body)

        try:
            database_pilot = Pilot.objects.filter(bike_name=pilot['bike_name'],
                                                  race_id=id).get()
            return HttpResponse(status=409)
        except ObjectDoesNotExist:
            race = Race.objects.filter(id=id).first()
            pilot = Pilot(name=pilot['name'],
                          bike_name=pilot['bike_name'],
                          engine_size=pilot['engine_size'],
                          race=race)
            pilot.save()
            race.pilot_set.add(pilot)
            #    str_data = serialize('json', race.pilot_set.all(), cls=DjangoJSONEncoder) # Or you don't need to provide the `cls` here because by default cls is DjangoJSONEncoder
            #   data = json.loads(str_data)
            # data = serializers.serialize("json", race.pilot_set.all())
            pilots = Pilot.objects.filter(id=pilot.id).values(
                'name', 'bike_name', 'engine_size', 'race_id')
            return JsonResponse({"pilot": list(pilots)})

    else:
        return JsonResponse(
            {"race": list(Race.objects.filter(id=id).values())})
コード例 #12
0
 def check(self):
     rep = dict()
     roots = list(self.roots())
     nodes = set(self.nodes[item].ident for item in self.nodes)
     parents = set(
         self.parent(item)
         for item in filter(lambda i: not self.is_root(i), self.nodes))
     children = list()
     for item in self.nodes:
         children.extend(self.children(item))
     children = set(children)
     rep['nonempty'] = self.size() > 0
     rep['single_root'] = len(roots) == 1
     rep['defined_ids'] = all(nodes)
     rep['unique_ids'] = len(nodes) == len(self.nodes)
     rep['valid_ids'] = nodes == set(self.nodes)
     rep['valid_parents'] = parents.issubset(self.nodes)
     rep['valid_children'] = children.issubset(self.nodes)
     rep['no_root_reference'] = children.isdisjoint(roots)
     rep['no_self_reference'] = all(
         self.parent(item) not in self.children(item)
         for item in self.nodes)
     rep['valid_links'] = all(item in self.children(self.parent(item))
                              for item in self.nodes
                              if self.parent(item) is not None)
     rep['traversable_data'] = set(self.nodes) == set(self.traverse())
     return rep
コード例 #13
0
 def test_sampen_logistic(self):
     # logistic map with r = 2.8 => static value
     data = list(datasets.logistic_map(0.45, 1000, r=2.8))
     self.assertAlmostEqual(0, nolds.sampen(data), delta=0.001)
     self.assertAlmostEqual(0,
                            nolds.sampen(data[100:], emb_dim=5),
                            delta=0.001)
     # logistic map with r = 3.3 => oscillation between two values
     data = list(datasets.logistic_map(0.45, 1000, r=3.3))
     self.assertAlmostEqual(0, nolds.sampen(data), delta=0.001)
     self.assertAlmostEqual(0,
                            nolds.sampen(data[100:], emb_dim=5),
                            delta=0.001)
     # logistic map with r = 3.5 => oscillation between four values
     data = list(datasets.logistic_map(0.45, 1000, r=3.5))
     self.assertAlmostEqual(0, nolds.sampen(data), delta=0.001)
     self.assertAlmostEqual(0,
                            nolds.sampen(data[100:], emb_dim=5),
                            delta=0.001)
     # logistic map with r = 3.9 => chaotic behavior
     data = list(datasets.logistic_map(0.45, 1000, r=3.9))
     self.assertAlmostEqual(0.5, nolds.sampen(data[100:]), delta=0.1)
     self.assertAlmostEqual(0.5,
                            nolds.sampen(data[100:], emb_dim=5),
                            delta=0.1)
コード例 #14
0
def test_list_sort_with(xs: List[str]):
    expected = sorted(xs, key=lambda x: x[1])
    ys: FrozenList[str] = frozenlist.of_seq(xs)
    func: Callable[[str], str] = lambda x: x[1]
    result = pipe(ys, frozenlist.sort_with(func))

    assert list(result) == list(expected)
コード例 #15
0
ファイル: KNN.py プロジェクト: Rorolas/Proyecto-Tesis
 def procesartexto(tweet):
     listatokenizada = preprocess(tweet)
     listatokenizada = list(set(listatokenizada))
     listaEliminar=[]
 
     for i in range(len(listatokenizada)):
         if es_numero(listatokenizada[i]):
             listaEliminar.append(listatokenizada[i])
         if len(listatokenizada[i])<=1:
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i].startswith('@'):
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i].startswith('x'):
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i].startswith('#'):
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i].startswith('http'):
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i] in str(stopwords):
             listaEliminar.append(listatokenizada[i])
         if listatokenizada[i] in listaemojis2:
             listaEliminar.append(listatokenizada[i])
 
     listaEliminar= list(set(listaEliminar))
     textoprocesado = ''
     for x in range(len(listaEliminar)):
         listatokenizada.remove(listaEliminar[x])
     for j in range(len(listatokenizada)):
         textoprocesado = textoprocesado +  ' '+  listatokenizada[j]
     del listatokenizada, listaEliminar
     return textoprocesado
コード例 #16
0
def dijkstra(G):
    """
    Dijkstra algorithm for finding shortest path from start position to end.
    """
    srcIdx = G.vex2idx[G.startpos]
    dstIdx = G.vex2idx[G.endpos]

    # build dijkstra
    nodes = list(G.neighbors.keys())
    dist = {node: float('inf') for node in nodes}
    prev = {node: None for node in nodes}
    dist[srcIdx] = 0

    while nodes:
        curNode = min(nodes, key=lambda node: dist[node])
        nodes.remove(curNode)
        if dist[curNode] == float('inf'):
            break

        for neighbor, cost in G.neighbors[curNode]:
            newCost = dist[curNode] + cost
            if newCost < dist[neighbor]:
                dist[neighbor] = newCost
                prev[neighbor] = curNode

    # retrieve path
    path = deque()
    curNode = dstIdx
    while prev[curNode] is not None:
        path.appendleft(G.vertices[curNode])
        curNode = prev[curNode]
    path.appendleft(G.vertices[curNode])
    return list(path)
コード例 #17
0
ファイル: C.py プロジェクト: nkymriy/AtCoder
def main():
    from builtins import int, map, list, print, min
    from collections import Counter
    import sys
    sys.setrecursionlimit(10**6)

    input = sys.stdin.readline
    input_str = (lambda: input().rstrip())
    input_list = (lambda: input().rstrip().split())
    input_number = (lambda: int(input()))
    input_number_list = (lambda: list(map(int, input_list())))

    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    N = input_number()
    S = [None] * N
    for i in range(N):
        S[i] = list(input_str())

    ans = ""
    for c in alphabet:
        t = 10**9
        for i in range(N):
            t = min(t, int(Counter(S[i])[c]))
        ans += c * t
    print(ans)
コード例 #18
0
ファイル: network.py プロジェクト: BrunoVandekerkhove/problog
 def __init__(self, factors={}):
     self.__factors = factors
     self.variables = list(factors.keys())
     self.__varidx = list(
         map(
             lambda x: x + 1,
             accumulate([0] +
                        [len(self.values(var)) for var in self.variables])))
コード例 #19
0
def test_collect_distributions():
    distributions = list(collect.collect_distributions(['pytest-nodev']))
    assert len(distributions) == 1
    _, module_names = distributions[0]
    assert len(module_names) == 1
    assert len(
        list(collect.collect_distributions(['non_existent_distribution'
                                            ]))) == 0
コード例 #20
0
ファイル: test_frozenlist.py プロジェクト: mlw214/Expression
def test_list_append(xs: List[int], ys: List[int]):
    expected = xs + ys
    fx = frozenlist.of_seq(xs)
    fy = frozenlist.of_seq(ys)
    fz = fx.append(fy)
    fh = fx + fy

    assert list(fz) == list(fh) == expected
コード例 #21
0
ファイル: test_frozenlist.py プロジェクト: mlw214/Expression
def test_list_indexed(xs: List[int]):

    expected = list(enumerate(xs))

    ys: FrozenList[int] = frozenlist.of_seq(xs)
    zs = frozenlist.indexed(ys)

    assert list(zs) == expected
コード例 #22
0
def test_import_distributions():
    distributions = [('pytest-nodev', ['pytest_nodev'])]
    module_names = list(collect.import_distributions(distributions))
    assert module_names == ['pytest_nodev']

    distributions = [('pytest-nodev', ['non_existent_module'])]
    module_names = list(collect.import_distributions(distributions))
    assert module_names == []
コード例 #23
0
def test_import_distributions():
    distributions = [('pytest-nodev', ['pytest_nodev'])]
    module_names = list(collect.import_distributions(distributions))
    assert module_names == ['pytest_nodev']

    distributions = [('pytest-nodev', ['non_existent_module'])]
    module_names = list(collect.import_distributions(distributions))
    assert module_names == []
コード例 #24
0
ファイル: test_frozenlist.py プロジェクト: mlw214/Expression
def test_list_filter(xs: List[int], limit: int):
    expected = filter(lambda x: x < limit, xs)

    ys: FrozenList[int] = frozenlist.of_seq(xs)
    predicate: Callable[[int], bool] = lambda x: x < limit
    result = pipe(ys, frozenlist.filter(predicate))

    assert list(result) == list(expected)
コード例 #25
0
ファイル: test_frozenlist.py プロジェクト: mlw214/Expression
def test_list_unfold(x: int):
    def unfolder(state: int) -> Option[Tuple[int, int]]:
        if state < x:
            return Some((state, state + 1))
        return Nothing

    result = FrozenList.unfold(unfolder, 0)

    assert list(result) == list(range(x))
コード例 #26
0
 def parse_variables(self):
     vars = re.search(r"[(].+[)]", self.query)
     if vars:
         vars_str = vars.group()[1:-1]
         variables = vars_str.replace(" ", "").split(",")
         variables = list(map(self.right_type, variables))
         return variables
     else:
         return list()
コード例 #27
0
ファイル: plots.py プロジェクト: gfekete/pugnlp
def join_spans(spans):
    spans = list(spans)
    joined_spans = [list(spans[0])]
    for i, (start, stop) in enumerate(spans[1:]):
        if start > joined_spans[i][1]:
            joined_spans += [[start, stop]]
        else:
            joined_spans[i - 1][1] = stop
    return joined_spans
コード例 #28
0
    def AddFile(self, jsonIn):
        for index in range(len(jsonIn)):
            if not jsonIn[index]:
                continue
            peakData = jsonIn[index]["peak"]
            riseAndTimeStrList = peakData.split(",")
            if len(riseAndTimeStrList) < 2:
                continue

            transactionData = jsonIn[index]["transactionList"]
            peakSize = len(riseAndTimeStrList)
            transactionDataSize = len(transactionData)
            if peakSize != transactionDataSize:
                print(peakSize, " ", transactionDataSize)
                return
            riseAndTimeList = []
            skipIndexes = []
            for x in range(peakSize):
                riseMinute = RiseMinute(riseAndTimeStrList[x])
                if len(riseAndTimeList) > 0 and riseAndTimeList[
                        -1].rise * riseMinute.rise > 0:
                    skipIndexes.append(x - 1)
                    riseAndTimeList[-1] = riseMinute
                else:
                    riseAndTimeList.append(riseMinute)

            newTransParams = []
            for i in range(len(transactionData)):
                if i in skipIndexes:
                    continue
                newTransParams.append(transactionData[i])

            transactionData = newTransParams

            startIndex = GetStartIndex(transactionData)
            if startIndex == -1:
                return

            riseList = list(map(lambda x: float(x.rise), riseAndTimeList))
            timeList = list(map(lambda x: float(x.time), riseAndTimeList))

            for index in range(startIndex, len(transactionData)):
                if index < 8:
                    continue
                if PeakFeatureCount > 0:
                    curPriceList = riseList[index + 1 -
                                            PeakFeatureCount:index + 1]
                    curTimeList = timeList[index + 1 - PeakFeatureCount:index +
                                           1]
                else:
                    curPriceList = []
                    curTimeList = []
                isBottom = riseList[index] < 0
                handler = PeakHandler(transactionData[index], isBottom,
                                      self.transactionParam, curPriceList,
                                      curTimeList)
                self.handlerList.append(handler)
コード例 #29
0
def resample(morph, res):
    m = morph.copy()
    count = max(m.nodes.keys()) + 1
    for stem in morph.stems():
        for sec in morph.sections(stem):
            length = sum(m.length(item) for item in sec)
            pttype = m.type(sec[0])
            parent = m.parent(sec[0])
            idents = [parent] + sec if not m.is_root(parent) else sec
            sec_coords = np.array(list(m.coord(item) for item in idents))
            sec_radii = np.array(list(m.radius(item) for item in idents))
            new_coords, new_radii = _sample(sec_coords, sec_radii, res)
            if len(new_coords) > 0:
                if m.is_root(parent):
                    new_coords = np.insert(new_coords,
                                           0,
                                           m.coord(sec[0]),
                                           axis=0)
                    new_radii = np.insert(new_radii,
                                          0,
                                          m.radius(sec[0]),
                                          axis=0)
                for item in sec[:-1]:
                    m.remove(item)
                item = sec[-1]
                for coord, radius in zip(new_coords[-1::-1],
                                         new_radii[-1::-1]):
                    node = Node(count)
                    node.value = [pttype, coord, radius]
                    m.insert(item, node)
                    item = count
                    count += 1
            else:
                start = Node(count)
                start.value = [
                    m.type(sec[0]),
                    m.coord(sec[0]),
                    m.radius(sec[0])
                ]
                count += 1
                end = Node(count)
                end.value = [
                    m.type(sec[-1]),
                    m.coord(sec[-1]),
                    m.radius(sec[-1])
                ]
                count += 1
                if len(sec) > 1:
                    for item in sec[:-1]:
                        m.remove(item)
                if m.is_root(parent):
                    m.insert(sec[-1], start)
                m.insert(sec[-1], end)
                m.remove(sec[-1])
    m.renumber()
    return m
コード例 #30
0
    def get_variable_list(self):
        results = list()

        for tf_file in pathlib.Path(self.working_dir).glob("*.tf"):
            with open(tf_file, "r") as fp:
                terraform_file_dict = hcl2.load(fp)
                results += terraform_file_dict[
                    "variable"] if "variable" in terraform_file_dict else list(
                    )

        return list(map(lambda d: next(iter(d)), results))
コード例 #31
0
ファイル: saleae.py プロジェクト: jrast/python-saleae
	def get_connected_devices(self):
		devices = self._cmd('GET_CONNECTED_DEVICES')
		self.connected_devices = []
		for dev in devices.split('\n')[:-1]:
			active = False
			try:
				index, name, type, id, active = list(map(str.strip, dev.split(',')))
			except ValueError:
				index, name, type, id = list(map(str.strip, dev.split(',')))
			self.connected_devices.append(ConnectedDevice(type, name, id, index, active))
		return self.connected_devices
コード例 #32
0
ファイル: saleae.py プロジェクト: michal13wat/saleae_capture
	def get_active_channels(self):
		'''Get the active digital and analog channels.
		:returns: A 2-tuple of lists of integers, the active digital and analog channels respectively'''
		channels = self._cmd('GET_ACTIVE_CHANNELS')
		msg = list(map(str.strip, channels.split(',')))
		assert msg.pop(0) == 'digital_channels'
		i = msg.index('analog_channels')
		digital = list(map(int, msg[:i]))
		analog = list(map(int, msg[i+1:]))

		return digital, analog
コード例 #33
0
 def get_subspaces(self):
     """
     return a list of subspaces for this setup
     """
     subspaces_list = list()
     subspaces = Subspace.objects.filter(setup_id=self.setup).order_by('id')
     for subspace in subspaces:
         subspace_features = list()
         subspace_features.append(subspace.feature_x_id)
         subspace_features.append(subspace.feature_y_id)
         subspaces_list.append(subspace_features)
     return subspaces_list
コード例 #34
0
 def _check1(self, s):
     self.failUnlessEqual(list(s), [(3, 4)])
     self.failUnless(s)
     self.failUnlessEqual(s.len(), 4)
     self.failIf((0, 1) in s)
     self.failUnless((3, 4) in s)
     self.failUnless((3, 1) in s)
     self.failUnless((5, 2) in s)
     self.failUnless((6, 1) in s)
     self.failIf((6, 2) in s)
     self.failIf((7, 1) in s)
     self.failUnlessEqual(list(s.each()), [3, 4, 5, 6])
コード例 #35
0
def build_probability_matrix(probs_as_strings):
    """
    Build the matrix
    :param probs_as_strings:
    :return:
    """

    matrix = dict()

    matrix['A'] = list(map(float, probs_as_strings[0].split(' ')))
    matrix['C'] = list(map(float, probs_as_strings[1].split(' ')))
    matrix['G'] = list(map(float, probs_as_strings[2].split(' ')))
    matrix['T'] = list(map(float, probs_as_strings[3].split(' ')))

    return matrix
コード例 #36
0
ファイル: message.py プロジェクト: ashleyse2016/SpamPAD
    def _parse_message(self):
        """Parse the message."""
        self._hook_check_start()
        # Dump the message raw headers
        for name, raw_value in self.msg._headers:
            self.raw_headers[name].append(raw_value)

        # XXX This is strange, but it's what SA does.
        # The body starts with the Subject header(s)
        body = list(self.get_decoded_header("Subject"))
        raw_body = list()
        for payload, part in self._iter_parts(self.msg):
            # Extract any MIME headers
            for name, raw_value in part._headers:
                self.raw_mime_headers[name].append(raw_value)
            text = None
            if payload is not None:
                # this must be a text part
                self.uri_list.update(set(URL_RE.findall(payload)))
                if part.get_content_subtype() == "html":
                    text = self.normalize_html_part(payload.replace("\n", " "))
                    text = " ".join(text)
                    body.append(text)
                    raw_body.append(payload)
                else:
                    text = payload.replace("\n", " ")
                    body.append(text)
                    raw_body.append(payload)
            self._hook_extract_metadata(payload, text, part)
        self.text = " ".join(body)
        self.raw_text = "\n".join(raw_body)
        self._parse_sender()
        received_headers = self.get_decoded_header("Received")
        for header in self.ctxt.conf["originating_ip_headers"]:
            headers = ["X-ORIGINATING-IP: %s" % x
                       for x in self.get_decoded_header(header)]
            received_headers.extend(headers)
        received_obj = ReceivedParser(received_headers)
        self.received_headers = received_obj.received
        self._parse_relays(self.received_headers)

        try:
            self._create_plugin_tags(self.received_headers[0])
        except IndexError:
            pass

        for header in self.received_headers:
            self.hostname_with_ip.append((header["rdns"], header["ip"]))
コード例 #37
0
def test_generate_objects_from_modules():
    import re
    modules = {'pytest_nodev.collection': collect, 're': re}
    include_patterns = ['pytest_nodev.collection:generate_objects_from_modules']
    objs = collect.generate_objects_from_modules(
        modules, include_patterns, module_blacklist_pattern='re')
    assert len(list(objs)) == 1
コード例 #38
0
ファイル: longslit.py プロジェクト: adwasser/deimos-longslit
def reduce_files(files, save=True, plot=True):

    for f in files:
        
        print("Cleaning", f)
        clean_name = f.split('.')[0] + '.clean.fits'
        if os.path.exists(clean_name):
            clean = fits.getdata(clean_name)
        else:
            clean = normalize(f, output=clean_name)
        continue
        print("Tracing", f)
        trace_spl, sigma_spl = ap_trace(clean)
        
        print("Extracting aperture and sky subtracting", f)
        ap, sky, unc = ap_extract(clean, trace_spl, sigma_spl)
        
        print("Fitting wavelength solution", f)
        wfunc = wavelength_solution(trace_spl, sigma_spl, "normed_NeArKrXe.fits")

        y = np.arange(ap.size)
        w = wfunc(y)
        if save:
            header = "Spectrum extracted from " + f + "\nAngstroms\tFlux"
            write_array = list(zip(w, ap - sky, unc))
            np.savetxt(f.split('.')[0] + ".dat", write_array, header=header)
        if plot:
            plt.clf()
            plt.plot(wfunc(y), ap - sky, 'k-')
            plt.xlabel("Wavelength (Angstroms)")
            plt.ylabel("Relatived flux (arbitrary units)")
            plt.show()
コード例 #39
0
ファイル: collect.py プロジェクト: AndreaCrotti/pytest-nodev
def collect_stdlib_distributions():
    """Yield a conventional spec and the names of all top_level standard library modules."""
    distribution_spec = 'Python==%d.%d.%d' % sys.version_info[:3]
    stdlib_path = sysconfig.get_python_lib(standard_lib=True)
    distribution_top_level = [name for _, name, _ in pkgutil.iter_modules(path=[stdlib_path])]
    distribution_top_level += list(sys.builtin_module_names)
    yield distribution_spec, distribution_top_level
コード例 #40
0
ファイル: views.py プロジェクト: BillKing94/GustavlePlusPlus
def user_images(request, user_id):
    assert isinstance(request, HttpRequest)
    user = get_object_or_404(AppUser, pk=user_id)
    isFriend = request.user.is_friends_with(user)
    if not (isFriend or request.user == user):
        return HttpResponseForbidden()
    requestSent = request.user.sent_requests.filter(user_to=user).exists()
    requestReceived = request.user.received_requests.filter(user_from=user).exists()
    images = user.images.all().order_by('-date_added')

    circleInfo = list()
    for circle in request.user.owned_circles.all():
        info = {
            'name': circle.name,
            'is_member': circle.members.filter(id=user.id).exists()
        }
        circleInfo.append(info)

    return render(request,
        'app/userimages.html',
        context_instance = RequestContext(request,
        {
            'title': user.full_name(),
            'page_user': user,
            'images': images,
            'is_friend': isFriend,
            'circle_info': circleInfo,
            'request_sent': requestSent,
            'request_received': requestReceived,
            'year': datetime.now().year
        })
    )
コード例 #41
0
    def _update_font(self):
        px_size = 2
        px_space = 2

        lcd_bg = QtGui.qRgb(0, 0, 20)
        lcd_off = QtGui.qRgb(60, 40, 20)
        lcd_on = QtGui.qRgb(250, 220, 20)

        def render_char(c):
            # Create QImage
            im = QtGui.QImage(
                5*(px_size+px_space) + px_space,
                8*(px_size+px_space) + px_space,
                QtGui.QImage.Format_RGB32
            )
            im.fill(lcd_bg)

            p = QtGui.QPainter()
            assert p.begin(im)
            for r_idx, r_def in enumerate((list(c) + [0]*8)[:8]):
                for c_idx in range(5):
                    c = lcd_off if r_def & (1<<(4-c_idx)) == 0 else lcd_on
                    p.fillRect(
                        (px_space+px_size)*c_idx + px_space,
                        (px_space+px_size)*r_idx + px_space,
                        px_size, px_size, c
                    )
            p.end()

            return im

        # render char rom font
        self._font = list(render_char(c) for c in CHAR_ROM)
        self.updateGeometry()
コード例 #42
0
def draw_all_training( dataDirectory ):
    test_samples = draw_test_samples( dataDirectory )

    availableGames = []
    fileinfos = index_processor.get_fileInfos( dataDirectory )
    for fileinfo in fileinfos:
        filename = fileinfo['filename']
        year = int( filename.split('-')[1].split('_')[0] )
        if year > 2014:
            continue  # ignore after 2014, to keep the set of games fixed
        numgames = fileinfo['numGames']
        for i in range( numgames ):
            availableGames.append( ( filename, i ) )
    print( 'total num games: ' + str( len( availableGames ) ) )

    # need to seed random first
    random.seed(0)
    # I suppose the first 100 samples will be the testing ones :-P
    # anyway, just skip those....
    
    samplesSet = set()
    for sample in availableGames:
        if sample not in test_samples:
            samplesSet.add( sample )
    print( 'Drawn all samples, ie ' + str( len( samplesSet ) ) + ' samples:' )
    # copy to list
    samples = list( samplesSet )
    return samples
コード例 #43
0
ファイル: base.py プロジェクト: SpamExperts/SpamPAD
    def get_rule_kwargs(data):
        """Extract the keyword arguments necessary to create a new instance
        for this class.
        """
        kwargs = dict()
        try:
            kwargs["score"] = list(map(float, data["score"].strip().split()))
        except KeyError:
            pass
        try:
            kwargs["desc"] = data["describe"].strip()
        except KeyError:
            pass
        try:
            kwargs["priority"] = data["priority"].strip()
        except KeyError:
            pass
        try:
            if data["tflags"]:
                kwargs["tflags"] = []
            for flag in data["tflags"]:
                kwargs["tflags"].append(flag.strip())

        except KeyError:
            pass
        return kwargs
コード例 #44
0
def test_collect_installed_distributions():
    installed_distributions = list(collect.collect_installed_distributions())
    assert len(installed_distributions) > 1
    for spec, module_names in installed_distributions:
        if spec.startswith('pytest-nodev'):
            break
    assert module_names == ['pytest_nodev']
コード例 #45
0
def main(argv=None):
    """
    :param argv: the command line args
    :return: nothing
    """
    if argv is None:
        argv = sys.argv

    # data = "0 71 87 99 99 99 101 103 113 114 115 128 128 128 129 129 147 147 163 163 163 172 199 202 216 216 228 228 241 243 243 246 256 261 262 262 264 277 300 310 310 315 315 315 327 331 335 344 345 356 371 371 376 391 409 409 409 411 418 424 424 428 442 443 444 444 444 459 463 478 482 484 499 510 523 523 523 531 538 543 543 547 558 570 572 572 581 587 587 591 607 610 612 625 646 652 659 660 670 671 673 683 686 686 686 686 687 706 706 709 715 738 739 744 754 759 774 784 785 786 787 788 809 814 815 815 833 833 834 837 853 853 858 868 872 885 887 887 902 902 903 914 922 932 934 943 947 952 956 967 981 986 986 996 1000 1001 1002 1005 1014 1030 1031 1031 1050 1050 1061 1069 1070 1080 1094 1095 1097 1101 1114 1115 1115 1130 1130 1130 1133 1148 1149 1159 1165 1168 1183 1193 1196 1197 1197 1202 1224 1229 1229 1230 1233 1243 1258 1261 1267 1277 1278 1293 1296 1296 1296 1311 1311 1312 1325 1329 1331 1332 1346 1356 1357 1365 1376 1376 1395 1395 1396 1412 1421 1424 1425 1426 1430 1440 1440 1445 1459 1470 1474 1479 1483 1492 1494 1504 1512 1523 1524 1524 1539 1539 1541 1554 1558 1568 1573 1573 1589 1592 1593 1593 1611 1611 1612 1617 1638 1639 1640 1641 1642 1652 1667 1672 1682 1687 1688 1711 1717 1720 1720 1739 1740 1740 1740 1740 1743 1753 1755 1756 1766 1767 1774 1780 1801 1814 1816 1819 1835 1839 1839 1845 1854 1854 1856 1868 1879 1883 1883 1888 1895 1903 1903 1903 1916 1927 1942 1944 1948 1963 1967 1982 1982 1982 1983 1984 1998 2002 2002 2008 2015 2017 2017 2017 2035 2050 2055 2055 2070 2081 2082 2091 2095 2099 2111 2111 2111 2116 2116 2126 2149 2162 2164 2164 2165 2170 2180 2183 2183 2185 2198 2198 2210 2210 2210 2224 2227 2254 2263 2263 2263 2279 2279 2297 2297 2298 2298 2298 2311 2312 2313 2323 2325 2327 2327 2327 2339 2355 2426"
    # n = 358
    # data_as_list = list(map(int, data.split(' ')))
    #
    # result = leaderboard_sequence(data_as_list, n, _all_masses)



    data = "114 1199 245 1312 358 128 356 922 702 709 1184 1053 959 373 959 724 1087 587 603 131 0 1298 472 1184 840 595 356 1289 128 131 99 845 1058 230 1070 586 583 1426 455 114 1068 700 817 484 1062 472 344 368 686 1167 227 1295 99 1327 475 341 364 1198 823 1295 1181 831 726 1070 1181 467 504 1186 598 228 839 345 259 240 1196 828 495 1312 954 843 712 1190 840 242 823 1085 114 1327 942 717 358 609 695 245 482 823 603 1068 1050 967 586 1298 472 581 242 1298 944 740 231 951 931 376 1199 596 128 1195 103 954 714 467 830 1082 137 236 339 1312 971 731 954 459 603 1323 227 1081"
    m = 16
    n = 330

    start = time.clock()

    data_as_list = list(map(int, data.split(' ')))
    result = convolution_cyclopeptide_sequencing(data_as_list, m, n)

    end = time.clock()

    print(end - start)

    print ("-".join(map(str, result)))
コード例 #46
0
def draw_samples( dataDirectory, numSamples ):
    # draws filename, and game index number, from the available games
    # without replacement (so we should check for dupes :-( )

    # first we should create a single list, containing pairs of ( filename, gameindex )
    # then we will draw samples from this
    # we should restrict the available games to something static, eg everything up to dec 2014, inclusive
    availableGames = []
    fileinfos = index_processor.get_fileInfos( dataDirectory )
    for fileinfo in fileinfos:
        filename = fileinfo['filename']
        year = int( filename.split('-')[1].split('_')[0] )
        if year > 2014:
            continue  # ignore after 2014, to keep the set of games fixed
        numgames = fileinfo['numGames']
        for i in range( numgames ):
            availableGames.append( ( filename, i ) )
    print( 'total num games: ' + str( len( availableGames ) ) )

    # need to seed random first
    random.seed(0)
    
    samplesSet = set()
    while len( samplesSet ) < numSamples:
        sample = random.choice( availableGames )
        if sample not in samplesSet:
            samplesSet.add( sample )
    print( 'Drawn ' + str( numSamples ) + ' samples:' )
    # copy to list
    samples = list( samplesSet )
    return samples
コード例 #47
0
ファイル: message.py プロジェクト: SpamExperts/SpamPAD
 def get_all_addr_header(self, header_name):
     """Get a list of all the addresses from this header."""
     values = list()
     for value in self.get_decoded_header(header_name):
         for dummy, addr in email.utils.getaddresses([value]):
             if addr:
                 values.append(addr)
     return values
コード例 #48
0
ファイル: core.py プロジェクト: MarcMeszaros/envitro
def _str_to_list(value, separator):
    """Convert a string to a list with sanitization."""
    value_list = [item.strip() for item in value.split(separator)]
    value_list_sanitized = builtins.list(filter(None, value_list))
    if len(value_list_sanitized) > 0:
        return value_list_sanitized
    else:
        raise ValueError("Invalid list variable.")
コード例 #49
0
ファイル: json_reporter.py プロジェクト: cosmicexplorer/pants
  def _render_messages(self, *msg_elements):
    def _message_details(element):
      if isinstance(element, string_types):
        element = [element]

      text, detail = (x or y for x, y in zip_longest(element, ('', None)))
      return {'text': text, 'detail': detail}

    return list(map(_message_details, msg_elements))
コード例 #50
0
ファイル: message.py プロジェクト: SpamExperts/SpamPAD
    def get_decoded_header(self, header_name):
        """Get a list of decoded headers with this name."""
        values = list()
        for value in self.get_raw_header(header_name):
            values.append(self._decode_header(value))

        for value in self.get_headers(header_name):
            values.append(value)
        return values
コード例 #51
0
ファイル: message.py プロジェクト: ashleyse2016/SpamPAD
 def get_name_header(self, header_name):
     """Get a list of the first names from this header."""
     values = list()
     for value in self.get_decoded_header(header_name):
         for name, dummy in email.utils.getaddresses([value]):
             if name:
                 values.append(name)
                 break
     return values
コード例 #52
0
ファイル: saleae.py プロジェクト: jrast/python-saleae
	def get_all_sample_rates(self):
		'''Get available sample rate combinations for the current performance level and channel combination.'''
		rates = self._cmd('GET_ALL_SAMPLE_RATES')
		self.sample_rates = []
		for line in rates.split('\n'):
			if len(line):
				digital, analog = list(map(int, map(str.strip, line.split(','))))
				self.sample_rates.append((digital, analog))
		return self.sample_rates
コード例 #53
0
ファイル: message.py プロジェクト: sorinsrn7/SpamPAD
    def _parse_message(self):
        """Parse the message."""
        self._hook_check_start()
        # Dump the message raw headers
        for name, raw_value in self.msg._headers:
            self.raw_headers[name].append(raw_value)

        # XXX This is strange, but it's what SA does.
        # The body starts with the Subject header(s)
        body = list(self.get_decoded_header("Subject"))
        raw_body = list()
        for payload, part in self._iter_parts(self.msg):
            # Extract any MIME headers
            for name, raw_value in part._headers:
                self.raw_mime_headers[name].append(raw_value)
            text = None
            if payload is not None:
                # this must be a text part
                self.uri_list.update(set(URL_RE.findall(payload)))
                if part.get_content_subtype() == "html":
                    text = self.normalize_html_part(payload.replace("\n", " "))
                    text = " ".join(text)
                    body.append(text)
                    raw_body.append(payload)
                else:
                    text = payload.replace("\n", " ")
                    body.append(text)
                    raw_body.append(payload)
            self._hook_extract_metadata(payload, text, part)
        self.text = " ".join(body)
        self.raw_text = "\n".join(raw_body)
        self._parse_sender()

        for value in self.get_received_headers("Received"):
            if 'from' in value:
                hostname = value.split(' ')[1]
                ip = IPFRE.search(value).group()
                clean_ip = ip.strip("[ ]();\n")
                try:
                    self.hostname_with_ip.append((hostname, clean_ip))
                except ValueError:
                    continue
コード例 #54
0
 def loadGenes(self,filename):
     transcripts=self.loadGFF(filename)
     genes=set()
     for transcript in transcripts:
         gene=transcript.getGene()
         if(not gene):
             raise Exception("transcript "+transcript.getID()+" has no gene")
         genes.add(gene)
     genes=list(genes)
     genes.sort(key=lambda gene: gene.getBegin())
     return genes
コード例 #55
0
ファイル: message.py プロジェクト: sorinsrn7/SpamPAD
 def get_header_ips(self):
     values = list()
     for value in self.get_received_headers("Received"):
         ips = IPFRE.findall(value)
         for ip in ips:
             clean_ip = ip.strip("[ ]();\n")
             try:
                 values.append(ipaddress.ip_address(clean_ip))
             except ValueError:
                 continue
     return values
コード例 #56
0
ファイル: message.py プロジェクト: ashleyse2016/SpamPAD
 def normalize_html_part(payload):
     """Strip all HTML tags."""
     data = list()
     stripper = _ParseHTML(data)
     try:
         stripper.feed(payload)
     except (UnicodeDecodeError, html.parser.HTMLParseError):
         # We can't parse the HTML, so just strip it.  This is still
         # better than including generic HTML/CSS text.
         pass
     return data
コード例 #57
0
ファイル: saleae.py プロジェクト: kevinvalk/python-saleae
	def get_active_channels(self):
		'''Get the active digital and analog channels.

		:returns: A 2-tuple of lists of integers, the active digital and analog channels respectively

		>>> s.get_active_channels()
		([0, 1, 2, 3], [0])
		'''
		channels = self._cmd('GET_ACTIVE_CHANNELS')
		# Work around possible bug in Logic8
		# https://github.com/ppannuto/python-saleae/pull/19
		while ('TRUE' == channels):
			time.sleep(0.1)
			channels = self._cmd('GET_ACTIVE_CHANNELS')
		msg = list(map(str.strip, channels.split(',')))
		assert msg.pop(0) == 'digital_channels'
		i = msg.index('analog_channels')
		digital = list(map(int, msg[:i]))
		analog = list(map(int, msg[i+1:]))

		return digital, analog
コード例 #58
0
ファイル: tutil.py プロジェクト: totalgood/pug-nlp
def make_datetime(dt, date_parser=parse_date):
    """Coerce a datetime or string into datetime.datetime object

    Arguments:
      dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
        to be coerced into a `datetime.date` object

    Returns:
      datetime.time: Time of day portion of a `datetime` string or object

    >>> make_date('')
    datetime.date(1970, 1, 1)
    >>> make_date(None)
    datetime.date(1970, 1, 1)
    >>> make_date("11:59 PM") == datetime.date.today()
    True
    >>> make_date(datetime.datetime(1999, 12, 31, 23, 59, 59))
    datetime.date(1999, 12, 31)
    >>> make_datetime(['1970-10-31', '1970-12-25'])  # doctest: +NORMALIZE_WHITESPACE
    [datetime.datetime(1970, 10, 31, 0, 0), datetime.datetime(1970, 12, 25, 0, 0)]
    """
    if (isinstance(dt, (datetime.datetime, datetime.date, datetime.time, pd.Timestamp, np.datetime64)) or
            dt in (float('nan'), float('inf'), float('-inf'), None, '')):
        return dt
    if isinstance(dt, (float, int)):
        return datetime_from_ordinal_float(dt)
    if isinstance(dt, datetime.date):
        return datetime.datetime(dt.year, dt.month, dt.day)
    if isinstance(dt, datetime.time):
        return datetime.datetime(1, 1, 1, dt.hour, dt.minute, dt.second, dt.microsecond)
    if not dt:
        return datetime.datetime(1970, 1, 1)
    if isinstance(dt, basestring):
        try:
            return date_parser(dt)
        except:
            print('Unable to make_datetime({})'.format(dt))
            raise
    try:
        return datetime.datetime(*dt.timetuple()[:7])
    except:
        try:
            dt = list(dt)
            if 0 < len(dt) < 7:
                try:
                    return datetime.datetime(*dt[:7])
                except:
                    pass
        except:  # TypeError
            # dt is not iterable
            return dt

    return [make_datetime(val, date_parser=date_parser) for val in dt]
コード例 #59
0
ファイル: views.py プロジェクト: BillKing94/GustavlePlusPlus
def api_list_images(request):
    assert(isinstance(request, HttpRequest))
    if request.user.is_authenticated():
        imageList = list()
        for image in request.user.images.all():
            imageList.append({
                'id': image.id
            })

        jsonResults = json.dumps(imageList)
        return HttpResponse(jsonResults, content_type="application/json")
    return HttpResponseForbidden()
コード例 #60
0
ファイル: saleae.py プロジェクト: kevinvalk/python-saleae
	def get_connected_devices(self):
		'''Get a list of attached Saleae devices.

		Note, this will never be an empty list. If no actual Saleae devices are
		connected, then Logic will return the four fake devices shown in the
		example.

		:returns: A list of ``saleae.ConnectedDevice`` objects

		>>> s.get_connected_devices() #doctest:+ELLIPSIS
		[<saleae.ConnectedDevice #1 LOGIC_4_DEVICE Logic 4 (...) **ACTIVE**>, <saleae.ConnectedDevice #2 LOGIC_8_DEVICE Logic 8 (...)>, <saleae.ConnectedDevice #3 LOGIC_PRO_8_DEVICE Logic Pro 8 (...)>, <saleae.ConnectedDevice #4 LOGIC_PRO_16_DEVICE Logic Pro 16 (...)>]
		'''
		devices = self._cmd('GET_CONNECTED_DEVICES')
		self.connected_devices = []
		for dev in devices.split('\n')[:-1]:
			active = False
			try:
				index, name, type, id, active = list(map(str.strip, dev.split(',')))
			except ValueError:
				index, name, type, id = list(map(str.strip, dev.split(',')))
			self.connected_devices.append(ConnectedDevice(type, name, id, index, active))
		return self.connected_devices