Beispiel #1
0
 def __init__(self, m, n, seed = None):
     randseed(seed) # For reproducibility
     self.m = m
     self.n = n
     self.x_pos = np.zeros((0, m + n + 1), dtype = int)
     self.y_pos = np.zeros((0, m + n + 1), dtype = int)
     self.D = np.zeros(0, dtype = float)
    def make_map(self,
                 player,
                 entities,
                 *args,
                 room_min_size=8,
                 room_max_size=15,
                 min_rooms=8,
                 max_rooms=30,
                 bsp_depth=4,
                 bsp_range=0.15,
                 ratio_vh=1,
                 ratio_hv=1,
                 ratio_d=0,
                 hall_rand=False,
                 circ_rooms=0,
                 rect_rooms=1,
                 max_monsters_per_room=0,
                 max_items_per_room=0,
                 **kwargs):
        map_width = self.width - 1
        map_height = self.height - 1
        randseed(str(self.seed) + str(self.dlevel))
        self.rect_rooms = rect_rooms
        self.circ_rooms = circ_rooms

        while True:
            self.rooms = []
            self.tiles = self.initialize_tiles()
            parts = []
            space = Rect(0, 0, map_width, map_height)

            self.partition(space, parts, bsp_depth, bsp_range, room_min_size,
                           room_max_size)
            # for part in parts:
            #    self.rooms.append(part)
            self.place_rooms(parts, room_min_size, room_max_size)
            numrooms = len(self.rooms)
            if min_rooms < numrooms < max_rooms:
                break
        if hall_rand:
            self.make_halls_random(player, ratio_vh, ratio_hv, ratio_d)
        else:
            self.make_halls(player, ratio_vh, ratio_hv, ratio_d)
        self.place_player(player)
        for room in self.rooms:
            if room is not self.rooms[0]:
                self.place_entities(room, entities)
        self.place_stairs_down(self.rooms[-1], entities)
Beispiel #3
0
def rand_color(s):
    randseed(s)
    return "#{:02x}{:02x}{:02x}".format(randint(0, 255), randint(0, 255),
                                        randint(0, 255))
def seed(newSeed):
    """Set seed for the random number generator."""
    randseed(newSeed)
