Beispiel #1
0
def benefits_data_types(idWho):
	""" Receives the benefit's id (idWho) and checks if the user is allowed to edit that
	benefits types of data. If 'GET' method, a list of all data types available and a list of the
	Benefit's pre selected types of data is returned. If 'POST' method, the information received 
	is checked and then updated to the database."""
	idWho = validate_benefit_idwho(idWho, session['idCompany'])
	if idWho:
		if request.method == "POST":
			ids_datatype = request.form.getlist("idDatatype")
			ids_datatype_check = data_types_exist(ids_datatype)
			if ids_datatype_check is not None:
				update_benefit_data_types(idWho, ids_datatype_check)
				return redirect("/beneficios/perfil/{}".format(idWho))
			else: 
				whoops = "Houve um erro na atualização dos tipos de dado. Selecione outro do menu."
				profile = BenefitProfile(idWho).get_profile()
				available_datatypes = get_available_data_types_for_benefit(idWho)
				return render_template("benefits_edit_data_types.html", 
										header = get_header(session), profile = profile, 
										available_datatypes = available_datatypes)
		else: # 'GET'
			profile = BenefitProfile(idWho).get_profile()
			available_datatypes = get_available_data_types_for_benefit(idWho)
			return render_template("benefits_edit_data_types.html", 
									header = get_header(session), profile = profile, 
									available_datatypes = available_datatypes)
	else:
		whoops = "Este perfil não existe, por favor selecione um benefício da lista."
		benefits_list = CompanyProfile(session["idCompany"]).get_benefits()
		return render_template("benefits_list.html", header = get_header(session), 
								benefits_list = benefits_list, whoops = whoops)
Beispiel #2
0
def benefits_register_new_data_type(idWho):
	""" Receives the benefit's id (idWho) and checks if the user is allowed to register a new 
 	type of data for that benefit. If 'GET' method, a list of all data types registered in
 	the database is returned. If 'POST' method, the new data type is checked before being
 	registered in the database and added to the list of data types of the benefit"""
	idWho = validate_benefit_idwho(idWho, session['idCompany'])
	if idWho:
		if request.method == "POST":
			name = request.form.get("name")
			example = request.form.get("example")
			if name and example:
				register_new_data_type(name, example, idWho)
				return redirect("/beneficios/perfil/{}".format(idWho))
			else:
				data_list = get_all_data_types()
				whoops = "Você precisa preencher os dois campos"
				return render_template("benefits_register_new_data_type.html", 
												header = get_header(session),
												data_list = data_list,
												idWho = idWho, whoops = whoops)
		else: # 'GET'
			data_list = get_all_data_types()
			return render_template("benefits_register_new_data_type.html", 
												header = get_header(session),
												data_list = data_list,
												idWho = idWho)
	else:
		whoops = "Este perfil não existe, por favor selecione um benefício da lista."
		benefits_list = CompanyProfile(session["idCompany"]).get_benefits()
		return render_template("benefits_list.html", header = get_header(session), 
								benefits_list = benefits_list, whoops = whoops)
Beispiel #3
0
 def resolve(self, settings, request_host):
     tokens = self.tokens[:]
     if not self.raw:
         if self.body and not utils.get_header("Content-Length", self.headers):
             tokens.append(
                 Header(
                     ValueLiteral("Content-Length"),
                     ValueLiteral(str(len(self.body.value.get_generator(settings)))),
                 )
             )
         if request_host:
             if not utils.get_header("Host", self.headers):
                 tokens.append(
                     Header(
                         ValueLiteral("Host"),
                         ValueLiteral(request_host)
                     )
                 )
         else:
             if not utils.get_header("Date", self.headers):
                 tokens.append(
                     Header(
                         ValueLiteral("Date"),
                         ValueLiteral(formatdate(timeval=None, localtime=False, usegmt=True))
                     )
                 )
     intermediate = self.__class__(tokens)
     return self.__class__([i.resolve(intermediate, settings) for i in tokens])
Beispiel #4
0
def people_edit_benefits(idWho):
	""" It receives the person's id and checks if the user can edit that person's
	benefits. Then it proceeds in checking the list of benefits added and or excluded
	from the person's profile. If new data might be necessary (needs_data_check), it
	returns the people_register_data with a list of all combined data (new and current)
	for data input. Benefit_updated_data_types is only True when the benefit updates its
	list of data types and those data types don't match the person's data in the database,
	requiring new data inputs """
	idWho = validate_person_idwho(idWho, session['idCompany'])
	if idWho:
		if request.method == "POST":
			ids_benefits = str_list_to_int(request.form.getlist("idBenefit"))
			needs_data_check = update_person_benefits(idWho, ids_benefits)
			benefit_updated_data_types = request.form.get("force_update")
			if needs_data_check or benefit_updated_data_types:
				combined_data = get_combined_data_for_person(ids_benefits, idWho)
				return render_template("people_register_data.html", 
										combined_data = combined_data, 
										header = get_header(session),
										person_id = idWho)
			return redirect("/pessoas/perfil/{}".format(idWho))
		else: # 'GET'
			return render_template("people_edit_benefits.html", 
							header = get_header(session),
							profile = PersonProfile(idWho).get_profile(),
							benefits_list = CompanyProfile(session['idCompany']).get_benefits())
	else:
		whoops = "Este perfil não existe, por favor selecione uma pessoa da lista."
		people_list = CompanyProfile(session["idCompany"]).get_people()
		return render_template("people_list.html", header = get_header(session), 
									people_list = people_list, whoops = whoops)
