Example #1
2
 def debug(self, msg, traceback=1):
     msg = str(msg)
     curframe = None
     """
     for x in xrange(0,100):
         frame = inspect.currentframe(x)
         print "trying frame["+str(x)+"]"
         if frame.f_back is None:
             print "this frame is none, will use frame["+str(x-1)+"] instead"
             break
         else:
             curframe = frame
             lineno = curframe.f_lineno
     """
     curframe = inspect.currentframe(traceback)
     lineno = curframe.f_lineno
     self.curframe = curframe
     frame_code = curframe.f_code
     frame_globals = curframe.f_globals
     functype = type(lambda: 0)
     funcs = []
     for func in gc.get_referrers(frame_code):
         if type(func) is functype:
             if getattr(func, "func_code", None) is frame_code:
                 if getattr(func, "func_globals", None) is frame_globals:
                     funcs.append(func)
                     if len(funcs) > 1:
                         return None
         cur_method = funcs[0].func_name if funcs else ""
     for line in msg.split("\n"):
         self.tester.debug("(" + str(cur_method) + ":" + str(lineno) + "): " + line.strip())
Example #2
1
 def serialize(self, buff):
     """
 serialize message into buffer
 :param buff: buffer, ``StringIO``
 """
     try:
         _x = self.agent_one
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         buff.write(struct.pack("<I%ss" % length, length, _x))
         _x = self.agent_two
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         buff.write(struct.pack("<I%ss" % length, length, _x))
         _x = self
         buff.write(
             _struct_6d.pack(_x.rotationx, _x.rotationy, _x.angle, _x.referencex, _x.referencey, _x.evaluation)
         )
     except struct.error as se:
         self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
     except TypeError as te:
         self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
Example #3
1
def detect_nan(i, node, fn):
    for output in fn.outputs:
        if not isinstance(output[0], np.random.RandomState) and not (
            hasattr(node, "op")
            or isinstance(
                node.op, (theano.sandbox.rng_mrg.GPU_mrg_uniform, theano.sandbox.cuda.basic_ops.GpuAllocEmpty)
            )
        ):
            try:
                has_nans = np.isnan(output[0]).any() or np.isinf(output[0]).any()
            except TypeError:
                has_nans = False
            if not has_nans:
                continue
            print ("*** NaN detected ***")
            theano.printing.debugprint(node, depth=3)
            print (type(node), node.op, type(node.op))
            print ("Inputs : %s" % [input[0] for input in fn.inputs])
            print "Input shape", [input[0].shape for input in fn.inputs]
            print ("Outputs: %s" % [output[0] for output in fn.outputs])
            print "Output shape", [output[0].shape for output in fn.outputs]
            print "NaN # :", [np.sum(np.isnan(output[0])) for output in fn.outputs]
            print "Inf # :", [np.sum(np.isinf(output[0])) for output in fn.outputs]
            print "NaN location: ", np.argwhere(np.isnan(output[0])), ", Inf location: ", np.argwhere(
                np.isinf(output[0])
            )
            import pdb

            pdb.set_trace()
            raise ValueError
Example #4
1
def expect_model_param(models, attribute_name, expected_values):
    print "param: {0}".format(attribute_name)
    actual_values = list(
        set(
            [
                m.params[attribute_name]["actual"]
                if type(m.params[attribute_name]["actual"]) != list
                else m.params[attribute_name]["actual"][0]
                for m in models.models
            ]
        )
    )
    # possible for actual to be a list (GLM)
    if type(expected_values) != list:
        expected_values = [expected_values]
    # limit precision. Rounding happens in some models like RF
    actual_values = [x if isinstance(x, basestring) else round(float(x), 5) for x in actual_values]
    expected_values = [x if isinstance(x, basestring) else round(float(x), 5) for x in expected_values]
    print "actual values: {0}".format(actual_values)
    print "expected values: {0}".format(expected_values)
    actual_values_len = len(actual_values)
    expected_values_len = len(expected_values)
    assert actual_values_len == expected_values_len, "Expected values len: {0}. Actual values len: " "{1}".format(
        expected_values_len, actual_values_len
    )
    diff = set(actual_values) - set(expected_values)
    assert len(diff) == 0, "Difference between actual and expected values: {0}".format(diff)