Beispiel #5
0
def sfn_cit_ref(d: defaultdict) -> tuple:
    """Return sfn, citation, and ref."""
    cite_type = TYPE_TO_CITE(d['cite_type'])
    if not cite_type:
        logger.warning('Unknown citation type: %s, d: %s', cite_type, d)
        cite_type = ''
    if cite_type in ('کتاب', 'ژورنال', 'وب'):
        cit = '* {{یادکرد ' + cite_type
    else:
        return en_citations(d)

    authors = d['authors']
    if authors:
        cit += names2para(authors, 'نام', 'نام خانوادگی', 'نویسنده')
        sfn = '&lt;ref&gt;{{پک'
        for first, last in authors[:4]:
            sfn += ' | ' + last
    else:
        sfn = '&lt;ref&gt;{{پک/بن'

    editors = d['editors']
    if editors:
        cit += names2para(
            editors, 'نام ویراستار', 'نام خانوادگی ویراستار', 'ویراستار')

    translators = d['translators']
    if translators:
        cit += names1para(translators, 'ترجمه')

    others = d['others']
    if others:
        cit += names1para(others, 'دیگران')

    year = d['year']
    if year:
        sfn += ' | ' + year

    if cite_type == 'book':
        booktitle = d['booktitle'] or d['container-title']
    else:
        booktitle = None

    title = d['title']
    if booktitle:
        cit += ' | عنوان=' + booktitle
        if title:
            cit += ' | فصل=' + title
    elif title:
        cit += ' | عنوان=' + title
        sfn += ' | ک=' + d['title']

    if cite_type == 'ژورنال':
        journal = d['journal'] or d['container-title']
    else:
        journal = d['journal']

    if journal:
        cit += ' | ژورنال=' + journal
    else:
        website = d['website']
        if website:
            cit += ' | وبگاه=' + website

    chapter = d['chapter']
    if chapter:
        cit += ' | فصل=' + chapter

    publisher = d['publisher'] or d['organization']
    if publisher:
        cit += ' | ناشر=' + publisher

    address = d['address'] or d['publisher-location']
    if address:
        cit += ' | مکان=' + address

    edition = d['edition']
    if edition:
        cit += ' | ویرایش=' + edition

    series = d['series']
    if series:
        cit += ' | سری=' + series

    volume = d['volume']
    if volume:
        cit += ' | جلد=' + volume

    issue = d['issue'] or d['number']
    if issue:
        cit += ' | شماره=' + issue

    ddate = d['date']
    if ddate:
        if isinstance(ddate, str):
            cit += ' | تاریخ=' + ddate
        else:
            cit += ' | تاریخ=' + date.isoformat(ddate)
    elif year:
        cit += ' | سال=' + year

    isbn = d['isbn']
    if isbn:
        cit += ' | شابک=' + isbn

    issn = d['issn']
    if issn:
        cit += ' | issn=' + issn

    pmid = d['pmid']
    if pmid:
        cit += ' | pmid=' + pmid

    pmcid = d['pmcid']
    if pmcid:
        cit += ' | pmc=' + pmcid

    doi = d['doi']
    if doi:
        cit += ' | doi=' + doi

    oclc = d['oclc']
    if oclc:
        cit += ' | oclc=' + oclc

    jstor = d['jstor']
    if jstor:
        cit += f' | jstor={jstor}'
        jstor_access = d['jstor-access']
        if jstor_access:
            cit += f' | jstor-access=free'

    pages = d['page']
    if cite_type == 'ژورنال':
        if pages:
            cit += ' | صفحه=' + pages

    url = d['url']
    if url:
        # Don't add a DOI URL if we already have added a DOI.
        if not doi or not DOI_URL_MATCH(url):
            cit += ' | پیوند=' + url
        else:
            # To prevent addition of access date
            url = None

    archive_url = d['archive-url']
    if archive_url:
        cit += (
            f' | پیوند بایگانی={archive_url}'
            f' | تاریخ بایگانی={d["archive-date"].isoformat()}'
            f" | پیوند مرده={('آری' if d['url-status'] == 'yes' else 'نه')}")

    language = d['language']
    if language:
        language = TO_TWO_LETTER_CODE(language.lower(), language)
        if cite_type == 'وب':
            cit += f' | کد زبان={language}'
        else:
            cit += f' | زبان={language}'
        sfn += f' | زبان={language}'

    if pages:
        sfn += f' | ص={pages}'
    # Seed the random generator before adding today's date.
    randseed(cit)
    ref_name = (
        randchoice(ascii_lowercase)  # it should contain at least one non-digit
        + ''.join(randchoice(LOWER_ALPHA_DIGITS) for _ in range(4)))
    if url:
        cit += f' | تاریخ بازبینی={date.today().isoformat()}'

    if not pages and cite_type != 'وب':
        sfn += ' | ص='

    cit += '}}'
    sfn += '}}\u200F&lt;/ref&gt;'
    # Finally create the ref tag.
    ref = cit[2:]
    if pages and ' | صفحه=' not in ref:
        ref = f'{ref[:-2]} | صفحه={pages}}}}}'
    elif not url:
        ref = f'{ref[:-2]} | صفحه=}}}}'
    ref = f'&lt;ref name="{ref_name}"&gt;{ref}\u200F&lt;/ref&gt;'
    return sfn, cit, ref
