Exemplo n.º 1
0
def publish(html_file, name='', short=False, bypass=False):
    name = url_encode(name)

    try:
        with open(html_file, 'r') as f:
            html = f.read()
    except (FileNotFoundError, IsADirectoryError) as e:
        print(e)
        exit()

    data = base64.b64encode(
        lzma.compress(bytes(html, encoding="utf-8"),
                      format=lzma.FORMAT_ALONE,
                      preset=9))

    url = f"https://itty.bitty.site/#{name}/{data.decode('utf-8')}"
    size = len(bytes(url, encoding="utf-8"))

    if size > 2048 and not bypass:
        print(
            "Size too big to be published at https://itty.bitty.site/ (Maximum allowed: 2048 bytes)"
        )
    elif short:
        from shorten import shorten
        print(shorten(url))
    else:
        print(url)
    print(f"{size} Bytes")
Exemplo n.º 2
0
def prprTxt(entry):
    tweetText = cut(
        entry.summary.replace("<br/>",
                              ". ").replace("<br />",
                                            ". ").split("Press Contacts")[0])
    tweetText += "\n" + shorten(entry.link)
    return tweetText
Exemplo n.º 3
0
def makePost():
    headline = "The British military made a subtle change before showing off its newest aircraft carrier — and avoided an awkward Magic Spell https://goo.gl/8J4rhV"
    article = wordSwap.getHeadline()
    headline = article[0]
    art_url = article[1]
    shorter = (shorten.shorten(art_url))
    headline = headline + "\n" + shorter
    while (len(headline) > 140) or art_url in oldurls:
        article = wordSwap.getHeadline()
        headline = article[0]
        art_url = article[1]
        shorter = (shorten.shorten(art_url))

        headline = headline + "\n" + shorter

    tweet.sendTweet(headline)
    # add article to the list
    oldurls.append(art_url)
Exemplo n.º 4
0
    def __str__(self):
        fields = []
        for k, field in self._meta.fields.items():
            v = getattr(self, k)

            if isinstance(field, TextField):
                if v:
                    v = repr(shorten(v))

            elif isinstance(field, ForeignKeyField):
                k = f'{k}_id'
                if v:
                    v = v.id

            fields.append(f'{k}={v}')

        return self.__class__.__name__ + '(' + ', '.join(fields) + ')'
def upload_and_share(file_path):
    oc = login()

    destination = config.OWNCLOUD_DIR + "/" + get_filename(file_path)

    try:
        # Try to upload file.
        oc.put_file(destination, file_path)
    except owncloud.ResponseError as inst:
        # If it fails because the directory does not yet exist,
        # create the directory and try to upload again.
        if 'HTTP error: 404' in inst.args:
            oc.mkdir(config.OWNCLOUD_DIR)
            oc.put_file(destination, file_path)
        else:
            raise

    # Share file.
    link_info = oc.share_file_with_link(destination)

    # Return shortened.
    return shorten(link_info.link)
Exemplo n.º 6
0
def upload_and_share(file_path):
    oc = login()

    destination = config.OWNCLOUD_DIR + "/" + get_filename(file_path)

    try:
        # Try to upload file.
        oc.put_file(destination, file_path)
    except owncloud.ResponseError as inst:
        # If it fails because the directory does not yet exist,
        # create the directory and try to upload again.
        if 'HTTP error: 404' in inst.args:
            oc.mkdir(config.OWNCLOUD_DIR)
            oc.put_file(destination, file_path)
        else:
            raise

    # Share file.
    link_info = oc.share_file_with_link(destination)

    # Return shortened.
    return shorten(link_info.link)
Exemplo n.º 7
0
 def test_loremipsum_lor(self):
     shortened = shorten("loremipsum", 6)
     self.assertEqual(shortened, "lor...")
Exemplo n.º 8
0
 def test_loremipsum_unchanged(self):
     shortened = shorten("loremipsum", 10)
     self.assertEqual(shortened, "loremipsum")
Exemplo n.º 9
0
        images.append(image_filename)
        images.append(image_filename + ".jpg")
        imajin = InlineImage(doc,
                             image_filename + ".jpg",
                             height=Inches(3.97),
                             width=Inches(6.25))
    context['projects'].append({
        "page_break":
        R('\f'),
        'description':
        post['d'],
        'title':
        post['t'],
        'year':
        '2019',
        'role':
        'programmer',
        'link':
        shorten(post['p'], post['t']) if post['p'] else
        shorten(post['g'], post['t']) if post['g'] and post['t'] else '-',
        'image':
        imajin
    })

