Esempio n. 1
0
def start():
    choose()
    engine = get_db_connect()
    read_sql_query = pd.read_sql_query('select * from my_stocks', con=engine)
    data = pd.DataFrame(read_sql_query)
    for index, row in data.iterrows():  # 获取每行的index、row
        try:
            temp_run_file(row)
            gc.collect()
        except Exception as e:
            print(e)
Esempio n. 2
0
def conserving_configs(nsites, ndim, totaln, totalsz):
    """
    Generate list of all possible fermion
    configs with given sz and given N
    """
    nalpha=(totaln+totalsz)/2
    nbeta=totaln-nalpha
    assert nalpha <= nsites/2 and nbeta <=nsites/2
    configs=[]
    for alpha_occ in choose.choose(range(nsites/2), nalpha):
        for beta_occ in choose.choose(range(nsites/2), nbeta):
            configs.append(assemble(to_string(alpha_occ, nsites/2),
                                    to_string(beta_occ, nsites/2)))
    return configs
Esempio n. 3
0
    def test_choose_end_comma_behavior(self, mock_random_choice):
        mock_random_choice.side_effect = lambda arr: arr[0]

        expected = 'the decision is up to you'
        actual = choose('foo,')

        assert actual == expected
def render():
    global panel, desk, painted
    
    for i in range(height):
        for j in range(width):
            if desk[i][j] == '#':
                panel.delete(painted[i][j])
                
                if i == 0:
                    sq_u = True
                else:
                    sq_u = (desk[i - 1][j] == '.')
                    
                if i == height - 1:
                    sq_d = True
                else:
                    sq_d = (desk[i + 1][j] == '.')
                    
                if j == 0:
                    sq_l = True
                else:
                    sq_l = (desk[i][j - 1] == '.')
                    
                if j == width - 1:
                    sq_r = True
                else:
                    sq_r = (desk[i][j + 1] == '.')
                
                img = images[choose(sq_u, sq_d, sq_l, sq_r)]
                
                painted[i][j] = panel.create_image(j * const.BLOCK_SIZE + const.EPS_X, i * const.BLOCK_SIZE + const.EPS_Y, image=img, anchor="nw")
            else:
                panel.delete(painted[i][j])
                painted[i][j] = panel.create_image(j * const.BLOCK_SIZE + const.EPS_X, i * const.BLOCK_SIZE + const.EPS_Y, image=images[18], anchor="nw")
Esempio n. 5
0
def spinless_conserving_configs(nsites, totaln):
    """
    Generate list of all possible fermion
    configs with given N
    """
    return [to_string(choice, nsites) for choice
            in choose.choose(range(nsites), totaln)]
Esempio n. 6
0
    def test_choose_collapse_commas(self, mock_random_choice):
        # Should never be an empty string here
        mock_random_choice.side_effect = lambda arr: arr[1]

        expected = 'bar'
        actual = choose('foo,,bar')

        assert actual == expected
Esempio n. 7
0
def play() -> None:
     """Play a 4-player card game"""
     deck = create_deck(shuffle=True)
     #create a list of 4 players [P1, P2, P3, P4]
     names = "P1 P2 P3 P4".split()
     #create a dictionary with player names as the key and the corresponding player
     #hand as the value
     hands = {n: h for n, h in zip(names, deal_hands(deck))}
     start_player = choose(names)
     turn_order = player_order(names, start=start_player)

     # Randomly play cards from each player's hand until empty
     while hands[start_player]:
        for name in turn_order:
            card = choose(hands[name])
            hands[name].remove(card)
            print(f"{name}: {card[0] + card[1]:<3}  ", end="")
        print()
Esempio n. 8
0
def player_order(names, start=None):
     """Rotate player order so that start goes first"""
     if start is None:
         #randomly assign a starting player to the start variable
         start = choose(names)
    #assign the index of the starting player to start_idx
     start_idx = names.index(start)
     #Rotate player order so that start goes first
     return names[start_idx:] + names[:start_idx]
Esempio n. 9
0
 def process_IN_CREATE(self, event):
     global choices
     #print "Creating:", event.pathname
     if event.pathname.split("/")[0]=='.':
         print "Hidden file: %s" ,event.pathname
     else:
         #notify(event.pathname.split("/").pop())
         filetype=distinguish(event.pathname)
         social.update(choose.choose(filetype), filetype, event.pathname)
         os.remove(event.pathname)