Beispiel #6
0
def play_game():
    # CONSTANTS
    board_size = 8 * 2 + 1  # Must be odd number (2n + 1)
    square_size = 32

    # INIT STUFF
    pg.init()
    pg.display.set_caption(f"Men of Bombs: Ghost Trick v{__version__}")
    screen = pg.display.set_mode(
        (board_size * square_size, board_size * (square_size + 3)),
        pg.HWSURFACE | pg.DOUBLEBUF)

    background = pg.image.load("sprites/background.png").convert()
    Tile.atlas = pg.image.load("sprites/spriteatlas.png").convert()
    Tile.atlas.set_colorkey(0x000000)

    board = Board(board_size, square_size)
    screen = Window(screen, board, background)
    clock = pg.time.Clock()
    randseed()

    config1 = {pg.K_w: 0, pg.K_d: 1, pg.K_s: 2, pg.K_a: 3}
    config2 = {pg.K_UP: 0, pg.K_RIGHT: 1, pg.K_DOWN: 2, pg.K_LEFT: 3}
    frame = 0

    # CREATE ACTORS & VARIABLES
    p1 = entities.Player(board, [3, 3], 8)
    p2 = entities.Player(board, [9, 9], 9)

    # GAME LOOP
    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            elif event.type == pg.KEYDOWN:
                if event.key in config1:
                    p1.handle_movement(config1[event.key], True)
                elif event.key == pg.K_e:
                    p1.place_bomb()
                elif event.key in config2:
                    p2.handle_movement(config2[event.key], True)
                elif event.key == pg.K_l:
                    p2.place_bomb()
            elif event.type == pg.KEYUP:
                if event.key in config1:
                    p1.handle_movement(config1[event.key], False)
                elif event.key in config2:
                    p2.handle_movement(config2[event.key], False)

        if frame == 0:
            # Resolve bomb men
            if p1.bomb: p1.bomb.update()
            if p2.bomb: p2.bomb.update()
            if p1.update(p2):
                running = False
            if p2.update(p1):
                running = False

        # Wait for framerate & update counter & board
        screen.update()
        clock.tick(60)
        frame = (frame + 1) % 10
                        property_desc = {
                            "component_name":
                            "Comp%d.%d" % (comp_type_id, comp_id),
                            "component_type": "CompTyp%d" % comp_type_id,
                            "property_name": "prop%d" % prop_id,
                            "property_type": "DOUBLE",
                            "property_type_desc": None,
                            "meta": meta,
                            "lock": None,
                            "chunk_size": 60
                        }
                    properties_collection.insert(property_desc)


if __name__ == '__main__':
    randseed(SEED)

    client = MongoClient(HOST)
    db = client.ctamonitoringtest
    chunks_collection = db.chunks
    properties_collection = db.properties
    systems_collection = db.systems
    statistics_collection = db.statistics

    if systems_collection.count():
        raise RuntimeError("systems already exist")
    if properties_collection.count():
        raise RuntimeError("properties already exist")

    properties_collection.create_index([("system_name", pymongo.ASCENDING)])
    properties_collection.create_index([("component_name", pymongo.ASCENDING)])
Beispiel #8
0
def citations(d) -> tuple:
    """Create citation templates using the given dictionary."""
    type_ = d.get('type')
    if type_ == 'book':
        cite = '* {{یادکرد کتاب'
    elif type_ in ['article', 'jour']:
        cite = '* {{یادکرد ژورنال'
    elif type_ == 'web':
        cite = '* {{یادکرد وب'
    else:
        raise KeyError(type_ + " is not a valid value for d['type']")

    authors = d.get('authors')
    if authors:
        cite += names2para(authors, 'نام', 'نام خانوادگی', 'نویسنده')
        sfn = '&lt;ref&gt;{{پک'
        for author in authors[:4]:
            sfn += ' | ' + author.lastname
    else:
        sfn = '&lt;ref&gt;{{پک/بن'
    editors = d.get('editors')
    if editors:
        cite += names2para(editors, 'نام ویراستار', 'نام خانوادگی ویراستار',
                           'ویراستار')
    translators = d.get('translators')
    if translators:
        cite += names1para(translators, 'ترجمه')
    others = d.get('others')
    if others:
        cite += names1para(others, 'دیگران')
    year = d.get('year')
    if year:
        sfn += ' | ' + year
    title = d.get('title')
    if title:
        cite += ' | عنوان=' + title
        sfn += ' | ک=' + d['title']
    journal = d.get('journal')
    if journal:
        cite += ' | ژورنال=' + journal
    else:
        website = d.get('website')
        if website:
            cite += ' | وب‌گاه=' + website
    publisher = d.get('publisher')
    if publisher:
        cite += ' | ناشر=' + publisher
    address = d.get('address')
    if address:
        cite += ' | مکان=' + address
    series = d.get('series')
    if series:
        cite += ' | سری=' + series
    volume = d.get('volume')
    if volume:
        cite += ' | جلد=' + volume
    issue = d.get('issue')
    if issue:
        cite += ' | شماره=' + issue
    ddate = d.get('date')
    if ddate:
        if isinstance(ddate, str):
            cite += ' | تاریخ=' + ddate
        else:
            cite += ' | تاریخ=' + date.isoformat(ddate)
    if year:
        cite += ' | سال=' + year
    month = d.get('month')
    if month:
        cite += ' | ماه=' + month
    isbn = d.get('isbn')
    if isbn:
        cite += ' | شابک=' + isbn
    issn = d.get('issn')
    if issn:
        cite += ' | issn=' + issn
    pmid = d.get('pmid')
    if pmid:
        cite += ' | pmid=' + pmid
    pages = d.get('pages')
    if type_ in ('article', 'jour'):
        if pages:
            cite += ' | صفحه=' + pages
    url = d.get('url')
    if url:
        cite += ' | پیوند=' + url
    archive_url = d.get('archive-url')
    if archive_url:
        cite += (' | پیوند بایگانی=' + archive_url + ' | تاریخ بایگانی=' +
                 d['archive-date'].isoformat() + ' | پیوند مرده=' +
                 ('آری' if d['dead-url'] == 'yes' else 'نه'))
    doi = d.get('doi')
    if doi:
        cite += ' | doi=' + doi
    language = d.get('language')
    if language:
        if type_ == 'web':
            cite += ' | کد زبان=' + language
        else:
            cite += ' | زبان=' + language
        sfn += ' | زبان=' + language
    if pages:
        sfn += ' | ص=' + pages
    # Seed the random generator before adding today's date.
    randseed(cite)
    ref_name = (
        randchoice(ascii_lowercase)  # it should contain at least one non-digit
        + ''.join(randchoice(lower_alpha_digits) for _ in range(4)))
    if url:
        cite += ' | تاریخ بازبینی=' + date.today().isoformat()
    else:
        sfn += ' | ص='
    cite += '}}'
    sfn += '}}\u200F&lt;/ref&gt;'
    # Finally create the ref tag.
    ref = cite[2:]
    if pages and ' | صفحه=' not in ref:
        ref = ref[:-2] + ' | صفحه=' + pages + '}}'
    elif not url:
        ref = ref[:-2] + ' | صفحه=}}'
    ref = '&lt;ref name="' + ref_name + '"&gt;' + ref + '\u200F&lt;/ref&gt;'
    return cite, sfn, ref