Example #5
1
    def function_convolution(self, dist_1, dist_2, bins=50):
        a_1, b_1, a_2, b_2 = 0, 0, 0, 0
        if dist_1 in self.bounds:
            a_1, b_1 = self.bounds[dist_1]
        else:
            a_1, b_1 = calculate_bounds_of_probability_distribution(dist_1)
            self.bounds[dist_1] = a_1, b_1
        if dist_2 in self.bounds:
            a_2, b_2 = self.bounds[dist_2]
        else:
            a_2, b_2 = calculate_bounds_of_probability_distribution(dist_2)
            self.bounds[dist_2] = a_2, b_2

        if (type(dist_1.dist), type(dist_2.dist)) == (uniform_gen, uniform_gen):
            return self.function_convolution_uniform((a_1, b_1), (a_2, b_2))

        convolution_bounds_a, convolution_bounds_b = min(a_1, a_2), max(b_1, b_2)

        delta = fabs(convolution_bounds_a - convolution_bounds_b) / bins
        convolution_interval = TimeInterval(convolution_bounds_a, convolution_bounds_b, bins)
        x = [dist_1.pdf(t) for t in convolution_interval]
        y = [dist_2.pdf(t) for t in reversed(convolution_interval)]

        c = convolve(x, y)
        dictionary_convolution = {}
        for t in xrange(len(c)):
            dictionary_convolution[delta * t] = c[t]
        bias = calculateCenterMass(dictionary_convolution)[0] + dist_2.mean() - dist_1.mean()
        dictionary_convolution_biased = {}
        for t in dictionary_convolution:
            dictionary_convolution_biased[t - bias] = dictionary_convolution[t]

        convolution_function = FunctionPiecewiseLinear(dictionary_convolution_biased, FunctionHorizontalLinear(0))
        return convolution_function.normalised()
Example #6
1
    def dehydrate_members(self, bundle):
        rangesString = bundle.request.GET.get("ranges", None)
        fullRange = rangesString is None
        if not fullRange:
            ranges = map(
                lambda rangeString: [datetime.strptime(val, "%Y%m") if val else None for val in rangeString.split("-")],
                rangesString.split(","),
            )
            mks_values = dict(bundle.obj.get_mks_values(ranges))
        else:
            mks_values = dict(bundle.obj.get_mks_values())
        members = []
        for mk in Member.objects.filter(pk__in=mks_values.keys(), current_party__isnull=False).select_related(
            "current_party"
        ):
            # TODO: this sucks, performance wise
            current_party = mk.current_party
            mk_data = mks_values[mk.id]
            members.append(
                dict(
                    id=mk.id,
                    name=mk.name,
                    score=map(itemgetter("score"), mk_data) if type(mk_data) is not dict else mk_data["score"],
                    rank=map(itemgetter("rank"), mk_data) if type(mk_data) is not dict else mk_data["rank"],
                    volume=map(itemgetter("volume"), mk_data) if type(mk_data) is not dict else mk_data["volume"],
                    numvotes=map(itemgetter("numvotes"), mk_data) if type(mk_data) is not dict else mk_data["numvotes"],
                    absolute_url=mk.get_absolute_url(),
                    party=current_party.name,
                    party_url=current_party.get_absolute_url(),
                    party_id=current_party.pk,
                )
            )

        return members