Beispiel #5
0
 def resolve(self, settings, msg=None):
     tokens = self.tokens[:]
     if self.ws:
         if not self.method:
             tokens.insert(1, Method("get"))
         for i in websockets.client_handshake_headers().lst:
             if not utils.get_header(i[0], self.headers):
                 tokens.append(
                     Header(ValueLiteral(i[0]), ValueLiteral(i[1])))
     if not self.raw:
         if not utils.get_header("Content-Length", self.headers):
             if self.body:
                 length = len(self.body.value.get_generator(settings))
                 tokens.append(
                     Header(
                         ValueLiteral("Content-Length"),
                         ValueLiteral(str(length)),
                     ))
         if settings.request_host:
             if not utils.get_header("Host", self.headers):
                 tokens.append(
                     Header(ValueLiteral("Host"),
                            ValueLiteral(settings.request_host)))
     intermediate = self.__class__(tokens)
     return self.__class__(
         [i.resolve(settings, intermediate) for i in tokens])
Beispiel #6
0
 def resolve(self, settings, msg=None):
     tokens = self.tokens[:]
     if self.ws:
         if not settings.websocket_key:
             raise RenderError(
                 "No websocket key - have we seen a client handshake?"
             )
         if not self.code:
             tokens.insert(
                 1,
                 Code(101)
             )
         hdrs = websockets.server_handshake_headers(settings.websocket_key)
         for i in hdrs.lst:
             if not utils.get_header(i[0], self.headers):
                 tokens.append(
                     Header(ValueLiteral(i[0]), ValueLiteral(i[1]))
                 )
     if not self.raw:
         if not utils.get_header("Content-Length", self.headers):
             if not self.body:
                 length = 0
             else:
                 length = len(self.body.value.get_generator(settings))
             tokens.append(
                 Header(
                     ValueLiteral("Content-Length"),
                     ValueLiteral(str(length)),
                 )
             )
     intermediate = self.__class__(tokens)
     return self.__class__(
         [i.resolve(settings, intermediate) for i in tokens]
     )
Beispiel #7
0
 def resolve(self, settings, msg=None):
     tokens = self.tokens[:]
     if self.ws:
         if not settings.websocket_key:
             raise RenderError(
                 "No websocket key - have we seen a client handshake?")
         if not self.code:
             tokens.insert(1, Code(101))
         hdrs = websockets.server_handshake_headers(settings.websocket_key)
         for i in hdrs.lst:
             if not utils.get_header(i[0], self.headers):
                 tokens.append(
                     Header(ValueLiteral(i[0]), ValueLiteral(i[1])))
     if not self.raw:
         if not utils.get_header("Content-Length", self.headers):
             if not self.body:
                 length = 0
             else:
                 length = len(self.body.value.get_generator(settings))
             tokens.append(
                 Header(
                     ValueLiteral("Content-Length"),
                     ValueLiteral(str(length)),
                 ))
     intermediate = self.__class__(tokens)
     return self.__class__(
         [i.resolve(settings, intermediate) for i in tokens])
Beispiel #8
0
def benefits_registration_card(idBenefit, idPerson):
	""" Receives idBenefit and idPerson and checks if the user can see that benefit's 
	registration card (benefit must be registered with the user's company as well as the person must
	be a company employee). If the information checks out, the employee's (person) benefit 
	registration card is returned with all correlated data """
	if validate_registration_card(idBenefit, idPerson, session['idCompany']):
		idBenefit = int(idBenefit)
		idPerson = int(idPerson)
		benefit_profile = BenefitProfile(idBenefit).get_profile()
		person_profile = PersonProfile(idPerson).get_profile()
		person_data = get_combined_data_for_person([idBenefit,], idPerson)
		admission_date = get_person_admission_date(idPerson, idBenefit)
		return render_template("benefits_registration_card.html", header = get_header(session),
												benefit = benefit_profile,
												person = person_profile,
												person_data = person_data,
												admission_date = admission_date)
	else:
		whoops = "Este Cartão de Registro não existe."
		return render_template("index.html", header = get_header(session),
												whoops = whoops)
	return render_template("benefits_registration_card.html", header = get_header(session),
												benefit = benefit_profile,
												person = person_profile,
												admission_date = admission_date)
Beispiel #9
0
 def resolve(self, settings, msg=None):
     tokens = self.tokens[:]
     if self.ws:
         if not self.method:
             tokens.insert(
                 1,
                 Method("get")
             )
         for i in websockets.client_handshake_headers().lst:
             if not utils.get_header(i[0], self.headers):
                 tokens.append(
                     Header(ValueLiteral(i[0]), ValueLiteral(i[1]))
                 )
     if not self.raw:
         if not utils.get_header("Content-Length", self.headers):
             if self.body:
                 length = len(self.body.value.get_generator(settings))
                 tokens.append(
                     Header(
                         ValueLiteral("Content-Length"),
                         ValueLiteral(str(length)),
                     )
                 )
         if settings.request_host:
             if not utils.get_header("Host", self.headers):
                 tokens.append(
                     Header(
                         ValueLiteral("Host"),
                         ValueLiteral(settings.request_host)
                     )
                 )
     intermediate = self.__class__(tokens)
     return self.__class__(
         [i.resolve(settings, intermediate) for i in tokens]
     )
Beispiel #10
0
def benefits_search():
	""" If 'GET' method, returns the search page, if 'POST' method, returns the result of 
	that search for Benefits """
	if request.method == "POST":
		benefit_name = request.form.get("name")
		if benefit_name:
			benefits_list = search_benefit_by_name_by_company(benefit_name, session['idCompany'])
			return render_template("benefits_search_result.html", header = get_header(session),
																benefits_list = benefits_list)
		else:
			whoops = "Por favor insira um nome"
			return render_template("search.html", header = get_header(session), 
											who = "beneficios", whoops = whoops)
	else: # 'GET'
		return render_template("search.html", header = get_header(session), who = "beneficios")