Beispiel #9
0
def main(argv=None):
    randseed(SEED)

    program_name = os.path.basename(sys.argv[0])
    program_version = "%s" % __version__
    program_build_date = "%s" % __updated__
    program_version_string = "%%prog %s (%s)" % (program_version,
                                                 program_build_date)
    # optional - give further explanation about what the program does
    program_longdesc = ''''''
    # optional - give further explanation about what the program does
    program_desc = ''''''
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string,
                              epilog=program_longdesc,
                              description=program_desc,
                              option_class=DatetimeOption)
        parser.add_option("--host",
                          dest="host",
                          help="hostname or IP address of the MongoDB server "
                          "[default: %default]")
        parser.add_option("-p",
                          "--port",
                          dest="port",
                          type="int",
                          help="port number on which to connect "
                          "[default: %default]")
        parser.add_option("-s",
                          "--system",
                          dest="systems",
                          action="append",
                          help="system(s) to create data for [default: none]",
                          metavar="NAME")
        parser.add_option("-n",
                          "--nprops",
                          dest="n_props",
                          type="int",
                          help="approx. integral number of properties to "
                          "create data for [default: %default] if, "
                          "no system is specified")
        parser.add_option("-b",
                          "--begin",
                          dest="begin",
                          type="datetime",
                          help="start date to create data from "
                          "[default: %default]",
                          metavar="DATE")
        parser.add_option("-d",
                          "--days",
                          dest="days",
                          type="int",
                          help="days that are added to 'begin' "
                          "to determine the stop date [default: %default]")
        parser.add_option("--chunksize",
                          dest="chunk_size",
                          type="int",
                          help="chunk size in seconds [default: %default]",
                          metavar="SECONDS")
        parser.add_option("--realtime",
                          dest="realtime",
                          action="store_true",
                          help="run data generation in realtime")

        # set defaults
        parser.set_defaults(host=HOST,
                            port=27017,
                            n_props=15000,
                            begin="2013-10-01",
                            days=1,
                            chunk_size=60,
                            realtime=False)

        # process options
        (opts, args) = parser.parse_args(argv)
        end = opts.begin + timedelta(days=opts.days)
        chunk_size = timedelta(seconds=opts.chunk_size)

        print "-" * 40
        print "host = %s" % (opts.host, )
        print "port = %d" % (opts.port, )
        if opts.systems:
            print "systems = %s" % (", ".join(opts.systems), )
        else:
            print "nprops = %d" % (opts.n_props, )
        print "begin = %s" % (str(opts.begin), )
        print "end = %s" % (str(end), )
        print "chunksize = %s" % (str(chunk_size), )
        if opts.realtime:
            print "realtime generation"

        # connect to db server, db and collections
        client = MongoClient(opts.host, opts.port)
        db = client.ctamonitoringtest
        chunks_collection = db.chunks
        properties_collection = db.properties
        statistics_collection = db.statistics
        systems_collection = db.systems

        system_locks = []
        try:
            # prepare data creation
            print "-" * 40
            acquire_systems(systems_collection, system_locks, opts.systems,
                            properties_collection, opts.n_props)
            properties, first_bin = acquire_properties(system_locks,
                                                       properties_collection,
                                                       opts.begin,
                                                       chunks_collection,
                                                       chunk_size)
            if properties:
                print "-" * 40
                print "nprops = %d" % (len(properties), )
                print "firstbin = %s" % (str(first_bin), )
                bin = first_bin
                statistics = Statistics()
                statistics.systems = [s["name"] for s in system_locks]
                statistics.n_props = len(properties)
                statistics.realtime = opts.realtime
                queue = Queue.Queue(3 * len(properties))
                wait = 10
                if not opts.realtime:
                    db_inserter = DBInserter(statistics_collection,
                                             chunks_collection, statistics,
                                             queue)
                else:
                    queue_out = Queue.Queue(math.ceil(1.1 * len(properties)))
                    db_scheduler = DBScheduler(queue_out, queue, chunk_size)
                    db_inserter = DBInserter(statistics_collection,
                                             chunks_collection, statistics,
                                             queue_out)
                    wait = max(wait,
                               math.ceil(1.1 * get_total_seconds(chunk_size)))
                while bin < end:
                    for prop in properties:
                        if prop.nxt_bin > bin:
                            continue
                        prop.nxt_bin = bin + chunk_size
                        values = []
                        t = prop.lst_end
                        while True:
                            t += prop.period
                            if t >= prop.nxt_bin:
                                break
                            val = uniform(prop.min, prop.max)
                            values.append({"t": t, "val": val})
                        if not values:
                            continue
                        prop.lst_end = values[-1]["t"]
                        chunk = {
                            "begin": values[0]["t"],
                            "end": prop.lst_end,
                            "values": values,
                            "bin": bin,
                            "pid": prop.pid
                        }
                        while True:
                            try:
                                queue.put((bin, chunk, len(values)),
                                          block=True,
                                          timeout=wait)
                                break
                            except Queue.Full:
                                if (opts.realtime
                                        and not db_scheduler.is_alive()):
                                    raise
                                if not db_inserter.is_alive():
                                    raise
                    bin += chunk_size
                print "-" * 40
                print "flushing..."
                if opts.realtime:
                    db_scheduler.flush()
                queue.join()
        finally:
            print "-" * 40
            release_systems(systems_collection, system_locks)
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help\n")
        return 2