Example #7
1
def fidelity(state1, state2):
    """ Computes the fidelity [1]_ between two quantum states

    The arguments provided to this function should be a square matrix or a
    Density object. If it is a square matrix, it is assumed to be diagonalizable.

    Parameters:
    ==========

    state1, state2 : a density matrix or Matrix


    Examples
    ========

    >>> from sympy import S, sqrt
    >>> from sympy.physics.quantum.dagger import Dagger
    >>> from sympy.physics.quantum.spin import JzKet
    >>> from sympy.physics.quantum.density import Density, fidelity
    >>> from sympy.physics.quantum.represent import represent
    >>>
    >>> up = JzKet(S(1)/2,S(1)/2)
    >>> down = JzKet(S(1)/2,-S(1)/2)
    >>> amp = 1/sqrt(2)
    >>> updown = (amp * up) + (amp * down)
    >>>
    >>> # represent turns Kets into matrices
    >>> up_dm = represent(up * Dagger(up))
    >>> down_dm = represent(down * Dagger(down))
    >>> updown_dm = represent(updown * Dagger(updown))
    >>>
    >>> fidelity(up_dm, up_dm)
    1
    >>> fidelity(up_dm, down_dm) #orthogonal states
    0
    >>> fidelity(up_dm, updown_dm).evalf().round(3)
    0.707

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Fidelity_of_quantum_states

    """
    state1 = represent(state1) if isinstance(state1, Density) else state1
    state2 = represent(state2) if isinstance(state2, Density) else state2

    if not isinstance(state1, Matrix) or not isinstance(state2, Matrix):
        raise ValueError(
            "state1 and state2 must be of type Density or Matrix "
            "received type=%s for state1 and type=%s for state2" % (type(state1), type(state2))
        )

    if state1.shape != state2.shape and state1.is_square:
        raise ValueError(
            "The dimensions of both args should be equal and the " "matrix obtained should be a square matrix"
        )

    sqrt_state1 = state1 ** Rational(1, 2)
    return Tr((sqrt_state1 * state2 * sqrt_state1) ** Rational(1, 2)).doit()
Example #8
1
   def delete(cls, client, resource):
       """ Use this API to delete capolicy.
	"""
       try:
           if type(resource) is not list:
               deleteresource = capolicy()
               if type(resource) != type(deleteresource):
                   deleteresource.name = resource
               else:
                   deleteresource.name = resource.name
               return deleteresource.delete_resource(client)
           else:
               if type(resource[0]) != cls:
                   if resource and len(resource) > 0:
                       deleteresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           deleteresources[i].name = resource[i]
               else:
                   if resource and len(resource) > 0:
                       deleteresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           deleteresources[i].name = resource[i].name
               result = cls.delete_bulk_request(client, deleteresources)
           return result
       except Exception as e:
           raise e
Example #9
0
    def subscribe(self, topicUri, handler):
        """
      Subscribe to topic. When already subscribed, will overwrite the handler.

      :param topicUri: URI or CURIE of topic to subscribe to.
      :type topicUri: str
      :param handler: Event handler to be invoked upon receiving events for topic.
      :type handler: Python callable, will be called as in <callable>(eventUri, event).
      """
        if type(topicUri) not in [unicode, str]:
            raise Exception("invalid type for parameter 'topicUri' - must be string (was %s)" % type(topicUri))

        if type(handler) not in [
            types.FunctionType,
            types.MethodType,
            types.BuiltinFunctionType,
            types.BuiltinMethodType,
        ]:
            raise Exception("invalid type for parameter 'handler' - must be a callable (was %s)" % type(handler))

        turi = self.prefixes.resolveOrPass(topicUri)
        if not self.subscriptions.has_key(turi):
            msg = [WampProtocol.MESSAGE_TYPEID_SUBSCRIBE, topicUri]
            o = json.dumps(msg)
            self.sendMessage(o)
        self.subscriptions[turi] = handler