Beispiel #11
0
def people_profile(idWho):
	""" Receives the person's id (idWho) and checks if the user is allowed to see
	that person's profile. This is an upgrade from the last version in which anyone could 
	see any person, even if the person wasn't part of the company. If that is the case an 
	alert is shown to the user. Otherwise the person's profile is returned."""
	idWho = validate_person_idwho(idWho, session['idCompany'])
	if idWho:
		profile = PersonProfile(idWho).get_profile()
		return render_template("people_profile.html", header = get_header(session),
													profile = profile)
	else:
		whoops = "Este perfil não existe, por favor selecione uma pessoa da lista."
		people_list = CompanyProfile(session["idCompany"]).get_people()
		return render_template("people_list.html", header = get_header(session), 
										people_list = people_list, whoops = whoops)
Beispiel #12
0
    def test_simple(self):

        file1contents = "file 1 contents"
        utils.write_file("file.txt", file1contents)
        
        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        content_length = utils.get_header("content-length", headers)
        etag           = utils.get_header("etag",           headers)

        self.assertEqual(200, status)
        self.assertEqual(file1contents, body)
        self.assertEqual(len(file1contents), int(content_length))
        self.assertTrue(etag != None)
Beispiel #13
0
def completed_tickets():
    db_connection = connect_db(APP)
    completed_tickets_cursor = db_connection.execute(
        'select * from tickets where status="Complete"')

    print completed_tickets_cursor

    completed_tickets_headers = get_header(APP, 'tickets')
    formatted_completed_tickets_headers = [
        format_headers(h) for h in completed_tickets_headers]

    completed_tickets = {}
    for name in completed_tickets_headers:
        completed_tickets[name] = []

    completed_tickets['url'] = []
    completed_tickets['delete'] = []

    for row in completed_tickets_cursor:
        for name, item in zip(completed_tickets_headers, row):
            completed_tickets[name].append(item)
        completed_tickets['url'].append('/ticket?ticket_number={}'.format(row[0]))
        completed_tickets['delete'].append(
            '/api/deleteticket?ticket_number={}'.format(row[0])
        )

    
    return render_template(
        'completedtickets.html',
        tickets=completed_tickets,
        completed_tickets=completed_tickets,
        completed_tickets_headers=completed_tickets_headers,
        formatted_completed_tickets_headers=formatted_completed_tickets_headers
    )
Beispiel #14
0
def get_abstract_enum(node, tu, scf_path):
    enum_constant_nodes = matchers.get_children(node, lambda n: n.kind == CursorKind.ENUM_CONSTANT_DECL)
    full_namespace = utils.get_namespace(node)
    constants = [generic.EnumConstant(cons.spelling, cons.enum_value) for cons in enum_constant_nodes]
    return generic.DefinedEnum(name=node.spelling, namespace=full_namespace, constants=constants, \
                               defined_in_header=utils.get_header(node, tu, scf_path), \
                               location=_convert_location(node.location))
Beispiel #15
0
 def buy(self, order_type, deadline=None):
     """Buys stocks in the trading list."""
     orders_table = []
     positions = self.alpaca.list_positions()
     existing_positions = {position.symbol: int(position.qty) for position in positions}
     for symbol, proportion, _ in self.trading_list:
         if proportion == 0:
             continue
         adjust = 1 if order_type == 'limit' else 0.98
         qty = int(self.cash * proportion * adjust / self.prices[symbol])
         if symbol in existing_positions:
             qty -= existing_positions[symbol]
         if qty > 0:
             orders_table.append([symbol, self.prices[symbol], qty, self.prices[symbol] * qty])
             try:
                 if order_type == 'limit':
                     self.alpaca.submit_order(symbol, qty, 'buy', 'limit', 'day',
                                              limit_price=self.prices[symbol])
                 elif order_type == 'market':
                     self.alpaca.submit_order(symbol, qty, 'buy', 'market', 'day')
                 else:
                     raise NotImplementedError('Order type %s not recognized' % (order_type,))
             except tradeapi.rest.APIError as e:
                 logging.error('Failed to buy %s: %s', symbol, e)
     outputs = [utils.get_header('Place ' + order_type.capitalize() + ' Buy Order')]
     if orders_table:
         outputs.append(tabulate(orders_table,
                                 headers=['Symbol', 'Price', 'Quantity', 'Estimated Cost'],
                                 tablefmt='grid'))
     logging.info('\n'.join(outputs))
     self.wait_for_order_to_fill(deadline=deadline)
Beispiel #16
0
def plot_phase(ax, filename):
    h = get_header(filename)
    N = int(h['N'])
    K = int(h['K'])
    p = float(h['p'])
    gs = int(h['gseed'])
    a = float(h['coupling'])
    iters = int(h['iters'])
    burn = int(h['burn'])
    ic = h['initial_condition']
    seed = int(h['seed'])
    stream = int(h['stream'])
    title = """N={}  K={}  p={}  gseed={}  a={}  ic={}\niters={}  burn={}  seed={}\
  stream={}""".format(N, K, p, gs, a, ic, iters, burn, seed, stream)
    # ax.set_title(title)
    df = pd.read_csv(filename, skiprows=3, header=None)
    df.columns = list(range(df.shape[1] - 1)) + ['time_elapsed']
    ax.set_xlabel("Phases", fontsize=14)
    ax.set_ylabel("Time [a.u.]", fontsize=14)
    # CROP PART TIME AXIS FROM s TO e
    s, e = 0, -1
    M = df.iloc[s:e]
    ax.imshow(M.values[:, 0:-1],
              aspect='auto',
              origin='lower',
              cmap='viridis',
              extent=(0, N, M.time_elapsed.iloc[0], M.time_elapsed.iloc[-1]))
    return title