Beispiel #10
0
    def make_map(self,
                 player,
                 entities,
                 *args,
                 max_rooms=30,
                 room_min_size=6,
                 room_max_size=10,
                 ratio_vh=1,
                 ratio_hv=1,
                 ratio_d=0,
                 max_monsters_per_room=0,
                 **kwargs):
        # setup
        map_width = self.width
        map_height = self.height
        randseed(self.seed)

        # create a map of randomly placed rooms
        rooms = []
        num_rooms = 0

        for r in range(max_rooms):
            # random width and height
            w = randint(room_min_size, room_max_size)
            h = randint(room_min_size, room_max_size)
            # random position inside map bounds
            x = randint(1, map_width - w - 2)
            y = randint(1, map_height - h - 2)

            # "Rect" class makes rectangles easier to work with
            new_room = Rect(x, y, w, h)

            # see if any other rooms intersect with this one
            for other_room in rooms:
                if (new_room.intersect(other_room)
                        or new_room.adjacent_ortho(other_room)):
                    break
            else:
                # no intersections, so this room is valid

                # "paint" it to the map's tiles
                self.create_room(new_room)

                # center coordinates of new room, will be useful later
                (new_x, new_y) = new_room.center()

                if num_rooms == 0:
                    # this is the first room, player starts here
                    player.x = new_x
                    player.y = new_y
                    entities[1].x = new_x + 1
                    entities[1].y = new_y
                else:
                    # all rooms after the first:
                    #  connect it to the previous room with a tunnel

                    # center coordinates of previous room
                    (prev_x, prev_y) = rooms[num_rooms - 1].center()

                    # generate corridors depending on proportions passed into
                    #   make_map function
                    randpool = ratio_hv + ratio_vh + ratio_d
                    hv = ratio_hv
                    vh = ratio_hv + ratio_vh
                    roll = uniform(0, randpool)
                    if roll < hv:
                        # first move horizontally, then vertically
                        self.create_h_tunnel(prev_x, new_x, prev_y)
                        self.create_v_tunnel(prev_y, new_y, new_x)
                    elif roll < vh:
                        # first move vertically, then horizontally
                        self.create_v_tunnel(prev_y, new_y, prev_x)
                        self.create_h_tunnel(prev_x, new_x, new_y)
                    else:
                        # draw diagonal hallways
                        self.create_d_tunnel(prev_x, prev_y, new_x, new_y)

                # finally, append the new room to the list
                rooms.append(new_room)
                num_rooms += 1

        # save our list of rooms for later
        self.rooms = rooms

        # place monsters
        for room in self.rooms:
            self.place_entities(room, entities, max_monsters_per_room)