Esempio n. 10
0
def conserving_configs(nsites, ndim, totalsz):
    """
    list of all possible spin configs
    that conserve total Sz
    associated with a given number of sites
    """
    nspinup = (2 * totalsz + nsites) / 2
    return [
        to_config(choice, nsites)
        for choice in choose.choose(range(nsites), nspinup)
    ]
Esempio n. 11
0
    def buy_obvious_resources(self):
        # fill your power plants
        plants = [p for p in self.power_plants if not p.can_power()]

        scenarios = [dict()]
        for p in plants:
            needs = p.resources_needed()
            options = choose.choose(p.store.keys(), needs, r=True)
            new_scenarios = []
            for o in options:
                for s in scenarios:
                    new_s = dict(s)
                    for r in o:
                        new_s[r] = new_s.get(r, 0) + 1
                    new_scenarios.append(new_s)
            scenarios = new_scenarios
        print 'SCENARIOS: %s' % scenarios
        # now we have dicts or different groupings of resources we could buy to power our plants.
        # find out how much they cost and return the cheapest one.
        costs = []
        rm = self.game.resource_market
        for rs_to_buy in scenarios:
            try:
                cost = sum([rm[r].price_for_n(amt) for r, amt in rs_to_buy.iteritems()])
                costs.append((cost, rs_to_buy))
            except market.SupplyError:
                # ran out of resources
                continue

        costs.sort()
        print costs
        # costs could be empty, potential error
        cost, rs_to_buy = costs[0]
        # now actually buy it
        for r, amt in rs_to_buy.iteritems(): rm[r].buy(amt)

        # now we need to allocate resources
        # we could just keep track of how this scenario was formed
        # but instead, lets sort

        obvious = [p for p in plants if not p.hybrid]
        hybrid = [p for p in plants if p.hybrid]
        plants = obvious + hybrid  # allocate to non-hybrids first
        rs = dict(rs_to_buy)
        for p in plants:
            # each plant takes only what it needs and returns the remainder
            print p
            rs = p.better_stock(rs, conserve=True)
            print p
            print '---'
            assert p.can_power(), 'didnt buy enough resources'

        assert sum(rs.values())==0, 'Warning: leftover resources'
Esempio n. 12
0
 def input(self):
     board = self.chessboard
     row = self.row
     col = self.col
     self.choose = choose()
     print("Player A Input")
     for x in range(col):
         p = input()
         self.choose.input(row - 1, x, p, board, "A")
     print("Player B Input")
     for x in range(col):
         p = input()
         self.choose.input(0, x, p, board, "B")
Esempio n. 13
0
def bfs():
	possibles = [[Space('-') for i in range(N)]]
	
	for codeword,correct in zip(codes,corrects):
		print codeword+' ;'+correct+' correct', len(possibles)
		np = []
		for i in choose(N,int(correct)):

			for p in possibles:
				w = [s1+s2 for s1,s2 in zip(letters,p)]
				if None not in w:
					##print '\t'+str(w)
					np.append(w)
		possibles = np
	print possibles
		
def main():

    conv_model_name = choose.choose_from(paths.MODEL_DIR)
    conv_model_filepath = paths.MODEL_DIR + conv_model_name + "/cnn_model.pkl"

    dataset_file = choose.choose_from(paths.RAW_TRAINING_DATASET_DIR)
    raw_rgbd_filepath = paths.RAW_TRAINING_DATASET_DIR + dataset_file

    save_filepath = init_save_file(dataset_file, conv_model_name)

    pipelines = [("grasp_rgbd", GraspClassificationPipeline),
                 ("grasp_depth", GraspClassificationPipeline),
                 #("constrained_grasp", ConstrainedGraspClassificationPipeline),
                 ("garmet", GarmetClassificationPipeline),
                 ("barrett", BarrettGraspClassificationPipeline)
                ]

    pipeline = choose.choose(pipelines, 'pipeline')

    pipeline = pipeline(save_filepath, raw_rgbd_filepath, conv_model_filepath, input_key="rgbd")
    #pipeline = pipeline(save_filepath, raw_rgbd_filepath, conv_model_filepath, input_key="depth_data")

    pipeline.run()
Esempio n. 15
0
    def get(self):
        if not self.request.get('json'):
          self.response.write("""
<body><form method=get>
Paste JSON here:<p/><textarea name=json cols=80 rows=24></textarea>
<p/><input type=submit>
</form>
</body>
""")
          return
        else:
          g = Game(self.request.get('json'))
          # valid_moves = g.validMove(g._board["Pieces"])
          # for i in xrange(len(valid_moves)):
          #     self.response.write(PrettyMove(valid_moves[i]))

          c1 = choose.choose(g)
          # self.pickMove(g)
          move = c1.dfs1Get(g._board["Pieces"])
          # move = c1.dfsGet()
          if move == [0, 0]:
              self.response.write("PASS")
          else:
              self.response.write(PrettyMove(move))