Beispiel #17
0
 def analyze_rows(self, sell_date_str, rows):
     ml_features, symbols, gains = [], [], {}
     for row in rows:
         ml_features.append(
             [getattr(row, key) for key in utils.ML_FEATURES])
         symbols.append(row.Symbol)
         gains[row.Symbol] = row.Gain
     ml_features = np.array(ml_features)
     weights = self.model.predict(ml_features)
     buy_symbols = [(symbol, weight)
                    for symbol, weight in zip(symbols, weights)]
     trading_list = self.get_trading_list(buy_symbols=buy_symbols)
     trading_table = []
     daily_gain = 0
     for symbol, proportion, weight in trading_list:
         if proportion == 0:
             continue
         gain = gains[symbol]
         # > 100% gain might caused by stock split. Do not calculate.
         if gain >= 1:
             continue
         trading_table.append([
             symbol,
             '%.2f%%' % (proportion * 100, ), weight,
             '%.2f%%' % (gain * 100, )
         ])
         daily_gain += gain * proportion
     outputs = [utils.get_header(sell_date_str)]
     if trading_table:
         outputs.append(
             tabulate(trading_table,
                      headers=['Symbol', 'Proportion', 'Weight', 'Gain'],
                      tablefmt='grid'))
     self.add_profit(pd.to_datetime(sell_date_str), daily_gain, outputs)
Beispiel #18
0
    def __init__(self,
                 lasFile_path: str,
                 filename: str,
                 downsampling_rate: float,
                 visualize=True):

        assert (type(lasFile_path) == str) and os.path.exists(
            lasFile_path
        ), 'LASFILE_PATH parameter has to be string and existing folder directory'
        assert (type(filename) == str) and (
            filename.split('.')[1] == 'las'
        ) and os.path.exists(
            lasFile_path + filename
        ), 'FILENAME parameter has to be string, it has to be las type format and it has to be localized in {}'.format(
            lasFile_path)
        assert (downsampling_rate > 0) and (
            downsampling_rate <= 1
        ), 'DOWNSAMPLING_RATE parameter has to be bigger than 0 and smaller or equal than 1'

        self.path = lasFile_path
        self.filename = filename
        self.dw_rate = downsampling_rate
        self.header = get_header(self.path + self.filename)
        self.point_cloud = get_point_cloud(self.path + self.filename,
                                           self.header)
        self.dws_point_cloud = self.point_cloud[
            random.sample(range(0, self.point_cloud.shape[0]),
                          round(self.point_cloud.shape[0] * self.dw_rate)), :]
        self.visualize = visualize
Beispiel #19
0
def people_edit_data(idWho):
	""" It receives the person's id and checks if the user can edit that person's
	data. Then it proceeds in getting a list of all data for that person 
	and returns the people_register_data page """
	idWho = validate_person_idwho(idWho, session['idCompany'])
	if idWho:
		person_data = PersonProfile(idWho).get_data()
		return render_template("people_register_data.html", 
								combined_data = person_data, 
								header = get_header(session),
								person_id = idWho)
	else: 
		whoops = "Este perfil não existe, por favor selecione uma pessoa da lista."
		people_list = CompanyProfile(session["idCompany"]).get_people()
		return render_template("people_list.html", header = get_header(session), 
								people_list = people_list, whoops = whoops)
Beispiel #20
0
def benefits_profile(idWho):
	""" Receives the benefit's id (idWho) and checks if the user is allowed to see
	that benefit's profile. This is an upgrade from the last version in which anyone could 
	see any benefit, even if the user's company wasn't registered with that benefit. If that
	is the case an alert is shown to the user. Otherwise the benefit profile is returned."""
	idWho = validate_benefit_idwho(idWho, session['idCompany'])
	if idWho:
		profile = BenefitProfile(idWho).get_profile()
		benefit_people = BenefitProfile(idWho).get_people_by_company(session['idCompany'])
		return render_template("benefits_profile.html", header = get_header(session),
								profile = profile, benefit_people = benefit_people)
	else:
		whoops = "Este perfil não existe, por favor selecione um benefício da lista."
		benefits_list = CompanyProfile(session["idCompany"]).get_benefits()
		return render_template("benefits_list.html", header = get_header(session), 
								benefits_list = benefits_list, whoops = whoops)
    def __init__(self, path: str, plots_num: int, signal_span: float):

        self.path = path
        self.header = get_header(self.path + 'roi.las')
        self.field = get_point_cloud(self.path + 'surface_evaluation/clean_field.las', self.header)
        self.plots_num = plots_num
        self.signal_span = signal_span
Beispiel #22
0
def people_search():
	""" If 'GET' returns the search page, if 'POST' returns the result of that search for 
	People """
	who = "pessoas"
	if request.method == "POST":
		person_name = request.form.get("name")
		if person_name:
			people_list = search_person_by_name_by_company(person_name, session['idCompany'])
			return render_template("people_search_result.html", header = get_header(session),
															people_list = people_list)
		else:
			whoops = "Por favor insira um nome"
			return render_template("search.html", header = get_header(session), 
												who = who, whoops = whoops)
	else:
		return render_template("search.html", header = get_header(session), who = who)
Beispiel #23
0
    def test_ifnonematch(self):

        file1contents = "file 1 contents"
        utils.write_file("file.txt", file1contents)

        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        etag = utils.get_header("etag", headers)

        headers = {"If-None-Match": etag}
        response = self.client.request("GET", "/file.txt", headers)
        (status, reason, body, headers) = response
        
        self.assertEqual(status, 304)                

        file1contents = "file 1 contents - even more!"
        utils.write_file("file.txt", file1contents)

        headers = {"If-None-Match": etag}
        response = self.client.request("GET", "/file.txt", headers)
        (status, reason, body, headers) = response

        self.assertEqual(status, 200)
        self.assertEquals(file1contents, body)