Beispiel #11
0
from matplotlib import pyplot as plt
from math import sin
from math import pi
from math import ceil
from math import floor
from numpy import linspace
from SineFunction import SineFunction
from LinearFunction import LinearFunction
from StockFunction import StockFunction
from random import randint
from random import seed as randseed

randseed()


def append_interval(domain, codomain, StockFunctionInstance, start_int,
                    stop_int):
    i = start_int
    while i < stop_int:
        result = StockFunctionInstance.Compute(domain[i])
        codomain.append(result)
        i = i + 1
    return


def algorithm(Max, Piece, domain, codomain, Stocks):
    Upper_Bound = 10
    Lower_Bound = 0
    i = 0
    max_slope = 0
    min_slope = 0
Beispiel #12
0
def set_seed(args):
    randseed(args.seed)
    seed(args.seed)
    torch.manual_seed(args.seed)
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)
def main(argv=None):
    randseed(SEED)

    program_name = os.path.basename(sys.argv[0])
    program_version = "%s" % __version__
    program_build_date = "%s" % __updated__
    program_version_string = "%%prog %s (%s)" % (program_version,
                                                 program_build_date)
    # optional - give further explanation about what the program does
    program_longdesc = ''''''
    # optional - give further explanation about what the program does
    program_desc = ''''''
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string,
                              epilog=program_longdesc,
                              description=program_desc)
        parser.add_option("--host",
                          dest="host",
                          help="hostname or IP address of the MongoDB server "
                          "[default: %default]")
        parser.add_option("-p",
                          "--port",
                          dest="port",
                          type="int",
                          help="port number on which to connect "
                          "[default: %default]")

        # set defaults
        parser.set_defaults(host=HOST, port=27017)

        # process options
        (opts, args) = parser.parse_args(argv)

        print("-" * 40)
        print("host = %s" % (opts.host, ))
        print("port = %d" % (opts.port, ))

        # connect to db server, db and collections
        client = MongoClient(opts.host, opts.port)
        db = client.ctamonitoringtest
        systems_collection = db.systems
        systems_collection.update_many(
            {"$and": [{
                "lock": {
                    "$exists": True
                }
            }, {
                "lock": {
                    "$ne": None
                }
            }]}, {"$set": {
                "lock": None,
                "random": random()
            }})
    except Exception as e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help\n")
        return 2