Example #10
0
def instaciateFunctions(submod_fun, s):
    fun_list = []
    name_list = []
    for idx in range(0, len(submod_fun)):
        res = submod_fun[idx](s)
        if type(res) is tuple:
            objective = res[0]
            names = res[1]
        else:
            objective = res
            names = submod_fun[idx].__name__

        if type(objective) is list:
            fun_list.extend(objective)
            if names is not list:
                names = map(lambda x: "%s-%d" % (names, x), np.arange(len(objective)))
            name_list.extend(names)
        else:
            fun_list.append(objective)
            if names is None:
                name_list.append(submod_fun[idx].func_name)
            else:
                name_list.append(names)

    return fun_list, name_list
Example #11
0
 def LinkToPelletCave(self, spawnPt):
     pelletCaveGUID = str(self.OnClickToLinkToPelletCaveFromErcana())
     print "pelletCaveGUID = ", pelletCaveGUID
     caveInfo = ptAgeInfoStruct()
     caveInfo.setAgeFilename("PelletBahroCave")
     caveInfo.setAgeInstanceName("PelletBahroCave")
     caveInfo.setAgeInstanceGuid(pelletCaveGUID)
     caveLink = ptAgeLinkStruct()
     caveLink.setAgeInfo(caveInfo)
     caveInfo = caveLink.getAgeInfo()
     caveInstance = caveInfo
     if type(caveInstance) == type(None):
         PtDebugPrint("pellet cave instance is none, aborting link")
         return
     info = ptAgeInfoStruct()
     info.copyFrom(caveInstance)
     als = ptAgeLinkStruct()
     spawnPoint = ptSpawnPointInfo()
     spawnPoint.setName("LinkInPointDefault")
     als.setAgeInfo(info)
     als.setSpawnPoint(spawnPoint)
     als.setLinkingRules(PtLinkingRules.kBasicLink)
     print "-- linking to pellet cave --"
     linkMgr = ptNetLinkingMgr()
     # linkMgr.linkToAge(als)
     linkMgr.linkToAge(als, "TouchPellet")
Example #12
0
def buildmwproject(top, creator, projects):
    """Build projects with an MW compiler"""
    mgr = MwShell(creator, start=1)
    mgr.send_timeout = AppleEvents.kNoTimeOut

    failed = []
    for file in projects:
        if type(file) == type(()):
            file, target = file
        else:
            target = ""
        file = os.path.join(top, file)
        try:
            fss = macfs.FSSpec(file)
        except MacOS.Error:
            print "** file not found:", file
            continue
        print "Building", file, target
        try:
            mgr.open(fss)
        except aetools.Error, detail:
            print "**", detail, file
            continue
        if target:
            try:
                mgr.Set_Current_Target(target)
            except aetools.Error, arg:
                print "**", file, target, "Cannot select:", arg
Example #13
0
    def publish(self, topicUri, event, excludeMe=True):
        """
      Publish an event under a topic URI. The latter may be abbreviated using a
      CURIE which has been previously defined using prefix(). The event must
      be JSON serializable.

      :param topicUri: The topic URI or CURIE.
      :type topicUri: str
      :param event: Event to be published (must be JSON serializable) or None.
      :type event: value
      :param excludeMe: When True, don't deliver the published event to myself (when I'm subscribed). Default: True.
      :type excludeMe: bool
      """

        if type(topicUri) not in [unicode, str]:
            raise Exception("invalid type for parameter 'topicUri' - must be string (was %s)" % type(topicUri))

        if type(excludeMe) != bool:
            raise Exception("invalid type for parameter 'excludeMe' - must be bool (was %s)" % type(excludeMe))

        msg = [WampProtocol.MESSAGE_TYPEID_PUBLISH, topicUri, event, excludeMe]

        try:
            o = json.dumps(msg)
        except:
            raise Exception("invalid type for parameter 'event' - not JSON serializable")

        self.sendMessage(o)