def plot_phase(ax, filename, m, M):
    h = get_header(filename)
    N = int(h['N'])
    K = int(h['K'])
    p = float(h['p'])
    gs = int(h['gseed'])
    a = float(h['coupling'])
    iters = int(h['iters'])
    burn = int(h['burn'])
    ic = h['initial_condition']
    seed = int(h['seed'])
    stream = int(h['stream'])
    title = """N={} K={} p={} gseed={}\na={} iters={} burn={} ic={} seed={}
    stream={}""".format(N, K, p, gs, a, iters, burn, ic, seed, stream)
    ax.set_title(title)
    df = pd.read_csv(filename, skiprows=3, header=None)
    if m is not None and M is not None:
        df = df.iloc[int(m * len(df)):int(M * len(df))]
    df.columns = list(range(df.shape[1] - 1)) + ['time_elapsed']
    ax.set_xlabel("Phases")
    ax.set_ylabel("Time [a.u.]")
    print('extent', 0, N, df.time_elapsed.iloc[0], df.time_elapsed.iloc[-1])
    ax.imshow(df[df.columns[:-1]].values,
              aspect='auto',
              origin='lower',
              cmap='viridis',
              extent=(0, N, df.time_elapsed.iloc[0], df.time_elapsed.iloc[-1]))
Beispiel #25
0
    def _request(self, method, request_path, params, cursor=False):
        #if method == c.GET:
        request_path = request_path + utils.parse_params_to_str(params)

        # url
        url = c.API_URL + request_path

        timestamp = utils.get_timestamp()
        # sign & header
        if self.use_server_time:
            timestamp = self._get_timestamp()

        #body = json.dumps(params) if method == c.POST else ""
        #body = urllib.urlencode(params)
        #body = utils.parse_params_to_str(params)

        #print "request_path",request_path
        #print "body", body

        body = ""

        #print "body",body
        sign = utils.sign(
            utils.pre_hash(timestamp, method, request_path, str(body)),
            self.API_SECRET_KEY)
        header = utils.get_header(self.API_KEY, sign, timestamp,
                                  self.PASSPHRASE)

        # send request
        response = None
        #print("url:", url)
        #print("headers:", header)
        #print("body:", body)

        print url
        if method == c.GET:
            response = requests.get(url, headers=header)
        elif method == c.POST:
            print header
            response = requests.post(url, params=body, headers=header)
            #response = requests.post(url, data=body, headers=header)
            #response = requests.post(url, json=body, headers=header)
        elif method == c.DELETE:
            response = requests.delete(url, headers=header)

        # exception handle
        if not str(response.status_code).startswith('2'):
            raise exceptions.SCAPIException(response)
        try:
            res_header = response.headers
            print response.text
            if cursor:
                return response.json(), r
            else:
                return response.json()
        except ValueError:
            raise exceptions.SCRequestException('Invalid Response: %s' %
                                                response.text)
Beispiel #26
0
 def print_summary(self):
     time_range = '%s ~ %s' % (self.start_date, self.end_date)
     summary_table = [['Time Range', time_range]]
     gain_texts = [(k + ' Gain', '%.2f%%' % ((v[1][-1] - 1) * 100, ))
                   for k, v in self.values.items()]
     summary_table.extend(sorted(gain_texts))
     logging.info(
         utils.get_header('Summary') + '\n' +
         tabulate(summary_table, tablefmt='grid'))
Beispiel #27
0
    def __init__(self, path, filename, ds_rate, low_quantile, up_quantile):

        self.path = path
        self.filename = filename
        self.ds_rate = ds_rate
        self.low_quantile = low_quantile
        self.up_quantile = up_quantile
        self.header = get_header(self.path + self.filename)
        self.point_cloud = get_point_cloud(self.path + self.filename, self.header)
Beispiel #28
0
    def test_dir(self):
        utils.create_dir("dir1")

        response = self.client.request("GET", "/dir1")
        (status, reason, body, headers) = response

        location = utils.get_header("location", headers)

        self.assertEqual(307, status)
        self.assertEqual("http://localhost:%s/dir1/" % utils.get_port(), location)
Beispiel #29
0
    def test_create(self):
        
        file1contents = "file 1 contents"

        headers = {"If-None-Match": "*"}
        response = self.client.request("PUT", "/file.txt", headers, file1contents)
        (status, reason, body, headers) = response

        etag = utils.get_header("etag", headers)

        self.assertEqual(201, status)
        self.assertTrue(etag != None)
        
        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        etag_get = utils.get_header("etag", headers)
        
        self.assertEqual(etag_get, etag)
Beispiel #30
0
    def test_etag_changed(self):

        file1contents = "file 1 contents"
        utils.write_file("file.txt", file1contents)
        
        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        etag1 = utils.get_header("etag", headers)

        file1contents = "file 1 contents - even more!"
        utils.write_file("file.txt", file1contents)

        response = self.client.request("GET", "/file.txt")
        (status, reason, body, headers) = response

        etag2 = utils.get_header("etag", headers)

        self.assertTrue(etag1 != etag2)
Beispiel #31
0
    def test_simple_in_dir(self):

        utils.create_dir("a-dir")
        
        file1contents = "file 1 contents"
        utils.write_file("a-dir/file.txt", file1contents)

        response = self.client.request("GET", "/a-dir/file.txt")
        (status, reason, body, headers) = response

        content_length = utils.get_header("content-length", headers)
        etag           = utils.get_header("etag",           headers)
        
        etag_pattern = re.compile(r'^"[^"]+"$')

        self.assertEqual(200, status)
        self.assertEqual(file1contents, body)
        self.assertEqual(len(file1contents), int(content_length))
        self.assertTrue(etag != None)
        self.assertTrue(etag_pattern.match(etag) != None)