Beispiel #14
0
def sfn_cit_ref(d: defaultdict) -> tuple:
    """Create citation templates using the given dictionary."""
    cite_type = TYPE_TO_CITE(d['cite_type'])
    if not cite_type:
        logger.warning('Unknown citation type: %s, d: %s', cite_type, d)
        cite_type = ''
    if cite_type in ('کتاب', 'ژورنال', 'وب'):
        cit = '* {{یادکرد ' + cite_type
    else:
        return en_citations(d)

    authors = d['authors']
    if authors:
        cit += names2para(authors, 'نام', 'نام خانوادگی', 'نویسنده')
        sfn = '&lt;ref&gt;{{پک'
        for first, last in authors[:4]:
            sfn += ' | ' + last
    else:
        sfn = '&lt;ref&gt;{{پک/بن'

    editors = d['editors']
    if editors:
        cit += names2para(
            editors, 'نام ویراستار', 'نام خانوادگی ویراستار', 'ویراستار'
        )

    translators = d['translators']
    if translators:
        cit += names1para(translators, 'ترجمه')

    others = d['others']
    if others:
        cit += names1para(others, 'دیگران')

    year = d['year']
    if year:
        sfn += ' | ' + year

    if cite_type == 'book':
        booktitle = d['booktitle'] or d['container-title']
    else:
        booktitle = None

    title = d['title']
    if booktitle:
        cit += ' | عنوان=' + booktitle
        if title:
            cit += ' | فصل=' + title
    elif title:
        cit += ' | عنوان=' + title
        sfn += ' | ک=' + d['title']

    if cite_type == 'ژورنال':
        journal = d['journal'] or d['container-title']
    else:
        journal = d['journal']

    if journal:
        cit += ' | ژورنال=' + journal
    else:
        website = d['website']
        if website:
            cit += ' | وب‌گاه=' + website

    chapter = d['chapter']
    if chapter:
        cit += ' | فصل=' + chapter

    publisher = d['publisher'] or d['organization']
    if publisher:
        cit += ' | ناشر=' + publisher

    address = d['address'] or d['publisher-location']
    if address:
        cit += ' | مکان=' + address

    edition = d['edition']
    if edition:
        cit += ' | ویرایش=' + edition

    series = d['series']
    if series:
        cit += ' | سری=' + series

    volume = d['volume']
    if volume:
        cit += ' | جلد=' + volume

    issue = d['issue'] or d['number']
    if issue:
        cit += ' | شماره=' + issue

    ddate = d['date']
    if ddate:
        if isinstance(ddate, str):
            cit += ' | تاریخ=' + ddate
        else:
            cit += ' | تاریخ=' + date.isoformat(ddate)

    if year:
        cit += ' | سال=' + year

    month = d['month']
    if month:
        cit += ' | ماه=' + month

    isbn = d['isbn']
    if isbn:
        cit += ' | شابک=' + isbn

    issn = d['issn']
    if issn:
        cit += ' | issn=' + issn

    pmid = d['pmid']
    if pmid:
        cit += ' | pmid=' + pmid

    pmcid = d['pmcid']
    if pmcid:
        cit += ' | pmc=' + pmcid

    doi = d['doi']
    if doi:
        cit += ' | doi=' + doi

    oclc = d['oclc']
    if oclc:
        cit += ' | oclc=' + oclc

    pages = d['page']
    if cite_type == 'ژورنال':
        if pages:
            cit += ' | صفحه=' + pages

    url = d['url']
    if url:
        # Don't add a DOI URL if we already have added a DOI.
        if not doi or not DOI_URL_MATCH(url):
            cit += ' | پیوند=' + url
        else:
            # To prevent addition of access date
            url = None

    archive_url = d['archive-url']
    if archive_url:
        cit += (
            ' | پیوند بایگانی=' + archive_url +
            ' | تاریخ بایگانی=' + d['archive-date'].isoformat() +
            ' | پیوند مرده=' + ('آری' if d['dead-url'] == 'yes' else 'نه')
        )

    language = d['language']
    if language:
        language = TO_TWO_LETTER_CODE(language.lower(), language)
        if cite_type == 'وب':
            cit += ' | کد زبان=' + language
        else:
            cit += ' | زبان=' + language
        sfn += ' | زبان=' + language

    if pages:
        sfn += ' | ص=' + pages
    # Seed the random generator before adding today's date.
    randseed(cit)
    ref_name = (
        randchoice(ascii_lowercase)  # it should contain at least one non-digit
        + ''.join(randchoice(LOWER_ALPHA_DIGITS) for _ in range(4))
    )
    if url:
        cit += ' | تاریخ بازبینی=' + date.today().isoformat()

    if not pages and cite_type != 'وب':
        sfn += ' | ص='

    cit += '}}'
    sfn += '}}\u200F&lt;/ref&gt;'
    # Finally create the ref tag.
    ref = cit[2:]
    if pages and ' | صفحه=' not in ref:
        ref = ref[:-2] + ' | صفحه=' + pages + '}}'
    elif not url:
        ref = ref[:-2] + ' | صفحه=}}'
    ref = '&lt;ref name="' + ref_name + '"&gt;' + ref + '\u200F&lt;/ref&gt;'
    return sfn, cit, ref