Example #1
0
def file_search(root="/", dir="", search=False):
    ex_files_prot = File.readFile("%s/exclusion_list.csv" % (root)).split("\n")

    files = get_file_names(dir)

    # 除外リストに記載されていないファイルパス一覧
    valid_filepath = []

    for f in files:
        p = Path(f)
        is_exclusion = False
        for e in ex_files_prot:
            # 除外リストのファイルがない場合
            if not Path(e).exists():
                continue
            # 除外リストのファイルと一致した場合
            if p.samefile(e):
                is_exclusion = True
                break
        if not is_exclusion:
            valid_filepath.append(f)

    for file in valid_filepath:
        Conv.converter(file, search)
        print(file + " : \033[32mOK\033[0m")

    print("converter : \033[32mALL SUCCEEDED\033[0m")
Example #2
0
def calculate_fitness(genoms, model_name, quantize_layer):
    try:
        with K.get_session().graph.as_default():
            model = model_selector(model_name)
            W_q = copy.deepcopy(g_W)
            if len(genoms.genom) > 1:
                W_q[::2] = [
                    converter(genoms.genom[i].gene)(W_q[i * 2])
                    for i in range(len(W_q) // 2)
                ]
            elif quantize_layer == -1:
                W_q[::2] = list(map(converter(genoms.genom[0].gene), W_q[::2]))
            elif quantize_layer >= 0 and quantize_layer * 2 < len(W_q):
                W_q[quantize_layer * 2] = converter(genoms.genom[0].gene)(
                    W_q[quantize_layer * 2])
            else:
                sys.exit("quantize_layer is out of index.")
            model.set_weights(W_q)
            model.compile(optimizer=optimizers.Adam(),
                          loss='categorical_crossentropy',
                          metrics=['accuracy'])
            score = model.evaluate(val_X, val_y, verbose=0)
        K.clear_session()
        return score[1]
    except:
        logger.exception(sys.exc_info()[0])
        return -1
Example #3
0
def main():
    """Entry point for RSS reader"""
    try:
        args = get_args()
        if args.verbose:
            logging.basicConfig(level=logging.INFO,
                                format='%(asctime)s %(message)s')

        if not args.date:
            response = check_response(go_for_rss(args.source))
            news_articles = xml_parser(response, args.limit)
            save_cache(news_articles, args.source)
        else:
            news_articles = read_cache(args.date, args.source, args.limit)

        if args.to_html or args.to_pdf:
            converter(news_articles, args.to_html, args.to_pdf)
        else:
            result = output_format(news_articles, args.json)
            print_result(result, args.limit)
    except CacheNotFoundError as ex:
        print(ex.__doc__)
    except GoForRssError as ex:
        print(ex.__doc__)
    except WrongResponseTypeError as ex:
        print(ex.__doc__)
    except NoDataToConvertError as ex:
        print(ex.__doc__)
Example #4
0
def launcher():

    if len(sys.argv) > 2:
        print("Too many arguments.")
        exit()

    if len(sys.argv) == 2 and not os.path.isfile(sys.argv[1]):
        print(converter.converter(sys.argv[1]))

    else:
        for line in fileinput.input():
            print(converter.converter(line))
Example #5
0
 def test_rand(self):
     from random import randint
     sol = lambda mpg: round(mpg / 4.54609188 * 1.609344, 2)
     for _ in range(40):
         n = randint(0, 10**randint(1, 5))
         self.assertEqual(converter(n), sol(n),
                          "It should work for random inputs too")
Example #6
0
def uploadLabel():
    try:
        for dirname, dirnames, filenames in os.walk('.'):
            # print path to all subdirectories first.
            for subdirname in dirnames:
                print(os.path.join(dirname, subdirname))

            # print path to all filenames.
            for filename in filenames:
                print(os.path.join(dirname, filename))
        print('ENTREI AQUI')
        isthisFile = request.files.get('file')
        print(isthisFile)
        print(isthisFile.filename)
        isthisFile.save("./input1/" + isthisFile.filename)
        print('guardou')
        global person1, person2
        person1, person2 = conv.converter()
        print("ConvPESSOA1: ", person1)
        print("ConvPESSOA2: ", person2)
    except:
        print('Algo aconteceu')
        INPUT_FOLDER_PATH = "input/"
        OUTPUT_FOLDER_PATH = "output/"
        for subdir in os.listdir(INPUT_FOLDER_PATH):
            if subdir != 'boon':
                shutil.rmtree(os.path.join(INPUT_FOLDER_PATH, subdir))
        for subdir in os.listdir(OUTPUT_FOLDER_PATH):
            if subdir != 'boon':
                shutil.rmtree(os.path.join(OUTPUT_FOLDER_PATH, subdir))

    return redirect(url_for('novo'))
Example #7
0
    def __init__(self):
        super(converter_gui, self).__init__()
        self.con = converter.converter('/dev/ttyACM0')
        
        self.setWindowTitle('SiversIMA Converter Control')
        
        hbox = QVBoxLayout(self)

        self.bt_open = QPushButton('Connect', self)
        self.bt_open.clicked.connect(self.button_clicked)

        self.bt_tx_on = QPushButton('TX ON', self)
        self.bt_tx_on.hide()
        self.bt_rx_on = QPushButton('RX ON', self)
        self.bt_rx_on.hide()

        self.le_rx_freq = QLineEdit()
        self.le_rx_freq.hide()
        self.le_tx_freq = QLineEdit()
        self.le_tx_freq.hide()

        hbox.addWidget(self.bt_open)
        hbox.addWidget(self.bt_tx_on)
        hbox.addWidget(self.bt_rx_on)
        hbox.addWidget(self.le_tx_freq)
        hbox.addWidget(self.le_rx_freq)
        
        self.setLayout(hbox)
        self.show()
    def __init__(self):
        super(converter_gui, self).__init__()
        self.con = converter.converter('/dev/ttyACM0')

        self.setWindowTitle('SiversIMA Converter Control')

        hbox = QVBoxLayout(self)

        self.bt_open = QPushButton('Connect', self)
        self.bt_open.clicked.connect(self.button_clicked)

        self.bt_tx_on = QPushButton('TX ON', self)
        self.bt_tx_on.hide()
        self.bt_rx_on = QPushButton('RX ON', self)
        self.bt_rx_on.hide()

        self.le_rx_freq = QLineEdit()
        self.le_rx_freq.hide()
        self.le_tx_freq = QLineEdit()
        self.le_tx_freq.hide()

        hbox.addWidget(self.bt_open)
        hbox.addWidget(self.bt_tx_on)
        hbox.addWidget(self.bt_rx_on)
        hbox.addWidget(self.le_tx_freq)
        hbox.addWidget(self.le_rx_freq)

        self.setLayout(hbox)
        self.show()
Example #9
0
def main():
    rate = int(input("Введите процентную ставку: "))
    money = int(input("Введите сумму: "))
    period = int(input("Введите период ведения счета в месяцах: "))

    result = account.calculate_income(rate, money, period)
    print("Параметры счета:\n", "Сумма в рублях: ", money, "\n", "Сумма в долларах: ", converter(1, money), "\n", "Сумма в евро: ", converter(2, money), "\n", "Ставка: ", rate, "\n", "Период: ", period, "\n",
          "Сумма на счете в конце периода в рублях: ", result, "\n","В евро: ", converter(2, result), "\n" "В долларах: ", converter(1, result), "\n")
Example #10
0
def final(input_filter,input_spectral,input_magnitude,input_photometric,output_filter,output_photometric):
	
	print(path_dictionary)

	save_json_file(path_dictionary)

	print(path_dictionary)
	
	result = converter(path_dictionary[str(1)],path_dictionary[str(2)],path_dictionary[str(3)],input_filter,input_spectral,float(input_magnitude),input_photometric,output_filter,output_photometric)
	# print(result)
	eel.display_final_output(result)
Example #11
0
    def run_handler(self):

        epsgIn = self.in_epsg.text()

        epsgInLabel = self.in_epsg_label.text()

        epsgOut = self.out_epsg.text()
        epsgOutLabel = self.out_epsg_label.text()

        filePath = self.filePath.text()

        if self.error_handler(epsgIn, epsgInLabel, epsgOut, epsgOutLabel,
                              filePath):
            try:
                converter(epsgIn, epsgOut, filePath)
                self.error_dialog.showMessage(
                    "conversion from {} to {} successful".format(
                        epsgIn, epsgOut))
            except:
                self.error_dialog.showMessage("ERROR: Conversion Unsuccessful")
Example #12
0
	def select_file(self):
		self.uploadStatus.setText("")
		self.file_path = QFileDialog.getOpenFileNames(self, "Select image for uploading", "", "*.png *.gif *.webp")
		self.loadBar.setMaximum(len(self.file_path[0]))
		self.loadBar.setVisible(True)
		for file in self.file_path[0]:
			self.loadBar.setValue(self.loadBar.value()+1)
			if file:
				self.FILE = converter(file)
				self.graffiti_send()
		self.loadBar.setValue(self.loadBar.value()+1)
		self.uploadStatus.setText("Everything Uploaded")
Example #13
0
 def select_file(self):
     self.uploadStatus.setText("")
     self.file_path = QFileDialog.getOpenFileNames(
         self, "Select image for uploading", "", "*.png *.gif *.webp")
     self.loadBar.setMaximum(len(self.file_path[0]))
     self.loadBar.setVisible(True)
     for file in self.file_path[0]:
         self.loadBar.setValue(self.loadBar.value() + 1)
         if file:
             self.FILE = converter(file)
             self.graffiti_send()
     self.loadBar.setValue(self.loadBar.value() + 1)
     self.uploadStatus.setText("Everything Uploaded")
Example #14
0
def load_data(responses):
    data_load_state = st.text('Loading data...')
    loop = st.checkbox(
        'Loop through all responses (might take a while, otherwise only the first response will be added)'
    )
    csv = st.checkbox('Add "data" prefix to values')
    resp_id = st.checkbox('Convert "id" to "response_id" (if applicable)')
    responses = add_data_str(responses) if csv else responses
    hugin_names_result = cnv.converter(responses, loop=loop, resp_id=resp_id)
    data_load_state.text('Loading data... Done!')
    st.markdown('<p class="header"> Convert all </p>', unsafe_allow_html=True)

    display_huginn_names(hugin_names_result)
    display_table(responses, hugin_names_result)
    select_keys(responses, hugin_names_result)
    meta_segm(responses, hugin_names_result)
Example #15
0
def convert_file():

    if request.method == 'POST':

        urlVideo = request.form['videoUrl']

        try:

            f = converter.converter(urlVideo)

            return send_from_directory(app.config['folder_video'],
                                       f,
                                       as_attachment=True)

        except:

            flash('Dirección url no válida')
            return render_template('index.html')
Example #16
0
 def test_converter(self):
     with patch('converter.convert_to_html') as mocked_convert_to_html:
         converter(self.news_articles, None, None)
         mocked_convert_to_html.assert_called_with(self.news_articles)
         # if path_to_html is provided -> call save_html
         with patch('converter.save_html') as mocked_save_html:
             converter(self.news_articles, self.path_to_html, None)
             mocked_save_html.assert_called_with(mocked_convert_to_html(),
                                                 self.path_to_html)
         # if path_to_pdf is provided -> call save_pdf
         with patch('converter.save_pdf') as mocked_save_pdf:
             converter(self.news_articles, None, self.path_to_pdf)
             mocked_save_pdf.assert_called_with(mocked_convert_to_html(),
                                                self.path_to_pdf)
Example #17
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 09:40:00 2021

@author: hmc
"""
from converter import converter
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser("Convert your data~!!")
    parser.add_argument("--yaml_path", type=str, default=None, required=True)
    args = parser.parse_args()
    _cvt = converter(args.yaml_path)
    _cvt.conversion()
Example #18
0
def test_converter():
    assert converter(10) == 3.54
    assert converter(20) == 7.08
    assert converter(30) == 10.62
    assert converter(24) == 8.50
    assert converter(36) == 12.74
        Id, w, c, p, h, d = (replace.replace(nstatus[b]))

        aanimeId.append(Id)
        watching += w
        completed += c
        planned += p
        hold += h
        dropped += d

    atotal = watching + completed + planned + hold + dropped

    print('Done! ')
    #replacing Id's
    print('Replacing ID\'s: ')
    for c in range(noofanime):
        aanimeId.append(converter.converter(nanimeId[c]))

        #removing anime without anilist links
        if aanimeId[c] == None:
            aanimeId.pop(c)
            astatus.pop(c)
    print('Done! ')
    #print(aanimeId)
    #print(astatus)
    #building .xml file
    print('Now Building: ')
    convertedlistani = open('convertedlistani.xml', 'w')
    convertedlistani.write('<?xml version="1.0" encoding="UTF-8" ?>')

    myanimelist = ET.Element('myanimelist')
    myinfo = ET.SubElement(myanimelist, 'myinfo')
Example #20
0
	def actual_import(self, cr, uid, ids, context=None):
		i = 0
		ex = 0
		upd = 0
		date = False

		conv = converter.converter()

		partner = self.pool.get('res.partner')
		cash = self.pool.get('reliance.partner_cash')
		
		for import_cash in self.browse(cr, uid, ids, context=context):

			if not import_cash.client_id:
				ex = ex + 1
				self.write(cr, uid, import_cash.id ,  {'notes':'empty line'}, context=context)
				cr.commit()
				continue

			########## cari partner dulu ####################
			pid = partner.search(cr, uid, [( 'ls_client_id','=', import_cash.client_id)], context=context)
			if pid:
				###### cari existing Cash record ############
				cid = cash.search(cr, uid, [('partner_id','=', pid[0] )], context=context)

				###### convert date ############
				if import_cash.date:
					date = conv.convert_date(cr, uid, self, import_cash, "date", "%Y-%m-%d",ex, context=context)
					if not date:
						continue

				###### convert cash_on_hand ############
				cash_on_hand = conv.convert_float(cr, uid, self, import_cash, "cash_on_hand", ",", ".", ex, context=context)
				if cash_on_hand is False:
					continue

				###### convert saldo_t1 ############
				saldo_t1 = conv.convert_float(cr, uid, self, import_cash, "saldo_t1", ",", ".", ex, context=context)
				if saldo_t1 is False:
					continue

				###### convert saldo_t2 ############
				saldo_t2 = conv.convert_float(cr, uid, self, import_cash, "saldo_t2", ",", ".", ex, context=context)
				if saldo_t2 is False:
					continue

				data = {
					"partner_id"	: 	pid[0],	
					"date"			:	date ,
					"cash_on_hand"	:	cash_on_hand,
					# "net_ac"		:	import_cash.net_ac,
					"saldo_t1"		:	saldo_t1,
					"saldo_t2"		:	saldo_t2,
				}
				if not cid:
					cash.create(cr,uid,data,context=context)
					i = i + 1
				else:
					upd = upd + 1
					cash.write(cr, uid, cid, data, context=context)
					_logger.warning('Update Partner Cash for ClientID=%s' % (import_cash.client_id))
			else:
				ex = ex + 1
				self.write(cr, uid, import_cash.id ,  {'notes':'No Partner'}, context=context)
				_logger.warning('Partner ID not found for ClientID=%s' % import_cash.client_id)
				cr.commit()
				continue

			cr.execute("update reliance_import_ls_cash set is_imported='t' where id=%s" % import_cash.id)
			cr.commit()


		raise osv.except_osv( 'OK!' , 'Done creating %s partner_cash, skipped=%s,updated=%s ' % (i,ex, upd) )			
Example #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from extractor import extractor
from normalizer import normalizer
from converter import converter

if __name__ == "__main__":

  results = extractor()
  nodes, ties = normalizer(results)
  converter(nodes, ties)
Example #22
0
def search(user, token, repo, dorklist):

    try:
        if dorklist:
            try:
                dorks = open(dorklist).read().splitlines()
            except:
                print('Error: Could not find the pointed dork list.')
                return
        else:
            dorks = open('./small_dorklist.txt').read().splitlines()

        for string in dorks:

            if token:
                if repo:
                    parsed_response = requests.get(
                        'https://api.github.com/search/code?q=%s' %
                        urllib.quote(
                            ('repo:' + user + '/' + repo + ' ' + string)),
                        headers={'Authorization': 'token %s' % token})
                else:
                    parsed_response = requests.get(
                        'https://api.github.com/search/code?q=%s' %
                        urllib.quote(('user:'******' ' + string)),
                        headers={'Authorization': 'token %s' % token})
            else:
                if repo:
                    parsed_response = requests.get(
                        'https://api.github.com/search/code?q=%s' %
                        urllib.quote(
                            ('repo:' + user + '/' + repo + ' ' + string)))
                else:
                    parsed_response = requests.get(
                        'https://api.github.com/search/code?q=%s' %
                        urllib.quote(('user:'******' ' + string)))

            if parsed_response.status_code == 200 and len(
                    parsed_response.json()['items']) != 0:
                response = parsed_response.json()['items']

                size = len(response)

                for i in range(size):

                    class ResponseObj:
                        repository = response[i]['repository']
                        fileName = response[i]['name']
                        repoName = repository['name']
                        path = response[i]['path']
                        fileUrl = response[i]['html_url']
                        repoUrl = repository['url']
                        resultUrl = response[i]['url']

                    if token:
                        request = requests.get(
                            ResponseObj.resultUrl,
                            headers={'Authorization': 'token %s' % token})
                    else:
                        request = requests.get(ResponseObj.resultUrl)

                    if request.status_code == 200:
                        encodedContent = request.json()['content']
                    else:
                        print('Nothing found with %s\n' % string)

                    if 'filename:' not in string and 'extension:' not in string:

                        print(Fore.CYAN,
                              "\n=================================\n",
                              Style.RESET_ALL)
                        print("Content searched: ", string, "\nRepository: ",
                              ResponseObj.repoName, "\nFile: ",
                              ResponseObj.fileName, "\nUrl: ",
                              ResponseObj.fileUrl, "\nRepo Url: ",
                              ResponseObj.repoUrl, "\n")

                        code = converter(encodedContent, string)
                        if code == False:
                            code = 'There was an issue searching for the code snippet.'

                        print("\nCode snippet:\n%s" % code)

                    else:
                        print(Fore.CYAN,
                              "\n=================================\n",
                              Style.RESET_ALL)
                        print("Content searched: ", string, "\nRepository: ",
                              ResponseObj.repoName, "\nFile: ",
                              ResponseObj.fileName, "\nUrl: ",
                              ResponseObj.fileUrl, "\nRepo Url: ",
                              ResponseObj.repoUrl, "\n")

            elif parsed_response.status_code == 403:
                print(
                    Fore.GREEN +
                    '\nLet\'s respect GitHub API Rate Limit, give me a minute to rest.'
                )
                sleep(60)

            else:
                print(Fore.RED + '\nNothing found with %s' % string)

        print(Fore.CYAN + '\nEverything done!\n')

    except KeyboardInterrupt:
        print(Fore.RED + '\nSearch interrupted by the user.')
    pybar_runs = [
        pybar_run(255, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(256, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(260, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
        pybar_run(261, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(262, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(263, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
        pybar_run(264, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(265, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(266, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
        pybar_run(268, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(269, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(270, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
        pybar_run(271, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(272, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(273, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
        pybar_run(274, run_type='analog_scan', febs=ALL_FEBS),
        pybar_run(275, run_type='threshold_scan', febs=ALL_FEBS),
        pybar_run(277, run_type='noise_occupancy_tuning', febs=ALL_FEBS),
    ]

    converter = converter(pybar_to_yarr=True)
    input_dir = '/Volumes/01/FullStaveRun_2A_CoolantM15/'
    output_dir = './json_out'

    for pb_run in pybar_runs:
        for feb in pb_run.febs:
            print
            convert_onefeb_onerun(converter, pb_run.run_number, feb,
                                  pb_run.run_type, input_dir, output_dir)
Example #24
0
def convertXML2JSON(xmlStr):
    return converter(xmlStr)
Example #25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from extractor import extractor
from normalizer import normalizer
from converter import converter

if __name__ == "__main__":

    results = extractor()
    nodes, ties = normalizer(results)
    converter(nodes, ties)
Example #26
0
 def __convert(self):
     print(os.path.basename(self.__file))
     converter.converter(os.path.basename(self.__file))
Example #27
0
# load files
files = list(glob.glob(os.path.join("data", '*')))

correct_times = [
    228, 3026, 3665, 3309, 3191, 3618, 3446, 3821, 3634, 3070, 6398, 1492
]
t = tabel([
    'File name', 'Correct time', 'Calculated time',
    'Is calculated time correct?'
])
index = 0
correct = 0
x = read.Reader()

for file in files:
    x.read(file)
    converted_tasks = converter.converter(x.my_data)
    carlier_object = carlier_task.Carlier_Task(converted_tasks)
    c_max = carlier.do_carlier(carlier_object)
    t.add_row(
        [file[5:], correct_times[index], c_max, correct_times[index] == c_max])
    if correct_times[index] == c_max:
        correct += 1
    index += 1
string = str(str(correct) + "/" + str(index))
print(string)
t.add_row(["", "", "", ""])
t.add_row(["", "", "Passed: ", string])

print(t)
Example #28
0
 def test_ip4_allowed_range_returns_same(self):
     self.assertEqual(converter.converter(u'192.168.0.0/24'),
                      ['192.168.0.0/24'])
Example #29
0
		self.update()
		self.geometry(self.geometry())
		self.minsize(self.winfo_width(), self.winfo_height())

	def setGroup(self, var, evt):
		self.inUnitCombo.configure(values=self.units.getUnitsList(self.unitGroupVar.get()))
		self.outUnitCombo.configure(values=self.units.getUnitsList(self.unitGroupVar.get()))
		self.inUnitCombo.current(0)
		self.outUnitCombo.current(0)
		self.resetValues(None)

	def resetValues(self, evt):
		self.inValueVar.set(0.0)
		self.outValueVar.set(0.0)

	def convert(self, evt=None):
		try:
			self.inValueEntry.configure(foreground="black")
			value = self.inValueVar.get()
			self.outValueVar.set(self.con.convert(value, self.inUnitVar.get(), self.outUnitVar.get()))

		except ValueError:
			self.inValueEntry.configure(foreground="red")
			self.outValueVar.set(0.0)

if __name__ == "__main__":
	manager = unit_manager.unit_manager()
	con = converter.converter(manager)
	app = app(None, manager, con)
	app.title("Unit Calculator")
	app.mainloop()
Example #30
0
 def test_ip6_allowed_range_returns_same(self):
     self.assertEqual(converter.converter(u'fe80::/64'),
                      ['fe80::/64'])
Example #31
0
 def test_ip6_range_returns_allowed_range(self):
     self.assertEqual(converter.converter(u'fe80::/63'),
                      ['fe80::/64', 'fe80:0:0:1::/64'])
Example #32
0
async def sync_channels(api_key, links, an_ag_endpoints, spreadsheet_id,
                        google):
    """
        Syncs the AG reps from Action Network with the Telegram broadcasts.
        First gets all registered AG's from AN and filters these on the
        five regions. Checks if any of these AG's are not yet in the
        regions corresponding Telegram channel. If so, adds them.

        Logs any made changes to the 'logs' global.

        Params:
        - api_key (str) : the api key for AN.
        - links (dict) : a dictionary which maps the names a region to the
                         invite link of the region's Telegram channel.
        - an_ag_endpoints (list) : a list of endpoints to the AN forms where
                                   AG's are registered.
        - spreadsheet_id (string) : id of the used google spreadsheet.
        - google (?) : api object used to make api calls.

    """
    ags = get_all_ags(api_key, an_ag_endpoints)
    ags_formatted = []
    ags_in_telegram_channel = []
    ags_not_in_telegram_channel = []

    # Format list of AG's.
    for ag in ags:
        ag["region"] = converter("municipality", "region", ag["Municipality"])
        if not ag["region"]:
            continue
        ag["telegram"] = True  # Will be set to False if AG is not added to channel after this function finishes.
        ag["Phone number"] = convert_phone_number(ag["Phone number"])
        if ag["Phone number"]:  # Becomes None if number is invalid.
            ags_formatted.append(ag)

    # Check which formatted AG's are already in telegram channels.
    ags_in_telegram_channel = [
        ag for region in regions
        for user in await client.get_participants(links[region]) if user.phone
        for ag in ags_formatted if user.phone in ag["Phone number"]
    ]

    # Add reps to telegram channel.
    for ag in [
            ag for ag in ags_formatted if ag not in ags_in_telegram_channel
    ]:
        # On succesful add, send welcome message and log.
        try:
            await add_user(ag, links)
            # logs["added"].append(filter_ag(ag))
            await send_invite(ag, links)
        # User doesn't have telegram.
        except IndexError:
            ag["telegram"] = False
            # if not ag in logs["no_telegram"]:
            # logs["no_telegram"].append(filter_ag(ag))
        except Exception as e:
            print("Error when adding rep: {}".format(e))
            # if not ag in logs["error"]:
            # logs["error"].append((filter_ag(ag), e))

    # Update the google sheet.
    update_ags_on_sheet(spreadsheet_id, google, ags_formatted)
Example #33
0
 def test_ip6_range_with_host_bits_returns_allowed_range(self):
     self.assertEqual(converter.converter(u'fe80::dead:beef/63'),
                      ['fe80::/64', 'fe80:0:0:1::/64'])
Example #34
0
 def test_ip4_range_returns_allowed_range(self):
     self.assertEqual(converter.converter(u'192.168.0.0/23'),
                      ['192.168.0.0/24', '192.168.1.0/24'])
     self.assertEqual(converter.converter(u'192.168.0.0/30'),
                      ['192.168.0.0/32', '192.168.0.1/32',
                       '192.168.0.2/32', '192.168.0.3/32'])
Example #35
0
        return (numberOfDocuments - relevantDocs + 0.5) / (relevantDocs + 0.5)
    else:
        return (numberOfDocuments + 0.5) / 0.5


# Main. The program starts from here
if __name__ == "__main__":

    # Command line arguments all loaded into proper local variables
    indexFile = sys.argv[1]
    queryFile = sys.argv[2]
    maximumResults = int(sys.argv[3])

    # Constant parameters in the problem statement
    k1 = 1.2
    b = 0.75
    k2 = 100

    parameterTuple = converter(indexFile)
    index = parameterTuple[0]
    uniqueDocuments = parameterTuple[1]  # Set of Docs
    numberOfDocuments = len(uniqueDocuments)  # Size of Corpus
    documentLength = parameterTuple[2]  # Size of each document in a Dictionary

    querySet = queries(queryFile)  # Set of Queries
    queryTerms = queryProcessor(querySet)  # Tokenised query terms in a Dictionary

    avgDocLength = sum(documentLength.values()) / numberOfDocuments  # Average document length

    docScore(maximumResults)  # Function call which computes document score
Example #36
0
import converter
sum_ = 0
for x in range(1, 1001):
    string = converter.converter(x).replace(" ", '')
    sum_ += len(string)
print(sum_)
Example #37
0
 def test_ip4_range_with_host_bits_returns_allowed_range(self):
     self.assertEqual(converter.converter(u'192.168.0.1/23'),
                      ['192.168.0.0/24', '192.168.1.0/24'])