Beispiel #32
0
def people_registration():
	""" This is a more complex function. First a list of all benefits registered with the 
	company is generated. If 'GET' method, returns the people registration page along with 
	the list of all benefits registered with the user's company. 
	If 'POST', it checks if both Person' name has been entered and if the cpf is a valid 
	cpf number in the correct cpf format, if not returns the registration page with an alert 
	(whoops). If valid, it calls the register new person function which will procced to check the 
	validity of the cpf entered against the person database/table. If everything goes well, 
	the function checks if a benefit was selected (or more) during registration. 
	If so, the person is also registered with those benefits. If that is the case the
	people_register_data page is returned to continue the data registration process. If not,
	an updated list of all company people is returned."""
	company_benefits = CompanyProfile(session['idCompany']).get_benefits()
	if request.method == 'POST':
		name = request.form.get("name")
		cpf = request.form.get("cpf")
		chosen_benefits = str_list_to_int(request.form.getlist("benefits"))
		if name and isCpfValid(cpf):
			if not get_person_id_by_cpf(cpf):
				new_person_id = register_new_person(name, cpf, session['idCompany'])
				if len(chosen_benefits) > 0:
					for benefit_id in chosen_benefits:
						register_person_to_benefit(new_person_id, benefit_id)
					combined_data = get_combined_data_for_person(chosen_benefits, new_person_id)
					return render_template("people_register_data.html",
															header = get_header(session),
															person_id = new_person_id,
															combined_data = combined_data)
				else:
					return redirect("/pessoas/lista")
			else:
				whoops = "Essa pessoa já está registrada"
				return render_template("people_registration.html", header = get_header(session), 
																whoops = whoops)
		else:
			whoops = "Por favor insira um nome e um número de cpf válido"
			return render_template("people_registration.html", header = get_header(session), 
															whoops = whoops)
	else: # 'GET'
		return render_template("people_registration.html", header = get_header(session), 
														benefits = company_benefits)
Beispiel #33
0
    def _request(self, method, request_path, params, cursor=False):

        if method == c.GET:
            request_path = request_path + utils.parse_params_to_str(params)
        # url
        url = c.API_URL + request_path

        timestamp = utils.get_timestamp()
        # print(timestamp)
        # sign & header
        if self.use_server_time:
            timestamp = self._get_timestamp()
        # print(timestamp)

        body = json.dumps(params) if method == c.POST else ""

        sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
        # print(utils.pre_hash(timestamp, method, request_path, str(body)))
        header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE)
        # send request
        response = None

        # print("url:", url)
        logging.info("url:" + url)
        # print("headers:", header)
        # print("body:", body)
        logging.info("body:" + body)

        if method == c.GET:
            response = requests.get(url, headers=header)
        elif method == c.POST:
            response = requests.post(url, data=body, headers=header)
            #response = requests.post(url, json=body, headers=header)
        elif method == c.DELETE:
            response = requests.delete(url, headers=header)

        # exception handle
        if not str(response.status_code).startswith('2'):
            raise exceptions.OkexAPIException(response)
        try:
            res_header = response.headers
            if cursor:
                r = dict()
                try:
                    r['before'] = res_header['OK-BEFORE']
                    r['after'] = res_header['OK-AFTER']
                except:
                    print("")
                return response.json(), r
            else:
                return response.json()
        except ValueError:
            raise exceptions.OkexRequestException('Invalid Response: %s' % response.text)
    def __init__(self, lasFile_path: str, filename: str,
                 downsampling_rate: float):

        self.path = lasFile_path
        self.filename = filename
        self.dw_rate = downsampling_rate
        self.header = get_header(self.path + 'roi.las')
        self.point_cloud = get_point_cloud(self.path + self.filename,
                                           self.header)
        self.dws_point_cloud = self.point_cloud[
            random.sample(range(0, self.point_cloud.shape[0]),
                          round(self.point_cloud.shape[0] * self.dw_rate)), :]
Beispiel #35
0
def get_true_video_url(fake_url):
    sess = requests.Session()
    headers = get_header()
    url = TRUE_VIDEO_API_URL + fake_url
    try:
        res = sess.get(url, headers=headers)
        result = json.loads(res.text, encoding='utf-8')
        string = result.get('data')[0].get('url')
        return string
    except Exception as e:
        print("视频真实地址API调用失败")
        print(e)
    def __init__(self, path, block_num, signal_span_z, signal_span_e,
                 edge_level, w, LAMBDA, q_dom, q_notdom):

        self.path = path
        self.header = get_header(self.path + 'roi.las')
        self.block_num = block_num
        self.signal_span_z = signal_span_z
        self.signal_span_e = signal_span_e
        self.edge_level = edge_level
        self.w = w
        self.LAMBDA = LAMBDA
        self.q_dom = q_dom
        self.q_notdom = q_notdom
Beispiel #37
0
    def test_html(self):

        file1contents = "file 1 contents"
        utils.create_dir("dir1")
        utils.write_file("dir1/file1.txt", file1contents)

        response = self.client.request("GET", "/dir1/", {"Accept": "text/html"})
        (status, reason, body, headers) = response
        
        content_type = utils.get_header("content-type", headers)
        
        self.assertEqual(200, status)
        self.assertEqual("text/html", content_type)
Beispiel #38
0
def benefits_registration():
	""" If 'GET' method, returns the benefits registration page. If 'POST', it first checks if a
	Benefit name has been entered, if not returns the registration page with an alert (whoops). If
	so it calls the register new benefit function which will procced to check the validity of the 
	name entered. If everything goes well, the new benefit profile is returned. Otherwise the
	registration page is reloaded with an alert."""
	if request.method == "POST":
		name = request.form.get("name")
		if name:
			idBenefit = register_new_benefit(name, session['idCompany'])
			if idBenefit:
				return redirect("/beneficios/perfil/{}".format(idBenefit))
			else:
				whoops = "Este beneficio já está cadastrado para essa empresa"
				return render_template("benefits_registration.html", header = get_header(session),
																whoops = whoops)
		else:
			whoops = "Por favor insira um nome"
			return render_template("benefits_registration.html", header = get_header(session),
																whoops = whoops)
	else: # 'GET'
		return render_template("benefits_registration.html", header = get_header(session))
Beispiel #39
0
 def train(self):
     precision_max, model_max = 0, None
     for _ in range(self.train_iter):
         model = self.create_model()
         self.fit_model(model)
         precision = self.evaluate(model)
         if precision > precision_max:
             precision_max = precision
             model_max = model
     model_name = 'model_p%d.hdf5' % (int(precision_max * 1E6),)
     model_max.save(os.path.join(self.root_dir, utils.MODELS_DIR, model_name))
     print(utils.get_header('Final Model'))
     self.evaluate(model_max, plot=True)