def extract_annotated_partitions(output_file, filename="ruwiktionary.xml"):
    meta_partitions = EMT.extract_meta_partitions(filename)
    for morfo, template_name, stems in meta_partitions:

        try:
            base_form_partition = extract_base_form_partition(morfo)
            if not check_for_root_presence(base_form_partition):
                continue
            partitiond_stems = partition_additional_stems(base_form_partition, stems)
            if partitiond_stems is None:
                #            print(l.strip())
                #            input()
                continue
            stems_dict = fill_stems_dict(partitiond_stems)
        except Exception as e:
            print(lineno(), l.strip(), "\n", type(e), e)
            #        if input() == 'r': raise e
            continue

        try:
            partitions = render_template(template_name, stems_dict)
        except (KeyError, TemplateException) as e:
            print(lineno(), l.strip(), "\n", type(e), e)
            #        if type(e) == TemplateException and input() == 'r': raise e
            continue
        if partitions is not None:
            for partition in partitions:
                check_partition(partition)
                print(partition, file=output_file)
def partition_additional_stem(stem, base_form_partition):
    partition = []
    for part_type, part in base_form_partition:
        assert type(part_type) == str
        assert type(stem) == str

        if stem == "" and part_type == "оконч":
            break

        if stem[: len(part)] == part:
            partition.append((part_type, part))
            stem = stem[len(part) :]
        elif part_type == "суфф":
            if len(part) > 0 and len(stem) > 0 and abs(len(part) - len(stem)) >= 3:
                raise Exception(part, stem, partition, base_form_partition)
            partition.append((part_type, stem))
            stem = ""
            break
        elif part_type == "корень" and part[: len(stem)] == stem:
            partition.append((part_type, stem))
            stem = ""
            break
        else:
            #            print(lineno(), base_form_partition, part, stem)
            return

    if stem != "":
        #        print(lineno(), base_form_partition, stems)
        return

    return partition
    def to_internal_value(self, data):
        if isinstance(data, type("")) or not hasattr(data, "__iter__"):
            self.fail("not_a_list", input_type=type(data).__name__)
        if not self.allow_empty and len(data) == 0:
            self.fail("empty")

        return [self.child_relation.to_internal_value(item) for item in data]
Example #17
0
 def wrapper(*args):
     if isMethod:
         checkArgs = args[1:]
     else:
         checkArgs = args
     # check number of args
     if len(checkArgs) < len(self.argTypes):
         msg = "%s() called with too few args (%d), should be >=%d" % (
             fn.__name__,
             len(checkArgs),
             len(self.argTypes),
         )
         raise TypeError(msg)
     # check args
     for ix, arg in enumerate(checkArgs):
         sbType = self.argTypes[ix]  # what the type should be
         if sbType != None and not isinstance(arg, sbType):
             msg = ("calling %s(), arg[%d] had type of %s," " should be %s") % (
                 fn.__name__,
                 ix,
                 type(arg).__name__,
                 typeName(sbType),
             )
             raise TypeError(msg)
     retval = fn(*args)
     # check return type
     if self.ret != None and not isinstance(retval, self.ret):
         msg = ("%s() returns type of %s," " should be %s") % (
             fn.__name__,
             type(retval).__name__,
             typeName(self.ret),
         )
         raise TypeError(msg)
     return retval
def parse_cmdline():
    """ parses command line and returns test directories, verbosity, and test filter
        usage: 
            runfiles.py  -v|--verbosity <level>  -f|--filter <regex>  dirs|files
    """
    verbosity = 2
    test_filter = None

    optlist, dirs = getopt.getopt(sys.argv[1:], "v:f:", ["verbosity=", "filter="])
    for opt, value in optlist:
        if opt in ("-v", "--verbosity"):
            verbosity = value
        elif opt in ("-f", "--filter"):
            if "," in value:
                test_filter = value.split(",")
            else:
                test_filter = [value]
    if type([]) != type(dirs):
        dirs = [dirs]

    ret_dirs = []
    for d in dirs:
        if "|" in d:
            # paths may come from the ide separated by |
            ret_dirs.extend(d.split("|"))
        else:
            ret_dirs.append(d)

    return ret_dirs, int(verbosity), test_filter