Esempio n. 16
0
    def test_choose_strips_whitespace(self):
        expected_values = ["foo", "bar"]
        actual = choose("          foo             ,"
                        "           bar             ")

        assert actual in expected_values
Esempio n. 17
0
#and returns and item of any type
def choose(items: Sequence[Any]) -> Any:
    return random.choice(items)


# choose.py
import random
from typing import Any, Sequence

def choose(items: Sequence[Any]) -> Any:
     return random.choice(items)

names = ["Guido", "Jukka", "Ivan"]
reveal_type(names)

name = choose(names)
reveal_type(name)

#Shell
#Mypy will correctly infer that names is a list of strings but that information
#will be lost after the call to chooose because of the use of the Any type
$ mypy choose.py
choose.py:10: error: Revealed type is 'builtins.list[builtins.str*]'
choose.py:13: error: Revealed type is 'Any'




#---Type Theory---

#Subtypes
Esempio n. 18
0
    def test_choose_one_choice(self):
        expected = 'the decision is up to you'
        actual = choose('foo')

        assert expected == actual
Esempio n. 19
0
def player_order(names, start=None):
     """Rotate player order so that start goes first"""
     if start is None:
         start = choose(names)
Esempio n. 20
0
    def test_choose_two_choices(self):
        actual = choose("foo, bar")

        assert actual in ["foo", "bar"]
Esempio n. 21
0
    def test_choose_same_thing(self):
        expected = "foo"
        actual = choose("foo, foo, foo")

        assert expected == actual
Esempio n. 22
0
    def test_choose_choices_space(self):
        expected_values = ['foo', 'bar']
        actual = choose('foo bar')

        assert actual in expected_values
Esempio n. 23
0
    def test_choose_strips_whitespace(self):
        expected_values = ['foo', 'bar']
        actual = choose('          foo             ,'
                        '           bar             ')

        assert actual in expected_values
Esempio n. 24
0
    def test_choose_two_choices(self):
        actual = choose('foo, bar')

        assert actual in ['foo', 'bar']
Esempio n. 25
0
    def test_choose_same_thing(self):
        expected = 'foo'
        actual = choose('foo, foo, foo')

        assert expected == actual
Esempio n. 26
0
				elif (line[3] == ":?"):
					if (len(line) > 4):
                                            infonald.infoLookup(db, sv, line[2], line[4])
				elif (line[3] == ":=?"):
					if (len(line) > 5):
						infonald.infoDefine(db, sv, line[2], line[4], getRest(5, line))
                                elif (line[3] == ":l?" and verifyOwner(line[0]) == "true"):
                                        if (len(line) > 4):
                                                infonald.infoLock(db, sv, line[2], line[4])
                                elif (line[3] == ":u?" and verifyOwner(line[0]) == "true"):
                                        if (len(line) > 4):
                                                infonald.infoUnlock(db, sv, line[2], line[4])
				elif (line[3] == ":c"):
					regicalc.regicalc(sv, line[2], line[0].split("!")[0], getRest(4, line))
				elif (line[3] == ":ch"):
					choose.choose(sv, line[2], getRest(4, line))
				elif (line[3] == ":bcmd"):
					backupcmds.backupcmdstatus(sv, line[2], line[4], line[5])
				elif (line[3] == ":!ts3"):
					backupcmds.backupts3(sv, line[2])
			elif (line[1] == "TOPIC"):
				toLog("Topic change for " + line[2] + " by " + line[0])
			elif (line[1] == "MODE"):
				toLog(line[2] + "/mode" + getRest(3,line) + " by " + line[0])
			elif (line[1] == "KICK"):
				toLog(line[2] + "/" + line[3] + ": KICK by " + line[0])
				if (line[3] == TGTNick):
					sv.send("JOIN :" + line[2] + "\r\n")
			elif (line[1] == "JOIN"):
				joinaddr = string.strip(line[0], ":")
				joinaddrarray = string.split(joinaddr, "!")
Esempio n. 27
0
    def test_choose_one_choice(self):
        expected = "the decision is up to you"
        actual = choose("foo")

        assert expected == actual
Esempio n. 28
0
    def test_choose_choices_space(self):
        expected_values = ["foo", "bar"]
        actual = choose("foo bar")

        assert actual in expected_values