def fetch(url):
    headers = get_header()
    session = requests.session()

    # ===========
    cookies = get_cookie(url, session, headers)
    try:
        resp = session.get(url, headers=headers, cookies=cookies)
    except Exception as e:
        print(e)
        return None
    cookies = session.cookies.get_dict()
    resp = session.get(PUBKEY_URL, headers=headers, cookies=cookies)
    searchObj = re.search(r'f=".*?";', resp.text, re.M | re.I)
    if not searchObj:
        print("找不到对应的pubkey的值")
        return None
    pubkey = searchObj.group()[3:-2]

    # ============
    cookies = session.cookies.get_dict()
    try:
        resp = session.get(SESSION_URL,
                           headers=headers,
                           cookies=cookies,
                           params={'pub': pubkey})
    except Exception as e:
        print(e)
        return None
    searchObj = re.search(r'sessionstr":".*?"', resp.text, re.M | re.I)
    if not searchObj:
        print("找不到对应的sessionstr的值")
        return None
    sessionstr = searchObj.group()[13:-1]

    # ==============
    cookies = session.cookies.get_dict()
    resp = session.get(BASE_CAPTCHA_SRC,
                       headers=headers,
                       cookies=cookies,
                       params={
                           'pub': pubkey,
                           'session': sessionstr
                       })
    if not resp.content:
        return None
    img_name = './captcha/' + ''.join(
        random.sample('1234567890qwertyuiopasdfghjklzxcvbnm', 5)) + '.png'
    with open(img_name, 'wb') as f:
        f.write(resp.content)
        print(img_name, "图片已经保存成功")
Beispiel #41
0
def apology(message, code=400):
    """ Render error message as a meme apology to user. """
    def escape(string):
        """
        Escape special characters for memegen.
        Created by Jace Browning:
        https://github.com/jacebrowning/memegen#special-characters
        """
        for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
                         ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
            string = string.replace(old, new)
        return string
    return render_template("apology.html", top = code, bottom = escape(message),
    										header = get_header(session)), code
Beispiel #42
0
    def test_update(self):

        file1contents = "file 1 contents"

        headers = {"If-None-Match": "*"}
        response = self.client.request("PUT", "/file.txt", headers, file1contents)
        (status, reason, body, headers) = response

        etag1 = utils.get_header("etag", headers)

        self.assertEqual(201, status)
        self.assertTrue(etag1 != None)
        
        file1contents = "file 1 contents - even more!"

        headers = {"If-Match": etag1}
        response = self.client.request("PUT", "/file.txt", headers, file1contents)
        (status, reason, body, headers) = response

        etag2 = utils.get_header("etag", headers)

        self.assertEqual(200, status)
        self.assertTrue(etag1 != etag2)
Beispiel #43
0
def multitrack():
    """
    Views more information about a single multitrack within a ticket given a multitrack ID.
    Gives info on status of multitrack.

    Return
    ------
    'multitrack.html': rendered template
    multitrack_id: int
        requested by the user
    ticket_status_headers: list
        headers of ticket status table
    formatted_ticket_status_headers: list
        formatted headers of ticket status table
    multitrack_status: dictionary
        contents in multitrack status table

    """
    ticket_number = request.args.get('ticket_number')
    multitrack_id = request.args.get('multitrack_id')
    db_connection = connect_db(APP)

    multitrack_status_headers = get_header(APP, 'multitracks')
    formatted_multitrack_status_headers = [
        format_headers(h) for h in multitrack_status_headers
    ]

    multitrack_status_cursor = db_connection.execute(
        'select * from multitracks where multitrack_id="{}"'.format(
            multitrack_id
        )
    )

    multitrack_status = fill_table(
        multitrack_status_headers, multitrack_status_cursor
    )

    update_multitrack_url = "/multitrack_update?multitrack_id={}&ticket_number={}".format(str(multitrack_id),ticket_number)
    ticket_url = "/ticket?ticket_number={}".format(ticket_number)
    return render_template(
        'multitrack.html', multitrack_id=multitrack_id,
        ticket_number=ticket_number,
        multitrack_status_headers=multitrack_status_headers,
        formatted_multitrack_status_headers=formatted_multitrack_status_headers,
        multitrack_status=multitrack_status,
        update_multitrack_url=update_multitrack_url,
        ticket_url=ticket_url
    )
Beispiel #44
0
def view_tickets():
    """
    Renders viewtickets.html template

    Returns
    -------
    'viewtickets.html': renders to a template
    tickets: dictionary
        empty entrys in the tickets table
    tickets_headers: list
        headers from the tickets table
    formatted_tickets_headers: list
        formatted headers from tickets table
    """
    db_connection = connect_db(APP)
    cursor = db_connection.execute('select * from tickets')

    tickets_headers = get_header(APP, 'tickets')
    formatted_tickets_headers = [format_headers(h) for h in tickets_headers]

    tickets = {}
    for name in tickets_headers:
        tickets[name] = []

    tickets['url'] = []
    tickets['delete'] = []

    for row in cursor:
        if row[1]=="Complete":
            continue
        for name, item in zip(tickets_headers, row):
            tickets[name].append(item)
        tickets['url'].append('/ticket?ticket_number={}'.format(row[0]))
        tickets['delete'].append(
            '/api/deleteticket?ticket_number={}'.format(row[0])
        )


    return render_template(
        'viewtickets.html', tickets=tickets,
        tickets_headers=tickets_headers,
        formatted_tickets_headers=formatted_tickets_headers
    )
Beispiel #45
0
def parse(bits):
    bstream = ConstBitStream(bits)
    endianness, size = get_header(bstream)
    while (bstream.pos < 8*size):
        data = get_data(bstream, endianness)
    return data    