Example #19
0
def pick2d(d, I, updown=0):
    """pick2d(d,I,updown=0) - pick I'th detector image array from MDA data
structure d
    and pass the data to plot2d routine, default the image is plotted
    in negative Y direction
    """
    # dets - d[2].d  whole 2D array
    # I    - specify the detector number
    dets = d[2].d
    y = d[1].p[0].data
    px = d[2].p[0].data
    x = px[0]
    data = dets[I].data

    # for aborted 2D scan
    if len(data) < d[1].npts:
        t = d[2].npts * [0.0]
        for i in range(d[1].npts)[d[1].curr_pt : d[1].npts]:
            data.append(t)

    title = dets[I].fieldName + ": " + dets[I].name
    x_str = "X: " + d[2].p[0].name + ": " + d[2].p[0].desc + " (" + d[2].p[0].unit + ")"
    y_str = "Y: " + d[1].p[0].name + ": " + d[1].p[0].desc + " (" + d[1].p[0].unit + ")"
    if type(data) == type([]):
        data = array(data)
    if updown == 0:
        plot2d(data, x, y, title=title, xtitle=x_str, ytitle=y_str)
    else:
        plot2dUpdown(data, x, y, title=title, xtitle=x_str, ytitle=y_str)
Example #20
0
    def prefix(self, prefix, uri):
        """
      Establishes a prefix to be used in CURIEs instead of URIs having that
      prefix for both client-to-server and server-to-client messages.

      :param prefix: Prefix to be used in CURIEs.
      :type prefix: str
      :param uri: URI that this prefix will resolve to.
      :type uri: str
      """

        if type(prefix) != str:
            raise Exception("invalid type for prefix")

        if type(uri) not in [unicode, str]:
            raise Exception("invalid type for URI")

        if self.prefixes.get(prefix):
            raise Exception("prefix already defined")

        self.prefixes.set(prefix, uri)

        msg = [WampProtocol.MESSAGE_TYPEID_PREFIX, prefix, uri]

        self.sendMessage(json.dumps(msg))
Example #21
0
def testSuggestionsAuto(lineText, textToType, expectedText, keyToUseSuggestion):
    # get editor
    editorArea = waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget")
    # go to proper line, make backup, type needed text
    if not __beginTestSuggestions__(editorArea, lineText, textToType):
        return False
    # check if suggestions are shown
    if not test.verify(
        checkIfObjectExists(":popupFrame_Proposal_QListView"), "Verifying if suggestions in automatic mode are shown."
    ):
        __endTestSuggestions__(editorArea)
        return False
    # verify proposed suggestions
    verifySuggestions(textToType)
    # test if suggestion can be selected with keyToUseSuggestion
    type(findObject(":popupFrame_Proposal_QListView"), keyToUseSuggestion)
    # get text which was written by usage of suggestion
    typedText = str(lineUnderCursor(editorArea)).strip()
    # verify if expected text is written
    test.compare(
        typedText,
        expectedText,
        "Verifying automatic suggestions usage with: " + keyToUseSuggestion + ", for text: " + textToType,
    )
    __endTestSuggestions__(editorArea)
    return True
def run_client():
    parser = argparse.ArgumentParser(usage="%(prog)s [options] server_name")
    parser.add_argument("-p", "--password", dest="password", default="", help="password")
    parser.add_argument("-P", "--port", dest="port", type=int, default=DEFAULT_PORT, help="port")
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true")
    parser.add_argument("-V", "--loud", dest="loud", action="store_true")
    parser.add_argument("-l", "--loop", dest="loop", action="store_true", help="Silently keep trying to connect")
    parser.add_argument("--version", action="version", version="%(prog)s {0}".format(VERSION))
    parser.add_argument("server_name", default="localhost", nargs="?", help="server name")

    options = parser.parse_args()

    if options.verbose:
        logging.basicConfig(level=logging.INFO)
    if options.loud:
        logging.basicConfig(level=logging.DEBUG)

    while True:
        client = Client()
        client.password = options.password
        try:
            client.conn(options.server_name, options.port)
        except socket.error:
            if not options.loop:
                print "Server not accepting connections"
        except Exception as e:  # Don't let an exception shut us down
            print type(e), e
        if not options.loop:
            break
        time.sleep(0.5)