doc.render(context)
doc.save("generated_resume.docx")
for image in images:
    os.remove(image)
convert_to("./", "generated_resume.docx")
os.remove("generated_resume.docx")
Exemplo n.º 10
0
def save(url):
    res = redis.get(REDIS_URL_FMT.format(url))
    if res is not None:
        return res
    else:
        return save_shortest(url, shorten(url))
Exemplo n.º 11
0
import shorten as func

print("Welcome to shorten!")
print("Here you can store full and shortened name of website.")

a = input("Enter full-version: ")
b = input("Enter short-version: ")

dictmain = {}
func.shorten(dictmain, b, a)

c = input("Print? Y/N ")
if c is ('y' or 'Y'):
    print(dictmain)

print("Do you want to add another link? Y/N ")
c = input()
if c is ('y' or 'Y'):
    a = input("Enter full-version ")
    b = input("Enter short-version ")
    func.shorten(dictmain, b, a)
else:
    pass

c = input("Enter short-version to get full: ")
print("Your full version: ", func.shorten(dictmain, c, None))
Exemplo n.º 12
0
def results(path=None):
    path = shorten.shorten(session)
    session['path'] = path
    session['message'] = ''
    return render_template('results.html', path=path)
Exemplo n.º 13
0
def main():
    """
    Add parsing functionality and arguments
    Helpful arguments such as -e to create executables automatically
    And -f to run Stage 4 in a loop automatically
    """
    parser = ArgumentParser()
    parser.add_argument("file", help="the file to work on")
    parser.add_argument("-p", "--print", help="output to stdout instead of file", action="store_true")
    parser.add_argument("-v", "--verbose", help="display the reduction percentage of the new file", action="store_true")
    parser.add_argument("-e", "--execute", help="have the driver generate executables of the original and abstracted sources", action="store_true")
    parser.add_argument("-f", "--final", help="have the driver run to completion instead of just abstracting the first function it finds", action="store_true")
    args = parser.parse_args()

    if "." not in args.file:
        print("Error: invalid file name")
        exit()

    file_name = args.file.split(".")

    # Stage 1
    if file_name[-1] == "c":
        # run gcc
        gcc_call = ["gcc"]+gcc_args+[reconstruct_name(file_name)]
        ret = call(gcc_call)
        # if gcc had an error then exit
        if ret != 0:
            exit()
        file_name[-1] = "s"

    # Stage 2
    if file_name[-1] == "s" and not (file_name[-2] == "orig" or file_name[-2] == "pp"):
        #call my preprocessor
        with open(reconstruct_name(file_name), "r") as fin:
            lines = fin.read().splitlines()
            processed = pp.process(lines)
            #print("\n".join(str(e) for e in processed))
            file_name[-1] = "orig.s"
            file_name = reconstruct_name(file_name).split(".")
            #write out the processed lines
            with open(reconstruct_name(file_name), "w") as fout:
                for c in processed:
                    fout.write(c)
                    fout.write("\n")
        if args.execute:
            make_executable(file_name)


    # Stage 3
    if file_name[-2] == "orig":
        orig = reconstruct_name(file_name)
        file_name[-2] = "pp"
        new = reconstruct_name(file_name)
        cp_call = ["cp", orig, new]
        ret = call(cp_call)
        if ret != 0:
            exit()

    # Stage 4
    if file_name[-2] == "pp":
        cont = True
        while True and cont:
            #run the actual procedural abstraction
            program = None
            with open(reconstruct_name(file_name), "r") as fin:
                program = fin.read().splitlines()
            new_program = shorten.shorten(program)
            if len(new_program) >= len(program):
                if len(new_program) > len(program) or reduce(lambda a, c: a and c[0] == c[1], zip(new_program, program), True):
                    print("No changes made", file=sys.stderr)
                    break
                print("File not shortened", file=sys.stderr)
            if not args.print:
                with open(reconstruct_name(file_name), "w") as fout:
                    for c in new_program:
                        fout.write(c)
                        fout.write("\n")
            else:
                print("\n".join(new_program))
                print()
                cont = False
            if args.verbose:
                print(float(len(new_program))/len(program))
            if not args.final:
                break
        if args.execute:
            make_executable(file_name)
def results(path=None):
    path = shorten.shorten(session)
    session['path'] = path
    session['message'] = ''
    return render_template('results.html', path=path)