Beispiel #46
0
def ticket():
    """
    Views more information about a single ticket given a ticket ID.
    Gives info on status of ticket, its history, and multitracks in the ticket.

    Return
    ------
    'ticket.html': rendered template
    ticket_number: int
        requested by the user
    ticket_status_headers: list
        headers of ticket status table
    formatted_ticket_status_headers: list
        formatted headers of ticket status table
    ticket_history_headers: list
        headers of ticket history table
    formatted_ticket_history_headers: list
        formatted headers of ticket history table
    multitracks_headers: list
        headers of multitracks in ticket table
    formatted_multitracks_headers: list
        formatted headers of multitracks in ticket tabls
    tickets: dictionary
        content in tickets table
    ticket_history: dictionary
        contents in ticket history table
    multitracks: dictionary
        contents in multitracks in ticket table
    update_ticket_url: string url
    add_multitrack_url: string url


    """
    db_connection = connect_db(APP)

    ticket_number = request.args.get('ticket_number')
    ticket_name = request.args.get('ticket_name')
    num_multitracks = request.args.get('num_multitracks')
    multitrack_id = request.args.get('multitrack_id')
    
    ticket_status_headers = get_header(APP, 'tickets')
    ticket_history_headers = get_header(APP, 'ticket_history')
    multitracks_headers = get_header(APP, 'multitracks')

    formatted_ticket_status_headers = [
        format_headers(h) for h in ticket_status_headers
    ]
    formatted_ticket_history_headers = [
        format_headers(h) for h in ticket_history_headers
    ]
    formatted_multitracks_headers = [
        format_headers(h) for h in multitracks_headers
    ]

    ticket_status_cursor = db_connection.execute(
        'select * from tickets where ticket_number="{}"'.format(ticket_number)
    )
    ticket_history_cursor = db_connection.execute(
        'select * from ticket_history where ticket_number="{}"'.format(ticket_number)
    )
    multitracks_cursor = db_connection.execute(
        'select * from multitracks where ticket_number="{}"'.format(ticket_number)
    )

    tickets = fill_table(ticket_status_headers, ticket_status_cursor)
    ticket_history = fill_table(ticket_history_headers, ticket_history_cursor)
    multitracks = fill_table(multitracks_headers, multitracks_cursor)
    
    multitracks['url'] = []
    multitracks_cursor = db_connection.execute(
        'select * from multitracks where ticket_number="{}"'.format(ticket_number)
    )

    multitracks['delete'] = []
    update_ticket_url = "/ticket_update?ticket_number={}".format(ticket_number)
    add_multitrack_url = "/ticket_addMultitrack?ticket_number={}&num_multitracks={}".format(ticket_number, num_multitracks)

    for row in multitracks_cursor:
        multitracks['url'].append('/multitrack?multitrack_id={}&ticket_number={}'.format(row[1], ticket_number))
        multitracks['delete'].append(
            '/api/deletemultitrack?multitrack_id={}&ticket_number={}'.format(row[1], ticket_number))

    return render_template(
        'ticket.html', ticket_number=ticket_number,
        ticket_name=ticket_name,
        multitrack_id=multitrack_id, 
        num_multitracks=num_multitracks,
        ticket_status_headers=ticket_status_headers,
        formatted_ticket_status_headers=formatted_ticket_status_headers,
        ticket_history_headers=ticket_history_headers,
        formatted_ticket_history_headers=formatted_ticket_history_headers,
        multitracks_headers=multitracks_headers,
        formatted_multitracks_headers=formatted_multitracks_headers,
        tickets=tickets,
        ticket_history=ticket_history,
        multitracks=multitracks,
        update_ticket_url=update_ticket_url,
        add_multitrack_url=add_multitrack_url

    )
Beispiel #47
0
    def serve(self, fp, check, request_host):
        """
            fp: The file pointer to write to.

            check: A function called with the effective actions (after random
            values have been calculated). If it returns False service proceeds,
            otherwise the return is treated as an error message to be sent to
            the client, and service stops.

            request_host: If this a request, this is the connecting host. If
            None, we assume it's a response. Used to decide what standard
            modifications to make if raw is not set.

            Calling this function may modify the object.
        """
        started = time.time()
        if not self.raw:
            if self.body and not utils.get_header("Content-Length", self.headers):
                self.headers.append(
                    (
                        LiteralGenerator("Content-Length"),
                        LiteralGenerator(str(len(self.body))),
                    )
                )
            if request_host:
                if not utils.get_header("Host", self.headers):
                    self.headers.append(
                        (
                            LiteralGenerator("Host"),
                            LiteralGenerator(request_host)
                        )
                    )

            else:
                if not utils.get_header("Date", self.headers):
                    self.headers.append(
                        (
                            LiteralGenerator("Date"),
                            LiteralGenerator(formatdate(timeval=None, localtime=False, usegmt=True))
                        )
                    )

        hdrs = []
        for k, v in self.headers:
            hdrs.extend([
                k,
                ": ",
                v,
                "\r\n",
            ])
        vals = self.preamble()
        vals.append("\r\n")
        vals.extend(hdrs)
        vals.append("\r\n")
        if self.body:
            vals.append(self.body)
        vals.reverse()
        actions = ready_actions(self.length(), self.actions)
        actions.reverse()
        if check:
            ret = check(self, actions)
            if ret:
                err = PathodErrorResponse(ret)
                err.serve(fp)
                return dict(
                    disconnect = True,
                    actions = actions_log(actions),
                    error = ret
                )
        disconnect = write_values(fp, vals, actions[:])
        duration = time.time() - started
        ret = dict(
            disconnect = disconnect,
            started = started,
            duration = duration,
            actions = actions_log(actions),
        )
        for i in self.logattrs:
            v = getattr(self, i)
            # Careful not to log any VALUE specs without sanitizing them first. We truncate at 1k.
            if hasattr(v, "__len__"):
                v = v[:TRUNCATE]
            ret[i] = v
        return ret