Example #23
0
   def unset(cls, client, resource, args):
       """ Use this API to unset the properties of capolicy resource.
	Properties that need to be unset are specified in args array.
	"""
       try:
           if type(resource) is not list:
               unsetresource = capolicy()
               if type(resource) != type(unsetresource):
                   unsetresource.name = resource
               else:
                   unsetresource.name = resource.name
               return unsetresource.unset_resource(client, args)
           else:
               if type(resource[0]) != cls:
                   if resource and len(resource) > 0:
                       unsetresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           unsetresources[i].name = resource[i]
               else:
                   if resource and len(resource) > 0:
                       unsetresources = [capolicy() for _ in range(len(resource))]
                       for i in range(len(resource)):
                           unsetresources[i].name = resource[i].name
               result = cls.unset_bulk_request(client, unsetresources, args)
           return result
       except Exception as e:
           raise e
Example #24
0
    def default(self, o):
        if type(o) == decimal.Decimal:
            return float(o)
        if type(o) == datetime.date or type(o) == datetime.datetime:
            return o.isoformat()
        if hasattr(o, "to_dict") and callable(getattr(o, "to_dict")):
            return o.to_dict()
        else:
            array = None
            try:
                # If it is an iterator, then try to construct array and limit number of objects
                iterator = iter(o)
                count = self.iterator_limit
                array = []
                for i, obj in enumerate(iterator):
                    array.append(obj)
                    if i >= count:
                        break
            except TypeError as e:
                # not iterable
                pass

            if array is not None:
                return array
            else:
                return json.JSONEncoder.default(self, o)
Example #25
0
    def on_find_products_by_store(self, results):

        self._log.info("Found Contracts: %s" % type(results))
        self._log.info(results)

        if len(results) > 0 and type(results[0]) == str:
            results = json.loads(results[0])

        self._log.info(results)

        if "type" not in results:
            return
        else:
            self._log.debug("Results: %s " % results["contracts"])

        if len(results) > 0 and "data" in results:

            data = results["data"]
            contracts = data["contracts"]
            signature = results["signature"]
            self._log.info("Signature: %s" % signature)

            # TODO: Validate signature of listings matches data
            # self._transport._myself.

            # Go get listing metadata and then send it to the GUI
            for contract in contracts:
                self._transport._dht.iterativeFindValue(
                    contract, callback=lambda msg, key=contract: self.on_node_search_value(msg, key)
                )
Example #26
0
def translate(proxy, args, line):
    if type(line) is unicode:
        param = {"text": line.strip().encode("utf8")}
    elif type(line) is str:
        param = {"text": line.strip()}
    else:
        raise Exception("Can't handle input")
    if args.A:
        param["align"] = True
    if args.T:
        param["topt"] = True
    if args.F:
        param["report-all-factors"] = True
    if args.nbest:
        param["nbest"] = int(args.nbest)
        param["add-score-breakdown"] = True
        pass
    if args.U:
        param["nbest-distinct"] = True
        pass
    attempts = 0
    while attempts < 120:
        try:
            return proxy.translate(param)
        except:
            print >> sys.stderr, "Waiting", proxy
            attempts += 1
            time.sleep(5)
            pass
        pass
    raise Exception("Exception: could not reach translation server.")
Example #27
0
def recording_period_measurements(no_stars):
    print "Recording period measurements... "
    list_of_quarters = ["ss3", "ss4", "ss5", "ss6", "ss7", "ss8", "ss9", "ss10", "ss11", "ss12", "ss13", "ss14"]
    for year in list_of_quarters:
        data = np.genfromtxt("/Users/angusr/angusr/ACF/PDCQ%s_output/results.txt" % year).T
        KID = np.array(range(1, no_stars + 1))
        ACF_period = data[1][1:]
        period_error = data[6][1:]
        sine_period = data[2][1:]
        # KID = data[0][0]
        # #KID = range(1,no_stars+1)
        # ACF_period =data[1][0]
        # print ACF_period
        # period_error = data[6][0]
        # sine_period = data[2][0]
        print type(KID), type(ACF_period), type(period_error), type(sine_period)
        np.savetxt(
            "/Users/angusr/angusr/ACF/PDCQ%s_output/Periods_%stest.txt" % (year, year),
            np.transpose((KID, ACF_period, period_error, sine_period)),
        )
        # file = open('/Users/angusr/angusr/ACF/PDCQ%s_output/Periods_%stest.txt' %(year, year), 'r')
        # for i in range(len(KID)):
        # file.write('%s   %s   %s   %s' %(str(period[x]), str(dlag_per_err[x]), str(sine_per[x])))
        # file.close()
    return
Example #28
0
    def testReturnType(self):
        # Test return type of gettimeout()
        self.sock.settimeout(1)
        self.assertEqual(type(self.sock.gettimeout()), type(1.0))

        self.sock.settimeout(3.9)
        self.assertEqual(type(self.sock.gettimeout()), type(1.0))
    def oInst(self, replyTo, **kw):
        # This will populate the middle frame with list of the members of
        # the object selected in the left frame

        # print "%s|oInst Frame Accessed, Request ID %s" % (self.timeStamp(), str(kw))

        head = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n<head>\n<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">\n<title>member List</title>\n</head>\n<body>\n<UL>'
        foot = "</ul></body></HTML>"
        body = ""
        doIdRequested = ""
        for j, k in kw.iteritems():
            doIdRequested = int(k)
            # print j,k
        try:
            memberList = inspect.getmembers(simbase.air.doId2do[doIdRequested])
        except KeyError:
            replyTo.respond(
                '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n<head>\n<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">\n<TITLE>OBJ Gone</title>\n</head><body>The object is no longer on the system</body>\n</HTML>'
            )
            return
        memberList.sort()
        memberList.reverse()
        while memberList:
            tempMember = memberList.pop()
            if (
                type(tempMember[1]) == str
                or type(tempMember[1]) == int
                or type(tempMember[1]) == float
                or type(tempMember[1]) == dict
            ):
                body = "%s<LI>%s\n" % (body, str(tempMember))
        replyTo.respond("%s%s%s" % (head, body, foot))
Example #30
0
def write_event_csv(all_events, fp, header_row=True):
    eventwriter = csv.writer(fp)

    if header_row == True:
        eventwriter.writerow(["ProcessPath", "Timestamp", "Event", "Path/IP/Domain", "Comments"])

    for event in all_events:
        if type(event) == CbFileModEvent:
            eventwriter.writerow([event.parent.path, event.timestamp, event.type, event.path, ""])
        elif type(event) == CbNetConnEvent:
            if event.dns:
                hostname = event.dns
            else:
                hostname = event.ipaddr
            hostname += ":%d" % event.port

            eventwriter.writerow([event.parent.path, event.timestamp, event.direction + " netconn", hostname, ""])
        elif type(event) == CbRegModEvent:
            eventwriter.writerow([event.parent.path, event.timestamp, event.type, event.path, ""])
        elif type(event) == CbChildProcEvent:
            eventwriter.writerow([event.parent.path, event.timestamp, "childproc", event.path, event.proc.cmdline])
        elif type(event) == CbModLoadEvent:
            eventwriter.writerow([event.parent.path, event.timestamp, "modload", event.path, event.md5])

    return 0